hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 98
values | lang stringclasses 21
values | max_stars_repo_path stringlengths 3 945 | max_stars_repo_name stringlengths 4 118 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 368k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 945 | max_issues_repo_name stringlengths 4 118 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 945 | max_forks_repo_name stringlengths 4 135 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1 1.03M | max_line_length int64 2 1.03M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7531574ddee2b20a358f920cbb64b09119cd233e | 1,624 | c | C | worksheet3/computeCellValues.c | nasay/cfdlab | 6fae95b8f926609b0c8643d31d5f2a2858ee3f71 | [
"MIT"
] | 1 | 2020-01-11T17:50:18.000Z | 2020-01-11T17:50:18.000Z | worksheet3/computeCellValues.c | nasay/cfdlab | 6fae95b8f926609b0c8643d31d5f2a2858ee3f71 | [
"MIT"
] | null | null | null | worksheet3/computeCellValues.c | nasay/cfdlab | 6fae95b8f926609b0c8643d31d5f2a2858ee3f71 | [
"MIT"
] | null | null | null | #include "LBDefinitions.h"
#include "computeCellValues.h"
#include <stdio.h>
void computeDensity(const double *const currentCell, double *density){
/*
* Computes the macroscopic density within currentCell
* rho(x,t) = sum(f_i, i=0:Q-1)
*/
int i;
*density = 0;
for (i=0; i<Q; i++) {
*density += currentCell[i];
}
}
void computeVelocity(const double * const currentCell, const double * const density, double *velocity){
/*
* Computes the velocity within currentCell
* u(x,t) = sum(f[i] * c[i] for i in [0:Q-1]) / rho
*/
int i,j;
for (j=0; j<3; j++) {
velocity[j] = 0;
for (i=0; i<Q; i++) {
velocity[j] += LATTICEVELOCITIES[i][j] * currentCell[i];
}
velocity[j] /= *density;
}
}
void computeFeq(const double * const density, const double * const velocity, double *feq){
/*
* feq[i] = w[i] * rho * (1 + c_i*u / (c_s^2) + ...
*/
int i;
double ci_dot_u, u_dot_u;
double ci0, ci1, ci2, u0, u1, u2;
double cs2 = C_S * C_S;
for (i=0; i<Q; i++) {
ci0 = LATTICEVELOCITIES[i][0];
ci1 = LATTICEVELOCITIES[i][1];
ci2 = LATTICEVELOCITIES[i][2];
u0 = velocity[0];
u1 = velocity[1];
u2 = velocity[2];
ci_dot_u = ci0*u0 + ci1*u1 + ci2*u2;
u_dot_u = u0*u0 + u1*u1 + u2*u2;
feq[i] = 1;
feq[i] += ci_dot_u/cs2;
feq[i] += (ci_dot_u * ci_dot_u) / (2 * cs2 * cs2);
feq[i] -= u_dot_u / (2 * cs2);
feq[i] *= *density;
feq[i] *= LATTICEWEIGHTS[i];
}
}
| 24.238806 | 103 | 0.514163 |
4c279ad358db915299e0bddea59ec449560ed7b5 | 565 | php | PHP | src/Application/Command/Publication/Delete/CommandHandler.php | szymach/talesweaver | a19a6bf1580d70d8063dc420ce4d3438c29a6ebc | [
"MIT"
] | null | null | null | src/Application/Command/Publication/Delete/CommandHandler.php | szymach/talesweaver | a19a6bf1580d70d8063dc420ce4d3438c29a6ebc | [
"MIT"
] | 18 | 2015-12-31T20:23:19.000Z | 2021-03-09T01:54:11.000Z | src/Application/Command/Publication/Delete/CommandHandler.php | szymach/talesweaver | a19a6bf1580d70d8063dc420ce4d3438c29a6ebc | [
"MIT"
] | null | null | null | <?php
declare(strict_types=1);
namespace Talesweaver\Application\Command\Publication\Delete;
use Talesweaver\Application\Bus\CommandHandlerInterface;
use Talesweaver\Domain\Publications;
final class CommandHandler implements CommandHandlerInterface
{
/**
* @var Publications
*/
private $publications;
public function __construct(Publications $publications)
{
$this->publications = $publications;
}
public function __invoke(Command $command): void
{
$this->publications->remove($command->getId());
}
}
| 20.925926 | 61 | 0.713274 |
209c458bd50fbd40c5a607b4d8188c4d27d838d7 | 2,821 | css | CSS | assets/fonts/fonts.css | KirillZamotaev/SIGMAPOOL | 26e01d1eaf8b9f68a1a59c29a56f45e8e46291ef | [
"MIT"
] | null | null | null | assets/fonts/fonts.css | KirillZamotaev/SIGMAPOOL | 26e01d1eaf8b9f68a1a59c29a56f45e8e46291ef | [
"MIT"
] | null | null | null | assets/fonts/fonts.css | KirillZamotaev/SIGMAPOOL | 26e01d1eaf8b9f68a1a59c29a56f45e8e46291ef | [
"MIT"
] | null | null | null | @font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-MediumItalic.woff2') format('woff2'),
url('~assets/fonts/GothamPro-MediumItalic.woff') format('woff');
font-weight: 500;
font-style: italic;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-Black.woff2') format('woff2'),
url('~assets/fonts/GothamPro-Black.woff') format('woff');
font-weight: 900;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-BlackItalic.woff2') format('woff2'),
url('~assets/fonts/GothamPro-BlackItalic.woff') format('woff');
font-weight: 900;
font-style: italic;
}
@font-face {
font-family: 'Gotham Pro Narrow';
src: url('~assets/fonts/GothamProNarrow-Medium.woff2') format('woff2'),
url('~assets/fonts/GothamProNarrow-Medium.woff') format('woff');
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro Narrow';
src: url('~assets/fonts/GothamProNarrow-Bold.woff2') format('woff2'),
url('~assets/fonts/GothamProNarrow-Bold.woff') format('woff');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro.woff2') format('woff2'),
url('~assets/fonts/GothamPro.woff') format('woff');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-BoldItalic.woff2') format('woff2'),
url('~assets/fonts/GothamPro-BoldItalic.woff') format('woff');
font-weight: bold;
font-style: italic;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-Bold.woff2') format('woff2'),
url('~assets/fonts/GothamPro-Bold.woff') format('woff');
font-weight: bold;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-Medium.woff2') format('woff2'),
url('~assets/fonts/GothamPro-Medium.woff') format('woff');
font-weight: 500;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-LightItalic.woff2') format('woff2'),
url('~assets/fonts/GothamPro-LightItalic.woff') format('woff');
font-weight: 300;
font-style: italic;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-Light.woff2') format('woff2'),
url('~assets/fonts/GothamPro-Light.woff') format('woff');
font-weight: 300;
font-style: normal;
}
@font-face {
font-family: 'Gotham Pro';
src: url('~assets/fonts/GothamPro-Italic.woff2') format('woff2'),
url('~assets/fonts/GothamPro-Italic.woff') format('woff');
font-weight: normal;
font-style: italic;
}
| 29.082474 | 75 | 0.64268 |
74d26df4c21cf05f356da782ac79d321822a4702 | 569 | js | JavaScript | frontend/app/pods/survey-templates/record/questions/new/route.js | wildnote/hanuman | c72883c0d5afe34a3b3793ca0987680891eb2ad7 | [
"MIT"
] | 4 | 2018-11-14T00:41:33.000Z | 2019-06-22T12:36:25.000Z | frontend/app/pods/survey-templates/record/questions/new/route.js | wildnote/hanuman | c72883c0d5afe34a3b3793ca0987680891eb2ad7 | [
"MIT"
] | 19 | 2018-12-20T17:14:06.000Z | 2022-02-21T21:40:32.000Z | frontend/app/pods/survey-templates/record/questions/new/route.js | wildnote/hanuman | c72883c0d5afe34a3b3793ca0987680891eb2ad7 | [
"MIT"
] | 2 | 2018-06-07T08:08:40.000Z | 2020-04-28T09:55:03.000Z | import { hash } from 'rsvp';
import Route from '@ember/routing/route';
export default Route.extend({
model() {
let surveyTemplate = this.modelFor('survey-templates.record');
return hash({
question: this.store.createRecord('question', { surveyTemplate }),
questions: surveyTemplate.get('questions'),
answerTypes: this.store.findAll('answer-type', { reload: true }),
dataSources: this.store.findAll('data-source'),
surveyTemplate
});
},
setupController(controller, models) {
controller.setProperties(models);
}
});
| 28.45 | 72 | 0.673111 |
2a012305bba84f016117bd736adf54c368d49073 | 1,552 | kt | Kotlin | WhatBreed/app/src/main/java/edu/fullerton/cpsc411/whatbreed/ResultsHistoryActivity.kt | andrewtgomez96/WhatBreedKotlin | 0b87ad0f26d5511a6386b5b4ac54a33bde9f05b1 | [
"MIT"
] | null | null | null | WhatBreed/app/src/main/java/edu/fullerton/cpsc411/whatbreed/ResultsHistoryActivity.kt | andrewtgomez96/WhatBreedKotlin | 0b87ad0f26d5511a6386b5b4ac54a33bde9f05b1 | [
"MIT"
] | null | null | null | WhatBreed/app/src/main/java/edu/fullerton/cpsc411/whatbreed/ResultsHistoryActivity.kt | andrewtgomez96/WhatBreedKotlin | 0b87ad0f26d5511a6386b5b4ac54a33bde9f05b1 | [
"MIT"
] | null | null | null | package edu.fullerton.cpsc411.whatbreed
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ArrayAdapter
import kotlinx.android.synthetic.main.activity_results_history.*
class ResultsHistoryActivity : AppCompatActivity() {
private var histdb: BreedResultDatabase? = null
private var resultDao: BreedResultDao? = null
var newBreedResult=BreedResult()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_results_history)
Thread {
histdb = BreedResultDatabase.getInstance(context = this)
resultDao = histdb?.BreedResultDao()
val breedList: List<BreedResult>? = resultDao?.getAllBreedResults()
var oneIndex: String = ""
val arrayConversion = arrayOfNulls<String>(breedList!!.size)
for(i in breedList!!.indices){
oneIndex += breedList.get(i).bresult
Log.d("results", breedList.get(i).bresult)
oneIndex += breedList.get(i).picPath
oneIndex += breedList.get(i).timeFound
Log.d("results", breedList.get(i).timeFound)
arrayConversion[i] = oneIndex
}
val adapter = ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
arrayConversion)
hist_listview.adapter = adapter
}.start()
}
}
| 32.333333 | 79 | 0.646907 |
f0e6473363d86fb57db200a794cd502a951cb906 | 237 | sql | SQL | admin/sql/triggers/on_delete_book.sql | power-cosmic/cosc571_database_project | accd8b1fe25acaf6be81ecd300ec030c558786e3 | [
"MIT"
] | 1 | 2015-02-02T19:36:36.000Z | 2015-02-02T19:36:36.000Z | admin/sql/triggers/on_delete_book.sql | power-cosmic/cosc571_database_project | accd8b1fe25acaf6be81ecd300ec030c558786e3 | [
"MIT"
] | 1 | 2015-09-18T18:59:14.000Z | 2015-09-18T18:59:14.000Z | admin/sql/triggers/on_delete_book.sql | power-cosmic/cosc571_database_project | accd8b1fe25acaf6be81ecd300ec030c558786e3 | [
"MIT"
] | null | null | null | DROP TRIGGER IF EXISTS on_delete_book;
DELIMITER $$
CREATE TRIGGER on_delete_book
AFTER DELETE
ON book
FOR EACH ROW
BEGIN
UPDATE publisher
SET num_books=num_books-1,
WHERE publisher.id=OLD.publisher_id;
END $$
DELIMITER ; | 16.928571 | 38 | 0.763713 |
dfee9db75c219da54d91b4ba89ef54abac375ce0 | 2,371 | ts | TypeScript | FoodDelivery Apps/code/client/src/app/app.component.ts | bahatteyoucef/Pfe_Final | cca912b247c0c66953f26386ef8eb2803a2a2e64 | [
"MIT"
] | null | null | null | FoodDelivery Apps/code/client/src/app/app.component.ts | bahatteyoucef/Pfe_Final | cca912b247c0c66953f26386ef8eb2803a2a2e64 | [
"MIT"
] | null | null | null | FoodDelivery Apps/code/client/src/app/app.component.ts | bahatteyoucef/Pfe_Final | cca912b247c0c66953f26386ef8eb2803a2a2e64 | [
"MIT"
] | null | null | null | import { Component, OnInit } from '@angular/core';
import { ServerService } from './service/server.service';
import { Platform, NavController } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { LocationAccuracy } from '@ionic-native/location-accuracy/ngx';
import { Storage } from '@ionic/storage';
import { take, map } from 'rxjs/operators';
import { isUndefined, isNumber, isNull } from 'util';
import { OneSignal } from '@ionic-native/onesignal/ngx';
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
GpsEnabled = false;
isLogged = false;
public selectedIndex = 0;
public appPages = [
{
title: 'home',
url: 'home',
icon: 'home'
},
{
title: 'Favorites',
url: 'favoris',
icon: 'heart'
},
{
title: 'Panier',
url: 'cart',
icon: 'cart'
},
{
title: 'Changer Adresse',
url: 'address',
icon: 'location'
},
{
title: 'Mes Commandes',
url: 'commandes',
icon: 'clipboard'
},
{
title: 'Profile',
url: 'profile',
icon: 'person'
},
]
constructor(
private platform: Platform,
public nav: NavController,
private splashScreen: SplashScreen,
private oneSignal: OneSignal,
private statusBar: StatusBar,
private storage: Storage,
private locationAccuracy: LocationAccuracy,
private server: ServerService
) {
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
// si client connecté redirect vers home sinon vers city pour saisir une adresse
this.storage.get('city').then((val) => {
// console.log(val);
if (isNull(val)) {
this.nav.navigateRoot('city')
console.log('city');
}
else {
this.nav.navigateRoot('home')
console.log('home');
}
});
this.statusBar.styleDefault();
this.statusBar.backgroundColorByHexString('#ffffff');
this.splashScreen.hide();
//this.askToTurnOnGPS();
});
}
// intilaisation de service onesignal de notification push
// se deconnecter
logout() {
this.server.logout();
}
} | 23.475248 | 86 | 0.601012 |
9bd0624921dce4030be6a08cbbdaa52b54e8f3ed | 2,591 | js | JavaScript | src/api/index.js | tiago7alves/rule-based-map-generator | b3bc8da406d7ae572b8661efca3479fa55db3848 | [
"MIT"
] | 7 | 2016-05-24T13:35:02.000Z | 2020-10-17T17:31:20.000Z | src/api/index.js | letiagoalves/rule-based-map-generator | b3bc8da406d7ae572b8661efca3479fa55db3848 | [
"MIT"
] | null | null | null | src/api/index.js | letiagoalves/rule-based-map-generator | b3bc8da406d7ae572b8661efca3479fa55db3848 | [
"MIT"
] | null | null | null | 'use strict';
var randomMatrix = require('random-matrix');
var Block = require('./../block');
var Connector = require('./../connector');
var World = require('./../world');
var WorldConstraints = require('./../world-constraints');
var strategies = require('./../strategies');
var Strategy = require('./../strategies/strategy.js');
var utils = require('./../utils/utils.js');
function getStrategyFactory(strategyName) {
if (strategies.hasOwnProperty(strategyName)) {
return strategies[strategyName];
}
throw new Error('Unknown strategy factory');
}
function createConnectorInstance(id, type, blockIds, blockClasses) {
return new Connector(id, type, blockIds, blockClasses);
}
function createBlockFactory(strategy) {
if (!utils.isInstanceOf(strategy, Strategy)) {
throw new Error('strategy is mandatory and must be a valid strategy');
}
return function createBlockInstance (id, classes, constraints) {
return new Block(strategy, id, classes, constraints);
};
}
function createWorldInstance(strategy, constraints, blocks) {
var areAllBlockInstances;
if (!utils.isInstanceOf(strategy, Strategy)) {
throw new Error('strategy is mandatory and must be a valid strategy');
}
if (!utils.isInstanceOf(constraints, WorldConstraints)) {
throw new Error('constraints is mandatory and must be a valid WorldConstraints instance');
}
// blocks validation
if (!Array.isArray(blocks) || blocks.length === 0) {
throw new Error('blocks is mandatory and must be a non-empty array');
}
areAllBlockInstances = blocks.every(function isBlockInstance(item) {
return utils.isInstanceOf(item, Block);
});
if (!areAllBlockInstances) {
throw new Error('blocks must only contain Block instances');
}
return new World(strategy, constraints, blocks);
}
function createStrategy(strategyName, seed) {
// TODO: validate arguments
var strategyFactory = getStrategyFactory(strategyName);
var randomMatrixGenerator = randomMatrix(seed);
var strategyInstance = strategyFactory.createInstance(randomMatrixGenerator);
return new Strategy(strategyInstance);
}
function createWorldConstraints(initialMapSize, bounds, mapCenter) {
return new WorldConstraints(initialMapSize, bounds, mapCenter);
}
module.exports = {
createStrategy: createStrategy,
createBlockFactory: createBlockFactory,
createConnectorInstance: createConnectorInstance,
createWorldInstance: createWorldInstance,
createWorldConstraints: createWorldConstraints
};
| 32.797468 | 98 | 0.71787 |
5417134ee561cb28ce2849542a9c8dd6e4dd63af | 9,541 | go | Go | types/services.go | switch-li/win32 | e35da23bbd186e9144fbb98ed05b9474271b1912 | [
"MIT"
] | null | null | null | types/services.go | switch-li/win32 | e35da23bbd186e9144fbb98ed05b9474271b1912 | [
"MIT"
] | null | null | null | types/services.go | switch-li/win32 | e35da23bbd186e9144fbb98ed05b9474271b1912 | [
"MIT"
] | null | null | null | package types
// Variables
type (
PFN_SC_NOTIFY_CALLBACK LPVOID
SERVICE_STATUS_HANDLE HANDLE
SC_HANDLE HANDLE
SC_LOCK LPVOID
)
// SC_STATUS_TYPE
type SC_STATUS_TYPE UINT
const (
SC_STATUS_PROCESS_INFO SC_STATUS_TYPE = 0
)
// ServiceType
type ServiceType DWORD
const (
SERVICE_KERNEL_DRIVER ServiceType = 0x00000001
SERVICE_FILE_SYSTEM_DRIVER ServiceType = 0x00000002
SERVICE_ADAPTER ServiceType = 0x00000004
SERVICE_RECOGNIZER_DRIVER ServiceType = 0x00000008
SERVICE_DRIVER ServiceType = 0x0000000B
SERVICE_WIN32_OWN_PROCESS ServiceType = 0x00000010
SERVICE_WIN32_SHARE_PROCESS ServiceType = 0x00000020
SERVICE_INTERACTIVE_PROCESS ServiceType = 0x00000100
SERVICE_WIN32 ServiceType = 0x00000030
SERVICE_NO_CHANGE ServiceType = 0xffffffff
)
// ServiceState
type ServiceState DWORD
const (
SERVICE_ACTIVE ServiceState = 0x00000001
SERVICE_INACTIVE ServiceState = 0x00000002
SERVICE_STATE_ALL ServiceState = 0x00000003
)
// ServiceCurrentState
type ServiceCurrentState DWORD
const (
SERVICE_STOPPED ServiceCurrentState = 0x00000001
SERVICE_START_PENDING ServiceCurrentState = 0x00000002
SERVICE_STOP_PENDING ServiceCurrentState = 0x00000003
SERVICE_RUNNING ServiceCurrentState = 0x00000004
SERVICE_CONTINUE_PENDING ServiceCurrentState = 0x00000005
SERVICE_PAUSE_PENDING ServiceCurrentState = 0x00000006
SERVICE_PAUSED ServiceCurrentState = 0x00000007
)
// ServiceStartType
type ServiceStartType DWORD
const (
SERVICE_BOOT_START ServiceStartType = 0x00000000
SERVICE_SYSTEM_START ServiceStartType = 0x00000001
SERVICE_AUTO_START ServiceStartType = 0x00000002
SERVICE_DEMAND_START ServiceStartType = 0x00000003
SERVICE_DISABLED ServiceStartType = 0x00000004
)
// ServiceErrorControl
type ServiceErrorControl DWORD
const (
SERVICE_ERROR_IGNORE ServiceErrorControl = 0x00000000
SERVICE_ERROR_NORMAL ServiceErrorControl = 0x00000001
SERVICE_ERROR_SEVERE ServiceErrorControl = 0x00000002
SERVICE_ERROR_CRITICAL ServiceErrorControl = 0x00000003
)
// ServiceInfoLevel
type ServiceInfoLevel DWORD
const (
SERVICE_CONFIG_DESCRIPTION ServiceInfoLevel = 1
SERVICE_CONFIG_FAILURE_ACTIONS ServiceInfoLevel = 2
SERVICE_CONFIG_DELAYED_AUTO_START_INFO ServiceInfoLevel = 3
SERVICE_CONFIG_FAILURE_ACTIONS_FLAG ServiceInfoLevel = 4
SERVICE_CONFIG_SERVICE_SID_INFO ServiceInfoLevel = 5
SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO ServiceInfoLevel = 6
SERVICE_CONFIG_PRESHUTDOWN_INFO ServiceInfoLevel = 7
SERVICE_CONFIG_TRIGGER_INFO ServiceInfoLevel = 8
SERVICE_CONFIG_PREFERRED_NODE ServiceInfoLevel = 9
)
// SCManagerAccess
type SCManagerAccess DWORD
const (
SC_MANAGER_GENERIC_READ SCManagerAccess = 0x80000000
SC_MANAGER_GENERIC_WRITE SCManagerAccess = 0x40000000
SC_MANAGER_GENERIC_EXECUTE SCManagerAccess = 0x20000000
SC_MANAGER_CONNECT SCManagerAccess = 0x0001
SC_MANAGER_CREATE_SERVICE SCManagerAccess = 0x0002
SC_MANAGER_ENUMERATE_SERVICE SCManagerAccess = 0x0004
SC_MANAGER_LOCK SCManagerAccess = 0x0008
SC_MANAGER_QUERY_LOCK_STATUS SCManagerAccess = 0x0010
SC_MANAGER_MODIFY_BOOT_CONFIG SCManagerAccess = 0x0020
SC_MANAGER_ALL_ACCESS SCManagerAccess = 0xF003F
)
// ServiceAccess
type ServiceAccess DWORD
const (
SERVICE_QUERY_CONFIG ServiceAccess = 0x0001
SERVICE_CHANGE_CONFIG ServiceAccess = 0x0002
SERVICE_QUERY_STATUS ServiceAccess = 0x0004
SERVICE_ENUMERATE_DEPENDENTS ServiceAccess = 0x0008
SERVICE_START ServiceAccess = 0x0010
SERVICE_STOP ServiceAccess = 0x0020
SERVICE_PAUSE_CONTINUE ServiceAccess = 0x0040
SERVICE_INTERROGATE ServiceAccess = 0x0080
SERVICE_USER_DEFINED_CONTROL ServiceAccess = 0x0100
SERVICE_ALL_ACCESS ServiceAccess = 0xF01FF
SERVICE_ACCESS_SYSTEM_SECURITY ServiceAccess = 0x01000000
SERVICE_DELETE ServiceAccess = 0x00010000
SERVICE_READ_CONTROL ServiceAccess = 0x00020000
SERVICE_WRITE_DAC ServiceAccess = 0x00040000
SERVICE_WRITE_OWNER ServiceAccess = 0x00080000
SERVICE_GENERIC_READ ServiceAccess = 0x80000000
SERVICE_GENERIC_WRITE ServiceAccess = 0x40000000
SERVICE_GENERIC_EXECUTE ServiceAccess = 0x20000000
SERVICE_MAXIMUM_ALLOWED ServiceAccess = 0x02000000
)
// ServiceControl
type ServiceControl DWORD
const (
SERVICE_CONTROL_STOP ServiceControl = 0x00000001
SERVICE_CONTROL_PAUSE ServiceControl = 0x00000002
SERVICE_CONTROL_CONTINUE ServiceControl = 0x00000003
SERVICE_CONTROL_INTERROGATE ServiceControl = 0x00000004
SERVICE_CONTROL_SHUTDOWN ServiceControl = 0x00000005
SERVICE_CONTROL_PARAMCHANGE ServiceControl = 0x00000006
SERVICE_CONTROL_NETBINDADD ServiceControl = 0x00000007
SERVICE_CONTROL_NETBINDREMOVE ServiceControl = 0x00000008
SERVICE_CONTROL_NETBINDENABLE ServiceControl = 0x00000009
SERVICE_CONTROL_NETBINDDISABLE ServiceControl = 0x0000000A
SERVICE_CONTROL_DEVICEEVENT ServiceControl = 0x0000000B
SERVICE_CONTROL_HARDWAREPROFILECHANGE ServiceControl = 0x0000000C
SERVICE_CONTROL_POWEREVENT ServiceControl = 0x0000000D
SERVICE_CONTROL_SESSIONCHANGE ServiceControl = 0x0000000E
SERVICE_CONTROL_PRESHUTDOWN ServiceControl = 0x0000000F
)
// ServiceAcceptControls
type ServiceAcceptControls DWORD
const (
SERVICE_ACCEPT_STOP ServiceAcceptControls = 0x00000001
SERVICE_ACCEPT_PAUSE_CONTINUE ServiceAcceptControls = 0x00000002
SERVICE_ACCEPT_SHUTDOWN ServiceAcceptControls = 0x00000004
SERVICE_ACCEPT_PARAMCHANGE ServiceAcceptControls = 0x00000008
SERVICE_ACCEPT_NETBINDCHANGE ServiceAcceptControls = 0x00000010
SERVICE_ACCEPT_HARDWAREPROFILECHANGE ServiceAcceptControls = 0x00000020
SERVICE_ACCEPT_POWEREVENT ServiceAcceptControls = 0x00000040
SERVICE_ACCEPT_SESSIONCHANGE ServiceAcceptControls = 0x00000080
SERVICE_ACCEPT_PRESHUTDOWN ServiceAcceptControls = 0x00000100
SERVICE_ACCEPT_TIMECHANGE ServiceAcceptControls = 0x00000200
SERVICE_ACCEPT_TRIGGEREVENT ServiceAcceptControls = 0x00000400
)
// ServiceNotifyMask
type ServiceNotifyMask DWORD
const (
SERVICE_NOTIFY_STOPPED ServiceNotifyMask = 0x00000001
SERVICE_NOTIFY_START_PENDING ServiceNotifyMask = 0x00000002
SERVICE_NOTIFY_STOP_PENDING ServiceNotifyMask = 0x00000004
SERVICE_NOTIFY_RUNNING ServiceNotifyMask = 0x00000008
SERVICE_NOTIFY_CONTINUE_PENDING ServiceNotifyMask = 0x00000010
SERVICE_NOTIFY_PAUSE_PENDING ServiceNotifyMask = 0x00000020
SERVICE_NOTIFY_PAUSED ServiceNotifyMask = 0x00000040
SERVICE_NOTIFY_CREATED ServiceNotifyMask = 0x00000080
SERVICE_NOTIFY_DELETED ServiceNotifyMask = 0x00000100
SERVICE_NOTIFY_DELETE_PENDING ServiceNotifyMask = 0x00000200
)
// ServiceFlags
type ServiceFlags DWORD
const (
SERVICE_RUNS_IN_SYSTEM_PROCESS ServiceFlags = 0x00000001
)
// SERVICE_STATUS_PROCESS
type SERVICE_STATUS_PROCESS struct {
ServiceType ServiceType
CurrentState ServiceCurrentState
ControlsAccepted ServiceAcceptControls
Win32ExitCode DWORD
ServiceSpecificExitCode DWORD
CheckPoint DWORD
WaitHint DWORD
ProcessId DWORD
ServiceFlags ServiceFlags
}
// SERVICE_NOTIFY
type SERVICE_NOTIFY struct {
Version DWORD
NotifyCallback PFN_SC_NOTIFY_CALLBACK
Context PVOID
NotificationStatus DWORD
ServiceStatus SERVICE_STATUS_PROCESS
NotificationTriggered DWORD
ServiceNames LPWSTR
}
type PSERVICE_NOTIFY *SERVICE_NOTIFY
// SERVICE_NOTIFYA
type SERVICE_NOTIFYA struct {
Version DWORD
NotifyCallback PFN_SC_NOTIFY_CALLBACK
Context PVOID
NotificationStatus DWORD
ServiceStatus SERVICE_STATUS_PROCESS
NotificationTriggered DWORD
ServiceNames LPSTR
}
type PSERVICE_NOTIFYA *SERVICE_NOTIFYA
// SERVICE_STATUS
type SERVICE_STATUS struct {
ServiceType ServiceType
CurrentState ServiceCurrentState
ControlsAccepted ServiceAcceptControls
Win32ExitCode DWORD
ServiceSpecificExitCode DWORD
CheckPoint DWORD
WaitHint DWORD
}
type LPSERVICE_STATUS *SERVICE_STATUS
// SERVICE_TABLE_ENTRY
type LPSERVICE_MAIN_FUNCTION LPVOID
type SERVICE_TABLE_ENTRY struct {
ServiceName LPWSTR
ServiceProc LPSERVICE_MAIN_FUNCTION
}
// ENUM_SERVICE_STATUS
type ENUM_SERVICE_STATUS struct {
ServiceName LPWSTR
DisplayName LPWSTR
ServiceStatus SERVICE_STATUS
}
type LPENUM_SERVICE_STATUS *ENUM_SERVICE_STATUS
// QUERY_SERVICE_CONFIG
type QUERY_SERVICE_CONFIG struct {
ServiceType ServiceType
StartType ServiceStartType
ErrorControl ServiceErrorControl
BinaryPathName LPWSTR
LoadOrderGroup LPWSTR
TagId DWORD
Dependencies LPWSTR
ServiceStartName LPWSTR
DisplayName LPWSTR
}
type LPQUERY_SERVICE_CONFIG *QUERY_SERVICE_CONFIG
// QUERY_SERVICE_LOCK_STATUS
type QUERY_SERVICE_LOCK_STATUS struct {
IsLocked DWORD
LockOwner LPWSTR
LockDuration DWORD
}
type LPQUERY_SERVICE_LOCK_STATUS *QUERY_SERVICE_LOCK_STATUS
| 33.36014 | 72 | 0.770674 |
171237bded32aeb45d6da7a971e0e05715d5a6f1 | 1,754 | c | C | server/command/command_time.c | Adam-/bedrock | 428b91d7dfded30dc5eaec8b1d29d10a49da34b8 | [
"BSD-2-Clause"
] | 13 | 2015-01-11T04:39:21.000Z | 2021-03-08T13:00:48.000Z | server/command/command_time.c | Adam-/bedrock | 428b91d7dfded30dc5eaec8b1d29d10a49da34b8 | [
"BSD-2-Clause"
] | null | null | null | server/command/command_time.c | Adam-/bedrock | 428b91d7dfded30dc5eaec8b1d29d10a49da34b8 | [
"BSD-2-Clause"
] | 4 | 2015-04-06T12:55:05.000Z | 2021-06-25T03:40:19.000Z | #include "server/command.h"
#include "command/command_time.h"
#include "server/packets.h"
#include <errno.h>
static void update_time(struct command_source *source, struct world *world, long time)
{
bedrock_node *node;
command_reply(source, "Time in %s changed to %ld", world->name, time);
world->time = time;
LIST_FOREACH(&client_list, node)
{
struct client *c = node->data;
if (c->world == world)
packet_send_time(c);
}
}
void command_time(struct command_source *source, int argc, const char **argv)
{
struct world *world;
if (source->user != NULL)
world = source->user->world;
else
{
if (world_list.count == 0)
{
command_reply(source, "There are no laoded worlds");
return;
}
world = world_list.head->data;
}
if (argc == 3)
{
if (!strcasecmp(argv[1], "set"))
{
char *errptr = NULL;
long time;
errno = 0;
time = strtol(argv[2], &errptr, 10);
if (errno || *errptr)
{
command_reply(source, "Invalid time");
return;
}
else
{
time %= 24000;
update_time(source, world, time);
}
}
}
else if (argc == 2)
{
if (!strcasecmp(argv[1], "day") || !strcasecmp(argv[1], "noon"))
update_time(source, world, 6000);
else if (!strcasecmp(argv[1], "night") || !strcasecmp(argv[1], "midnight"))
update_time(source, world, 18000);
else if (!strcasecmp(argv[1], "dawn") || !strcasecmp(argv[1], "morning"))
update_time(source, world, 24000);
else if (!strcasecmp(argv[1], "dusk") || !strcasecmp(argv[1], "evening"))
update_time(source, world, 12000);
}
else
{
bedrock_node *node;
LIST_FOREACH(&world_list, node)
{
struct world *world = node->data;
command_reply(source, "Current time in %s is %ld", world->name, world->time);
}
}
}
| 20.880952 | 86 | 0.631129 |
0b98688189c3ac958636f3a3393afa2872fb1f5c | 2,820 | py | Python | lib/ravstack/runtime.py | geertj/raviron | 7920c6b71757eddcca16b60051c1cf08706ae11b | [
"MIT"
] | 1 | 2015-05-11T21:39:35.000Z | 2015-05-11T21:39:35.000Z | lib/ravstack/runtime.py | geertj/raviron | 7920c6b71757eddcca16b60051c1cf08706ae11b | [
"MIT"
] | null | null | null | lib/ravstack/runtime.py | geertj/raviron | 7920c6b71757eddcca16b60051c1cf08706ae11b | [
"MIT"
] | null | null | null | #
# This file is part of ravstack. Ravstack is free software available under
# the terms of the MIT license. See the file "LICENSE" that was provided
# together with this source file for the licensing terms.
#
# Copyright (c) 2015 the ravstack authors. See the file "AUTHORS" for a
# complete list.
from __future__ import absolute_import, print_function
import sys
import logging
from . import config, defaults, util
prog_name = __name__.split('.')[0]
LOG = logging.getLogger(prog_name)
CONF = config.Config()
DEBUG = util.EnvInt('DEBUG')
VERBOSE = util.EnvInt('VERBOSE')
LOG_STDERR = util.EnvInt('LOG_STDERR')
log_context = ''
log_datetime = '%(asctime)s '
log_template = '%(levelname)s [%(name)s] %(message)s'
log_ctx_template = '%(levelname)s [{}] [%(name)s] %(message)s'
def setup_config():
"""Return the configuration object."""
CONF.set_schema(defaults.config_schema)
CONF.read_file(defaults.config_file)
CONF.update_from_env()
meta = util.get_ravello_metadata()
if 'appName' in meta and CONF['ravello']['application'] == '<None>':
CONF['ravello']['application'] = meta['appName']
CONF.update_to_env()
def setup_logging(context=None):
"""Set up or reconfigure logging."""
root = logging.getLogger()
if root.handlers:
del root.handlers[:]
global log_context
if context is not None:
log_context = context
template = log_ctx_template.format(log_context) if log_context else log_template
# Log to stderr?
if LOG_STDERR:
handler = logging.StreamHandler(sys.stderr)
handler.setFormatter(logging.Formatter(template))
root.addHandler(handler)
else:
root.addHandler(logging.NullHandler())
# Available log file?
logfile = defaults.log_file
if util.can_open(logfile, 'a'):
handler = logging.FileHandler(logfile)
handler.setFormatter(logging.Formatter(log_datetime + template))
root.addHandler(handler)
root.setLevel(logging.DEBUG if DEBUG else logging.INFO if VERBOSE else logging.ERROR)
# A little less verbosity for requests.
logger = logging.getLogger('requests.packages.urllib3.connectionpool')
logger.setLevel(logging.DEBUG if DEBUG else logging.ERROR)
# Silence "insecure platform" warning for requests module on Py2.7.x under
# default verbosity.
logging.captureWarnings(True)
logger = logging.getLogger('py.warnings')
logger.setLevel(logging.DEBUG if DEBUG else logging.ERROR)
# Run a main function
def run_main(func):
"""Run a main function."""
setup_config()
setup_logging()
# Run the provided main function.
try:
func()
except Exception as e:
LOG.error('Uncaught exception:', exc_info=True)
if DEBUG:
raise
print('Error: {!s}'.format(e))
| 30.989011 | 89 | 0.693617 |
ce06b7ac638d08e076e17e6cb7d7455317fccfcc | 3,740 | swift | Swift | Open Terminal/AppDelegate.swift | DreamSworK/FinderOpenTerminal | 411d48c0d66853525d2f70c81094497c087566a9 | [
"Apache-2.0"
] | 2 | 2018-05-06T21:25:45.000Z | 2018-11-05T04:11:12.000Z | Open Terminal/AppDelegate.swift | DreamSworK/FinderOpenTerminal | 411d48c0d66853525d2f70c81094497c087566a9 | [
"Apache-2.0"
] | null | null | null | Open Terminal/AppDelegate.swift | DreamSworK/FinderOpenTerminal | 411d48c0d66853525d2f70c81094497c087566a9 | [
"Apache-2.0"
] | null | null | null | //
// AppDelegate.swift
// Open Terminal
//
// Created by Quentin PÂRIS on 23/02/2016.
// Copyright © 2016 QP. All rights reserved.
//
import Cocoa
import Darwin
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationWillFinishLaunching(_ aNotification: Notification) {
let appleEventManager:NSAppleEventManager = NSAppleEventManager.shared()
appleEventManager.setEventHandler(self, andSelector: #selector(AppDelegate.handleGetURLEvent(_:replyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
SwiftySystem.execute("/usr/bin/pluginkit", arguments: ["pluginkit", "-e", "use", "-i", "fr.qparis.openterminal.Open-Terminal-Finder-Extension"])
SwiftySystem.execute("/usr/bin/killall",arguments: ["Finder"])
helpMe()
exit(0)
}
@objc func handleGetURLEvent(_ event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
if let url = URL(string: event!.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))!.stringValue!) {
if !url.path.isEmpty {
if(FileManager.default.fileExists(atPath: url.path)) {
let arg = "tell application \"System Events\"\n" +
// Check if Terminal.app is running
"if (application process \"Terminal\" exists) then\n" +
// if Terminal.app is running make sure it is in the foreground
"tell application \"Terminal\"\n" +
"activate\n" +
"end tell\n" +
// Open a new window in the Terminal.app by triggering ⌘+n
"tell application \"System Events\" to tell process \"Terminal\" to keystroke \"n\" using command down\n" +
"else\n" +
// If Terminal.app is not running bring it up
"tell application \"Terminal\"\n" +
"activate\n" +
"end tell\n" +
"end if\n" +
"end tell\n" +
// Switch to the requested directory and clear made input
"tell application \"Terminal\"\n" +
"delay 0.01\n" +
"do script \"cd '\(url.path)' && clear\" in window 1\n" +
"end tell"
SwiftySystem.execute("/usr/bin/osascript", arguments: ["-e", arg])
} else {
let error = NSLocalizedString("pathError", comment: "Missing directory message")
helpMe(error)
}
}
}
exit(0)
}
fileprivate func helpMe(_ customMessage: String) {
let alert = NSAlert ()
alert.messageText = "Information"
alert.informativeText = customMessage
alert.runModal()
}
fileprivate func helpMe() {
let info = NSLocalizedString("information", comment: "Information presented on startup")
helpMe(info + "\n\n(c) Quentin PÂRIS 2018 - http://quentin.paris")
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| 45.060241 | 201 | 0.514706 |
572b1180d774398e4fea8609166d9c8accdaffc4 | 6,410 | h | C | vendors/goodix/GR551x_SDK_V1_00/components/boards/custom_board.h | goodix/amazon-freertos | 407b49d6fb506b4c2bc65bd2373e0ab3e28844e7 | [
"MIT"
] | 1 | 2019-12-05T01:51:03.000Z | 2019-12-05T01:51:03.000Z | vendors/goodix/GR551x_SDK_V1_00/components/boards/custom_board.h | goodix/amazon-freertos | 407b49d6fb506b4c2bc65bd2373e0ab3e28844e7 | [
"MIT"
] | null | null | null | vendors/goodix/GR551x_SDK_V1_00/components/boards/custom_board.h | goodix/amazon-freertos | 407b49d6fb506b4c2bc65bd2373e0ab3e28844e7 | [
"MIT"
] | 2 | 2019-11-19T02:51:31.000Z | 2019-12-11T17:42:15.000Z | #ifndef __CUSTOM_BOARD_H
#define __CUSTOM_BOARD_H
/*******DBG_PRINTF UART IO CONFIG*****************/
#define LOG_UART_GRP UART0
#define LOG_UART_PORT GPIO0
#define LOG_UART_TX_PIN LL_GPIO_PIN_3
#define LOG_UART_RX_PIN LL_GPIO_PIN_4
#define LOG_UART_TX_PINMUX LL_GPIO_MUX_0
#define LOG_UART_RX_PINMUX LL_GPIO_MUX_0
#define LOG_UART_PIN_MUX_SET ll_gpio_set_mux_pin_0_7
/*******HCI UART IO CONFIG***********************/
#define HCI_UART_FLOW_ON 0
#define HCI_UART_BAUDRATE 921600
#define HCI_UART_TRN_PORT GPIO0
#define HCI_UART_FLOW_PORT GPIO0
#define HCI_UART_TX_PIN GPIO_PIN_3
#define HCI_UART_RX_PIN GPIO_PIN_4
#define HCI_UART_CTS_PIN GPIO_PIN_2
#define HCI_UART_RTS_PIN GPIO_PIN_5
#define HCI_UART_TX_PINMUX GPIO_MUX_0
#define HCI_UART_RX_PINMUX GPIO_MUX_0
#define HCI_UART_CTS_PINMUX GPIO_MUX_0
#define HCI_UART_RTS_PINMUX GPIO_MUX_0
/*******UART DRIVER IO CONFIG*******************/
#define SERIAL_PORT_GRP UART0
#define SERIAL_PORT_PORT GPIO0
#define SERIAL_PORT_TX_PIN GPIO_PIN_3
#define SERIAL_PORT_RX_PIN GPIO_PIN_4
#define SERIAL_PORT_TX_PINMUX GPIO_MUX_0
#define SERIAL_PORT_RX_PINMUX GPIO_MUX_0
/*******ADC IO CONFIG**************************/
#define ADC_P_INPUT_PIN MSIO_PIN_0
#define ADC_N_INPUT_PIN MSIO_PIN_1
/*******GPIO KEY*******************************/
#define GPIO_KEY0 GPIO_PIN_12
#define GPIO_KEY1 GPIO_PIN_13
#define GPIO_KEY_PORT GPIO0
/*******I2C IO CONFIG**************************/
#define I2C_MODULE I2C0
#define I2C_GPIO_MUX GPIO_MUX_2
#define I2C_GPIO_PORT GPIO1
#define I2C_SCL_PIN GPIO_PIN_14 //GPIO30
#define I2C_SDA_PIN GPIO_PIN_10 //GPIO26
#define I2C_MASTER_MODULE I2C0
#define I2C_MASTER_GPIO_MUX GPIO_MUX_3
#define I2C_MASTER_GPIO_PORT MSIO
#define I2C_MASTER_SCL_PIN MSIO_PIN_0 //MSIO0
#define I2C_MASTER_SDA_PIN MSIO_PIN_1 //MSIO1
#define I2C_SLAVE_MODULE I2C1
#define I2C_SLAVE_GPIO_MUX GPIO_MUX_0
#define I2C_SLAVE_GPIO_PORT GPIO1
#define I2C_SLAVE_SCL_PIN GPIO_PIN_14 //GPIO30
#define I2C_SLAVE_SDA_PIN GPIO_PIN_10 //GPIO26
/*******I2S IO CONFIG**************************/
#define I2S_MASTER_GPIO_MUX AON_GPIO_MUX_2
#define I2S_MASTER_WS_PIN AON_GPIO_PIN_2
#define I2S_MASTER_TX_SDO_PIN AON_GPIO_PIN_3
#define I2S_MASTER_RX_SDI_PIN AON_GPIO_PIN_4
#define I2S_MASTER_SCLK_PIN AON_GPIO_PIN_5
#define I2S_SLAVE_GPIO_MUX GPIO_MUX_4
#define I2S_SLAVE_GPIO_PORT GPIO1
#define I2S_SLAVE_WS_PIN GPIO_PIN_8
#define I2S_SLAVE_TX_SDO_PIN GPIO_PIN_9
#define I2S_SLAVE_RX_SDI_PIN GPIO_PIN_0
#define I2S_SLAVE_SCLK_PIN GPIO_PIN_1
/*******PWM IO CONFIG***************************/
#define PWM0_MODULE PWM0
#define PWM0_GPIO_MUX GPIO_MUX_5
#define PWM0_CHANNEL_C GPIO_PIN_4
#define PWM0_PORT GPIO0
#define PWM1_MODULE PWM1
#define PWM1_GPIO_MUX MSIO_MUX_0
#define PWM1_CHANNEL_B MSIO_PIN_4
#define PWM1_PORT MSIO
/*******COMP IO CONFIG***************************/
#define COMP_INPUT_PIN MSIO_PIN_0
#define COMP_INPUT_PORT MSIO
#define COMP_VREF_PIN MSIO_PIN_1
#define COMP_VREF_PORT MSIO
/*******QSPI IO CONFIG*************************/
#define QSPI_MODULE QSPI1
#define QSPI_GPIO_MUX GPIO_MUX_2
#define QSPI_GPIO_PORT GPIO0
#define QSPI_CS_PIN GPIO_PIN_15 //GPIO15
#define QSPI_CLK_PIN GPIO_PIN_9 //GPIO9
#define QSPI_IO0_PIN GPIO_PIN_8 //GPIO8
#define QSPI_IO1_PIN GPIO_PIN_14 //GPIO14
#define QSPI_IO2_PIN GPIO_PIN_13 //GPIO13
#define QSPI_IO3_PIN GPIO_PIN_12 //GPIO12
#define QSPI_POLLING 0x0
#define QSPI_DMA 0x1
#define QSPI_USE_OPERATION QSPI_DMA
/*******SPIM IO CONFIG*************************/
#define SPIM_GPIO_MUX GPIO_MUX_0
#define SPIM_GPIO_PORT GPIO1
#define SPIM_CS0_PIN GPIO_PIN_1 //GPIO17
#define SPIM_CS1_PIN GPIO_PIN_15 //GPIO31
#define SPIM_CLK_PIN GPIO_PIN_8 //GPIO24
#define SPIM_MOSI_PIN GPIO_PIN_9 //GPIO25
#define SPIM_MISO_PIN GPIO_PIN_0 //GPIO16
#define SPIS_GPIO_MUX GPIO_MUX_1
#define SPIS_GPIO_PORT GPIO1
#define SPIS_CS0_PIN GPIO_PIN_1 //GPIO17
#define SPIS_CLK_PIN GPIO_PIN_8 //GPIO24
#define SPIS_MOSI_PIN GPIO_PIN_0 //GPIO16
#define SPIS_MISO_PIN GPIO_PIN_9 //GPIO25
/*******VS1005 MP3 CODEC DRIVER IO CONFIG*********/
#define VS1005_GROUP_0 GPIO0
#define VS1005_GROUP_1 GPIO1
#define VS_XCS_PIN GPIO_PIN_8
#define VS_XCS_PIN_GRP VS1005_GROUP_1
#define VS_XDCS_PIN GPIO_PIN_9
#define VS_XDCS_PIN_GRP VS1005_GROUP_1
#define VS_RST_PIN GPIO_PIN_2
#define VS_RST_PIN_GRP VS1005_GROUP_0
#define VS_DQ_PIN GPIO_PIN_4
#define VS_DQ_PIN_GRP VS1005_GROUP_0
#define VS_SPI_GPIO_MUX_0 GPIO_MUX_3
#define VS_SPI_GPIO_GRP_0 VS1005_GROUP_0
#define VS_CLK_PIN GPIO_PIN_7
#define VS_MOSI_PIN GPIO_PIN_6
#define VS_SPI_GPIO_MUX_1 GPIO_MUX_1
#define VS_SPI_GPIO_GRP_1 VS1005_GROUP_1
#define VS_MISO_PIN GPIO_PIN_0
#endif
| 43.310811 | 63 | 0.566147 |
85b894b46727acf15696b7be08456c5faf888dbc | 2,458 | js | JavaScript | third_party/google_input_tools/src/chrome/os/inputview/hwt_eventtype.js | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | third_party/google_input_tools/src/chrome/os/inputview/hwt_eventtype.js | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/google_input_tools/src/chrome/os/inputview/hwt_eventtype.js | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 The ChromeOS IME Authors. All Rights Reserved.
// limitations under the License.
// See the License for the specific language governing permissions and
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// distributed under the License is distributed on an "AS-IS" BASIS,
// Unless required by applicable law or agreed to in writing, software
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// You may obtain a copy of the License at
// you may not use this file except in compliance with the License.
// Licensed under the Apache License, Version 2.0 (the "License");
//
/**
* @fileoverview Handwriting event type.
* @author wuyingbing@google.com (Yingbing Wu)
*/
goog.provide('i18n.input.hwt.CandidateSelectEvent');
goog.provide('i18n.input.hwt.CommitEvent');
goog.provide('i18n.input.hwt.EventType');
goog.require('goog.events');
goog.require('goog.events.Event');
/**
* Handwriting event type to expose to external.
*
* @enum {string}
*/
i18n.input.hwt.EventType = {
BACKSPACE: goog.events.getUniqueId('b'),
CANDIDATE_SELECT: goog.events.getUniqueId('cs'),
COMMIT: goog.events.getUniqueId('c'),
COMMIT_START: goog.events.getUniqueId('hcs'),
COMMIT_END: goog.events.getUniqueId('hce'),
RECOGNITION_READY: goog.events.getUniqueId('rr'),
ENTER: goog.events.getUniqueId('e'),
HANDWRITING_CLOSED: goog.events.getUniqueId('hc'),
MOUSEUP: goog.events.getUniqueId('m'),
SPACE: goog.events.getUniqueId('s')
};
/**
* Candidate select event.
*
* @param {string} candidate The candidate.
* @constructor
* @extends {goog.events.Event}
*/
i18n.input.hwt.CandidateSelectEvent = function(candidate) {
goog.base(this, i18n.input.hwt.EventType.CANDIDATE_SELECT);
/**
* The candidate.
*
* @type {string}
*/
this.candidate = candidate;
};
goog.inherits(i18n.input.hwt.CandidateSelectEvent, goog.events.Event);
/**
* Commit event.
*
* @param {string} text The text to commit.
* @param {number=} opt_back The number of characters to be deleted.
* @constructor
* @extends {goog.events.Event}
*/
i18n.input.hwt.CommitEvent = function(text, opt_back) {
goog.base(this, i18n.input.hwt.EventType.COMMIT);
/**
* The text.
*
* @type {string}
*/
this.text = text;
/**
* The number of characters to be deleted.
*
* @type {number}
*/
this.back = opt_back || 0;
};
goog.inherits(i18n.input.hwt.CommitEvent, goog.events.Event);
| 25.340206 | 75 | 0.70057 |
4a4d6b6eeb5c2befdc91605642005d95eb94c25b | 470 | js | JavaScript | src/app/components/pages/placeSearchForm/placeInputs.js | threelephant/inventory-client | 66eedf30e2018618ea628af8583c15455f9923da | [
"MIT"
] | null | null | null | src/app/components/pages/placeSearchForm/placeInputs.js | threelephant/inventory-client | 66eedf30e2018618ea628af8583c15455f9923da | [
"MIT"
] | null | null | null | src/app/components/pages/placeSearchForm/placeInputs.js | threelephant/inventory-client | 66eedf30e2018618ea628af8583c15455f9923da | [
"MIT"
] | null | null | null | import React from 'react'
import { FormGroup, Label, Input } from 'reactstrap'
const Division = ({ onChange }) => {
return (
<FormGroup>
<Label for="id">Отдел</Label>
<Input onChange={onChange} name="object_id" />
</FormGroup>
)
}
const Placement = ({ onChange }) => {
return (
<FormGroup>
<Label for="id">Помещение</Label>
<Input onChange={onChange} name="object_id" />
</FormGroup>
)
}
export { Division, Placement }
| 20.434783 | 52 | 0.606383 |
4a48dd818865c694f36b1fb734a655a4ac44582f | 18,248 | js | JavaScript | src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/illustrations/sapIllus-Dialog-GroupTable.js | EricVanEldik/openui5 | ad80fc60ab8b36b5f4f8a070bcff77d0ce8557ff | [
"Apache-2.0"
] | null | null | null | src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/illustrations/sapIllus-Dialog-GroupTable.js | EricVanEldik/openui5 | ad80fc60ab8b36b5f4f8a070bcff77d0ce8557ff | [
"Apache-2.0"
] | null | null | null | src/sap.ui.webc.fiori/src/sap/ui/webc/fiori/thirdparty/illustrations/sapIllus-Dialog-GroupTable.js | EricVanEldik/openui5 | ad80fc60ab8b36b5f4f8a070bcff77d0ce8557ff | [
"Apache-2.0"
] | null | null | null | sap.ui.define(function () { 'use strict';
var dialogSvg = `<svg width="160" height="160" viewBox="0 0 160 160" fill="none" xmlns="http://www.w3.org/2000/svg" id="sapIllus-Dialog-GroupTable">
<circle cx="80" cy="80" r="80" fill="var(--sapContent_Illustrative_Color7)"/>
<path d="M124.428 37.4707H55.4125C51.2306 37.4707 47.8405 40.8608 47.8405 45.0427V130.4C47.8405 134.582 51.2306 137.972 55.4125 137.972H124.428C128.61 137.972 132 134.582 132 130.4V45.0427C132 40.8608 128.61 37.4707 124.428 37.4707Z" fill="var(--sapContent_Illustrative_Color18)"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M55.599 45.6074C55.599 45.2632 55.6936 44.9873 55.8092 44.9873H123.595C123.711 44.9873 123.805 45.25 123.805 45.6074V129.838C123.805 130.182 123.711 130.458 123.595 130.458H55.8092C55.6936 130.458 55.599 130.195 55.599 129.838V45.6074Z" fill="var(--sapContent_Illustrative_Color18)"/>
<path d="M123.81 53.0505H55.599V60.0314H123.81V53.0505Z" fill="var(--sapContent_Illustrative_Color19)"/>
<path d="M59.548 55.689H71.2765C71.6601 55.689 71.9728 56.1067 71.9728 56.6217C71.9728 57.1472 71.6601 57.5518 71.2765 57.5518H59.548C59.1618 57.5518 58.8491 57.134 58.8491 56.6217C58.8491 56.1067 59.1513 55.689 59.548 55.689Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 62.5146H69.0696C69.4531 62.5146 69.7658 62.9324 69.7658 63.4447C69.7658 63.9702 69.4531 64.3774 69.0696 64.3774H59.548C59.1618 64.3774 58.8491 63.9597 58.8491 63.4447C58.8491 62.9324 59.1513 62.5146 59.548 62.5146Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 69.6533H70.5829C70.9691 69.6533 71.2818 70.0711 71.2818 70.5834C71.2818 71.1089 70.9691 71.5161 70.5829 71.5161H59.548C59.1618 71.5161 58.8491 71.0984 58.8491 70.5834C58.8491 70.0684 59.1513 69.6533 59.548 69.6533Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 76.4844H64.54C64.9262 76.4844 65.2362 76.9021 65.2362 77.4145C65.2362 77.9399 64.9262 78.3445 64.54 78.3445H59.548C59.1618 78.3445 58.8491 77.9294 58.8491 77.4145C58.8491 76.8942 59.1513 76.4844 59.548 76.4844Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 83.457H64.54C64.9262 83.457 65.2362 83.8722 65.2362 84.3871C65.2362 84.9126 64.9262 85.3172 64.54 85.3172H59.548C59.1618 85.3172 58.8491 84.9021 58.8491 84.3871C58.8491 83.8722 59.1513 83.457 59.548 83.457Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 97.4185H64.54C64.9262 97.4185 65.2362 97.8336 65.2362 98.3485C65.2362 98.874 64.9262 99.2786 64.54 99.2786H59.548C59.1618 99.2786 58.8491 98.8609 58.8491 98.3485C58.8491 97.8336 59.1513 97.4185 59.548 97.4185Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 90.4385H64.54C64.9262 90.4385 65.2362 90.8536 65.2362 91.3686C65.2362 91.894 64.9262 92.2986 64.54 92.2986H59.548C59.1618 92.2986 58.8491 91.8835 58.8491 91.3686C58.8491 90.8536 59.1513 90.4385 59.548 90.4385Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.548 104.397H64.54C64.9262 104.397 65.2362 104.815 65.2362 105.33C65.2362 105.856 64.9262 106.26 64.54 106.26H59.548C59.1618 106.26 58.8491 105.843 58.8491 105.33C58.8491 104.815 59.1513 104.397 59.548 104.397Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M59.5244 111.407H64.5164C64.9 111.407 65.2126 111.825 65.2126 112.337C65.2126 112.863 64.9 113.27 64.5164 113.27H59.5244C59.1408 113.27 58.8281 112.852 58.8281 112.337C58.8281 111.825 59.1513 111.407 59.5244 111.407Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 55.689H95.7976C96.1812 55.689 96.4939 56.1067 96.4939 56.6217C96.4939 57.1472 96.1812 57.5518 95.7976 57.5518H84.0691C83.6829 57.5518 83.3702 57.134 83.3702 56.6217C83.3702 56.1067 83.6829 55.689 84.0691 55.689Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 62.5146H93.5906C93.9742 62.5146 94.2869 62.9324 94.2869 63.4447C94.2869 63.9702 93.9742 64.3774 93.5906 64.3774H84.0691C83.6829 64.3774 83.3702 63.9597 83.3702 63.4447C83.3702 62.9324 83.6829 62.5146 84.0691 62.5146Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 69.6533H95.104C95.4902 69.6533 95.8029 70.0711 95.8029 70.5834C95.8029 71.1089 95.4902 71.5161 95.104 71.5161H84.0691C83.6829 71.5161 83.3702 71.0984 83.3702 70.5834C83.3702 70.0684 83.6829 69.6533 84.0691 69.6533Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 76.4844H89.0611C89.4473 76.4844 89.7573 76.9021 89.7573 77.4145C89.7573 77.9399 89.4473 78.3445 89.0611 78.3445H84.0691C83.6829 78.3445 83.3702 77.9294 83.3702 77.4145C83.3702 76.8942 83.6829 76.4844 84.0691 76.4844Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 83.457H89.0611C89.4473 83.457 89.7573 83.8722 89.7573 84.3871C89.7573 84.9126 89.4473 85.3172 89.0611 85.3172H84.0691C83.6829 85.3172 83.3702 84.9021 83.3702 84.3871C83.3702 83.8722 83.6829 83.457 84.0691 83.457Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 97.4185H89.0611C89.4473 97.4185 89.7573 97.8336 89.7573 98.3485C89.7573 98.874 89.4473 99.2786 89.0611 99.2786H84.0691C83.6829 99.2786 83.3702 98.8609 83.3702 98.3485C83.3702 97.8336 83.6829 97.4185 84.0691 97.4185Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 90.4385H89.0611C89.4473 90.4385 89.7573 90.8536 89.7573 91.3686C89.7573 91.894 89.4473 92.2986 89.0611 92.2986H84.0691C83.6829 92.2986 83.3702 91.8835 83.3702 91.3686C83.3702 90.8536 83.6829 90.4385 84.0691 90.4385Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0691 104.397H89.0611C89.4473 104.397 89.7573 104.815 89.7573 105.33C89.7573 105.856 89.4473 106.26 89.0611 106.26H84.0691C83.6829 106.26 83.3702 105.843 83.3702 105.33C83.3702 104.815 83.6829 104.397 84.0691 104.397Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M84.0455 111.407H89.0375C89.4211 111.407 89.7337 111.825 89.7337 112.337C89.7337 112.863 89.4211 113.27 89.0375 113.27H84.0455C83.6619 113.27 83.3492 112.852 83.3492 112.337C83.3492 111.825 83.6619 111.407 84.0455 111.407Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 55.689H120.04C120.424 55.689 120.736 56.1067 120.736 56.6217C120.736 57.1472 120.424 57.5518 120.04 57.5518H108.312C107.925 57.5518 107.613 57.134 107.613 56.6217C107.613 56.1067 107.925 55.689 108.312 55.689Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 62.5146H117.833C118.217 62.5146 118.529 62.9324 118.529 63.4447C118.529 63.9702 118.217 64.3774 117.833 64.3774H108.312C107.925 64.3774 107.613 63.9597 107.613 63.4447C107.613 62.9324 107.925 62.5146 108.312 62.5146Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 69.6533H119.347C119.733 69.6533 120.045 70.0711 120.045 70.5834C120.045 71.1089 119.733 71.5161 119.347 71.5161H108.312C107.925 71.5161 107.613 71.0984 107.613 70.5834C107.613 70.0684 107.925 69.6533 108.312 69.6533Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 76.4844H113.304C113.687 76.4844 114 76.9021 114 77.4145C114 77.9399 113.687 78.3445 113.304 78.3445H108.312C107.925 78.3445 107.613 77.9294 107.613 77.4145C107.613 76.8942 107.925 76.4844 108.312 76.4844Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 83.457H113.304C113.687 83.457 114 83.8722 114 84.3871C114 84.9126 113.687 85.3172 113.304 85.3172H108.312C107.925 85.3172 107.613 84.9021 107.613 84.3871C107.613 83.8722 107.925 83.457 108.312 83.457Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 97.4185H113.304C113.687 97.4185 114 97.8336 114 98.3485C114 98.874 113.687 99.2786 113.304 99.2786H108.312C107.925 99.2786 107.613 98.8609 107.613 98.3485C107.613 97.8336 107.925 97.4185 108.312 97.4185Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 90.4385H113.304C113.687 90.4385 114 90.8536 114 91.3686C114 91.894 113.687 92.2986 113.304 92.2986H108.312C107.925 92.2986 107.613 91.8835 107.613 91.3686C107.613 90.8536 107.925 90.4385 108.312 90.4385Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.312 104.397H113.304C113.687 104.397 114 104.815 114 105.33C114 105.856 113.687 106.26 113.304 106.26H108.312C107.925 106.26 107.613 105.843 107.613 105.33C107.613 104.815 107.925 104.397 108.312 104.397Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M108.283 111.407H113.275C113.661 111.407 113.974 111.825 113.974 112.337C113.974 112.863 113.661 113.27 113.275 113.27H108.283C107.897 113.27 107.587 112.852 107.587 112.337C107.592 111.825 107.902 111.407 108.283 111.407Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M73.8251 47.468H60.4781C59.5784 47.468 58.8491 48.1973 58.8491 49.097C58.8491 49.9966 59.5784 50.7259 60.4781 50.7259H73.8251C74.7247 50.7259 75.454 49.9966 75.454 49.097C75.454 48.1973 74.7247 47.468 73.8251 47.468Z" fill="var(--sapContent_Illustrative_Color20)"/>
<path d="M96.5875 17H27.572C23.3901 17 20 20.3901 20 24.572V109.93C20 114.112 23.3901 117.502 27.572 117.502H96.5875C100.769 117.502 104.16 114.112 104.16 109.93V24.572C104.16 20.3901 100.769 17 96.5875 17Z" fill="var(--sapContent_Illustrative_Color8)"/>
<path fill-rule="evenodd" clip-rule="evenodd" d="M27.7585 25.1367C27.7585 24.7925 27.8531 24.5166 27.9687 24.5166H95.7546C95.8702 24.5166 95.9648 24.7793 95.9648 25.1367V109.367C95.9648 109.711 95.8702 109.987 95.7546 109.987H27.9687C27.8531 109.987 27.7585 109.724 27.7585 109.367V25.1367Z" fill="var(--sapContent_Illustrative_Color8)"/>
<path d="M95.97 32.5798H27.7585V39.5607H95.97V32.5798Z" fill="var(--sapContent_Illustrative_Color18)"/>
<path d="M31.7076 35.2183H43.4361C43.8197 35.2183 44.1323 35.636 44.1323 36.151C44.1323 36.6765 43.8197 37.0811 43.4361 37.0811H31.7076C31.3213 37.0811 31.0087 36.6633 31.0087 36.151C31.0087 35.636 31.3108 35.2183 31.7076 35.2183Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 42.0439H41.2291C41.6127 42.0439 41.9254 42.4617 41.9254 42.974C41.9254 43.4995 41.6127 43.9067 41.2291 43.9067H31.7076C31.3213 43.9067 31.0087 43.489 31.0087 42.974C31.0087 42.4617 31.3108 42.0439 31.7076 42.0439Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 49.1829H42.7425C43.1287 49.1829 43.4413 49.6006 43.4413 50.1129C43.4413 50.6384 43.1287 51.0457 42.7425 51.0457H31.7076C31.3213 51.0457 31.0087 50.6279 31.0087 50.1129C31.0087 49.598 31.3108 49.1829 31.7076 49.1829Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 56.0137H36.6995C37.0858 56.0137 37.3958 56.4314 37.3958 56.9438C37.3958 57.4692 37.0858 57.8738 36.6995 57.8738H31.7076C31.3213 57.8738 31.0087 57.4587 31.0087 56.9438C31.0087 56.4235 31.3108 56.0137 31.7076 56.0137Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 62.9863H36.6995C37.0858 62.9863 37.3958 63.4015 37.3958 63.9164C37.3958 64.4419 37.0858 64.8465 36.6995 64.8465H31.7076C31.3213 64.8465 31.0087 64.4314 31.0087 63.9164C31.0087 63.4015 31.3108 62.9863 31.7076 62.9863Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 76.9478H36.6995C37.0858 76.9478 37.3958 77.3629 37.3958 77.8778C37.3958 78.4033 37.0858 78.8079 36.6995 78.8079H31.7076C31.3213 78.8079 31.0087 78.3902 31.0087 77.8778C31.0087 77.3629 31.3108 76.9478 31.7076 76.9478Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 69.9678H36.6995C37.0858 69.9678 37.3958 70.3829 37.3958 70.8979C37.3958 71.4233 37.0858 71.8279 36.6995 71.8279H31.7076C31.3213 71.8279 31.0087 71.4128 31.0087 70.8979C31.0087 70.3829 31.3108 69.9678 31.7076 69.9678Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.7076 83.9268H36.6995C37.0858 83.9268 37.3958 84.3445 37.3958 84.8595C37.3958 85.385 37.0858 85.7895 36.6995 85.7895H31.7076C31.3213 85.7895 31.0087 85.3718 31.0087 84.8595C31.0087 84.3445 31.3108 83.9268 31.7076 83.9268Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M31.6839 90.9365H36.6759C37.0595 90.9365 37.3721 91.3543 37.3721 91.8666C37.3721 92.3921 37.0595 92.7993 36.6759 92.7993H31.6839C31.3003 92.7993 30.9877 92.3815 30.9877 91.8666C30.9877 91.3543 31.3108 90.9365 31.6839 90.9365Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 35.2183H67.9572C68.3408 35.2183 68.6534 35.636 68.6534 36.151C68.6534 36.6765 68.3408 37.0811 67.9572 37.0811H56.2286C55.8424 37.0811 55.5298 36.6633 55.5298 36.151C55.5298 35.636 55.8424 35.2183 56.2286 35.2183Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 42.0439H65.7502C66.1338 42.0439 66.4464 42.4617 66.4464 42.974C66.4464 43.4995 66.1338 43.9067 65.7502 43.9067H56.2286C55.8424 43.9067 55.5298 43.489 55.5298 42.974C55.5298 42.4617 55.8424 42.0439 56.2286 42.0439Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 49.1829H67.2635C67.6498 49.1829 67.9624 49.6006 67.9624 50.1129C67.9624 50.6384 67.6498 51.0457 67.2635 51.0457H56.2286C55.8424 51.0457 55.5298 50.6279 55.5298 50.1129C55.5298 49.598 55.8424 49.1829 56.2286 49.1829Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 56.0137H61.2206C61.6068 56.0137 61.9169 56.4314 61.9169 56.9438C61.9169 57.4692 61.6068 57.8738 61.2206 57.8738H56.2286C55.8424 57.8738 55.5298 57.4587 55.5298 56.9438C55.5298 56.4235 55.8424 56.0137 56.2286 56.0137Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 62.9863H61.2206C61.6068 62.9863 61.9169 63.4015 61.9169 63.9164C61.9169 64.4419 61.6068 64.8465 61.2206 64.8465H56.2286C55.8424 64.8465 55.5298 64.4314 55.5298 63.9164C55.5298 63.4015 55.8424 62.9863 56.2286 62.9863Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 76.9478H61.2206C61.6068 76.9478 61.9169 77.3629 61.9169 77.8778C61.9169 78.4033 61.6068 78.8079 61.2206 78.8079H56.2286C55.8424 78.8079 55.5298 78.3902 55.5298 77.8778C55.5298 77.3629 55.8424 76.9478 56.2286 76.9478Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 69.9678H61.2206C61.6068 69.9678 61.9169 70.3829 61.9169 70.8979C61.9169 71.4233 61.6068 71.8279 61.2206 71.8279H56.2286C55.8424 71.8279 55.5298 71.4128 55.5298 70.8979C55.5298 70.3829 55.8424 69.9678 56.2286 69.9678Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.2286 83.9268H61.2206C61.6068 83.9268 61.9169 84.3445 61.9169 84.8595C61.9169 85.385 61.6068 85.7895 61.2206 85.7895H56.2286C55.8424 85.7895 55.5298 85.3718 55.5298 84.8595C55.5298 84.3445 55.8424 83.9268 56.2286 83.9268Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M56.205 90.9365H61.197C61.5806 90.9365 61.8933 91.3543 61.8933 91.8666C61.8933 92.3921 61.5806 92.7993 61.197 92.7993H56.205C55.8215 92.7993 55.5088 92.3815 55.5088 91.8666C55.5088 91.3543 55.8215 90.9365 56.205 90.9365Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 35.2183H92.1998C92.5834 35.2183 92.896 35.636 92.896 36.151C92.896 36.6765 92.5834 37.0811 92.1998 37.0811H80.4712C80.085 37.0811 79.7723 36.6633 79.7723 36.151C79.7723 35.636 80.085 35.2183 80.4712 35.2183Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 42.0439H89.9928C90.3764 42.0439 90.689 42.4617 90.689 42.974C90.689 43.4995 90.3764 43.9067 89.9928 43.9067H80.4712C80.085 43.9067 79.7723 43.489 79.7723 42.974C79.7723 42.4617 80.085 42.0439 80.4712 42.0439Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 49.1829H91.5061C91.8924 49.1829 92.205 49.6006 92.205 50.1129C92.205 50.6384 91.8924 51.0457 91.5061 51.0457H80.4712C80.085 51.0457 79.7723 50.6279 79.7723 50.1129C79.7723 49.598 80.085 49.1829 80.4712 49.1829Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 56.0137H85.4632C85.8468 56.0137 86.1595 56.4314 86.1595 56.9438C86.1595 57.4692 85.8468 57.8738 85.4632 57.8738H80.4712C80.085 57.8738 79.7723 57.4587 79.7723 56.9438C79.7723 56.4235 80.085 56.0137 80.4712 56.0137Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 62.9863H85.4632C85.8468 62.9863 86.1595 63.4015 86.1595 63.9164C86.1595 64.4419 85.8468 64.8465 85.4632 64.8465H80.4712C80.085 64.8465 79.7723 64.4314 79.7723 63.9164C79.7723 63.4015 80.085 62.9863 80.4712 62.9863Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 76.9478H85.4632C85.8468 76.9478 86.1595 77.3629 86.1595 77.8778C86.1595 78.4033 85.8468 78.8079 85.4632 78.8079H80.4712C80.085 78.8079 79.7723 78.3902 79.7723 77.8778C79.7723 77.3629 80.085 76.9478 80.4712 76.9478Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 69.9678H85.4632C85.8468 69.9678 86.1595 70.3829 86.1595 70.8979C86.1595 71.4233 85.8468 71.8279 85.4632 71.8279H80.4712C80.085 71.8279 79.7723 71.4128 79.7723 70.8979C79.7723 70.3829 80.085 69.9678 80.4712 69.9678Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4712 83.9268H85.4632C85.8468 83.9268 86.1595 84.3445 86.1595 84.8595C86.1595 85.385 85.8468 85.7895 85.4632 85.7895H80.4712C80.085 85.7895 79.7723 85.3718 79.7723 84.8595C79.7723 84.3445 80.085 83.9268 80.4712 83.9268Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M80.4424 90.9365H85.4343C85.8206 90.9365 86.1332 91.3543 86.1332 91.8666C86.1332 92.3921 85.8206 92.7993 85.4343 92.7993H80.4424C80.0561 92.7993 79.7461 92.3815 79.7461 91.8666C79.7513 91.3543 80.0614 90.9365 80.4424 90.9365Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M45.9846 26.9973H32.6376C31.738 26.9973 31.0087 27.7266 31.0087 28.6263C31.0087 29.5259 31.738 30.2552 32.6376 30.2552H45.9846C46.8843 30.2552 47.6136 29.5259 47.6136 28.6263C47.6136 27.7266 46.8843 26.9973 45.9846 26.9973Z" fill="var(--sapContent_Illustrative_Color14)"/>
<path d="M136 20.8858C136 19.7539 132.879 18.8479 128.708 18.6421C128.47 14.2576 127.552 10.9975 126.476 11C125.401 11.0025 124.507 14.2877 124.278 18.6948C120.095 18.996 116.986 19.9798 117 21.1142C117.014 22.2486 120.121 23.1546 124.292 23.3579C124.542 27.7424 125.448 31.0025 126.521 31C127.595 30.9975 128.493 27.7123 128.722 23.3052C132.905 23.004 136.012 22.0202 136 20.8858Z" fill="var(--sapContent_Illustrative_Color3)"/>
<path d="M149 34.4258C149 33.6901 146.864 33.1011 144.011 32.9674C143.848 30.1175 143.22 27.9984 142.484 28C141.748 28.0016 141.136 30.137 140.979 33.0016C138.118 33.1974 135.99 33.8369 136 34.5742C136.01 35.3116 138.136 35.9005 140.989 36.0326C141.161 38.8825 141.781 41.0016 142.515 41C143.249 40.9984 143.864 38.863 144.021 35.9984C146.882 35.8026 149.008 35.1631 149 34.4258Z" fill="var(--sapContent_Illustrative_Color3)"/>
</svg>
`;
return dialogSvg;
});
| 243.306667 | 429 | 0.766988 |
80fdecfcb7c329058e20b7f90e405f8a80d651e6 | 207 | kt | Kotlin | app/src/main/java/com/dinaraparanid/prima/utils/web/genius/search_response/Data.kt | dinaraparanid/MusicPlayer | 68cfaee9458f4a1f5e077f668c09d5d4a9171594 | [
"Apache-2.0"
] | 6 | 2021-07-24T20:25:57.000Z | 2022-02-19T18:23:11.000Z | app/src/main/java/com/dinaraparanid/prima/utils/web/genius/search_response/Data.kt | dinaraparanid/MusicPlayer | 68cfaee9458f4a1f5e077f668c09d5d4a9171594 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/dinaraparanid/prima/utils/web/genius/search_response/Data.kt | dinaraparanid/MusicPlayer | 68cfaee9458f4a1f5e077f668c09d5d4a9171594 | [
"Apache-2.0"
] | 1 | 2021-07-03T00:24:34.000Z | 2021-07-03T00:24:34.000Z | package com.dinaraparanid.prima.utils.web.genius.search_response
import com.google.gson.annotations.Expose
/**
* Found song from search query
*/
class Data(@Expose @JvmField val hits: Array<DataOfData>) | 23 | 64 | 0.782609 |
9c248eae435b7915c64549e345c12128de72296d | 636 | js | JavaScript | src/components/App.js | roheat/indorse-healthy | 9217567d242f7783d95cece11a7671594aa85493 | [
"MIT"
] | null | null | null | src/components/App.js | roheat/indorse-healthy | 9217567d242f7783d95cece11a7671594aa85493 | [
"MIT"
] | 3 | 2020-09-04T23:38:55.000Z | 2022-02-12T11:42:38.000Z | src/components/App.js | roheat/indorse-healthy | 9217567d242f7783d95cece11a7671594aa85493 | [
"MIT"
] | null | null | null | import React from 'react';
import AutoComplete from './AutoComplete';
import DisplayDetails from './DisplayDetails';
import '../styles/app.css';
import items from '../items';
class App extends React.Component {
state = {
selectedItem: null
}
selectedItem = item => {
this.setState({ selectedItem: item });
}
render() {
return (
<div className="container">
<h1>Healthy living, healthy eating</h1>
<AutoComplete items={JSON.parse(items)} getSelectedItem={(item) => this.selectedItem(item)}/>
<DisplayDetails items={JSON.parse(items)} item={this.state.selectedItem} />
</div>
);
}
};
export default App; | 23.555556 | 97 | 0.68239 |
5c9fe367d0667c642fdc189fa841deb8dc69d04d | 206 | css | CSS | public/stylesheet/service.min.css | jerossh/zhongtuo2 | 2d2d32ac7d2d5f44ed44bd9cc857432a493e72fc | [
"MIT"
] | null | null | null | public/stylesheet/service.min.css | jerossh/zhongtuo2 | 2d2d32ac7d2d5f44ed44bd9cc857432a493e72fc | [
"MIT"
] | null | null | null | public/stylesheet/service.min.css | jerossh/zhongtuo2 | 2d2d32ac7d2d5f44ed44bd9cc857432a493e72fc | [
"MIT"
] | null | null | null | #service .servicewrap{line-height:2em;padding:30px 0;color:#0090dd;margin-bottom:10px}#service .servicewrap:hover{background-color:#f6f9fc;border-radius:1rem}.service_caption{padding-top:10px;color:#6f7c82} | 206 | 206 | 0.825243 |
c7e00dd26b34f7f44b8c29edc94d77a59f611a05 | 56 | java | Java | image-encryption/src/main/java/com/markby/RandomUtils.java | MarkBY/image-encryption | 8835ad3fae81dec7a5d8e9d175685cbcd44bf4d4 | [
"MIT"
] | null | null | null | image-encryption/src/main/java/com/markby/RandomUtils.java | MarkBY/image-encryption | 8835ad3fae81dec7a5d8e9d175685cbcd44bf4d4 | [
"MIT"
] | null | null | null | image-encryption/src/main/java/com/markby/RandomUtils.java | MarkBY/image-encryption | 8835ad3fae81dec7a5d8e9d175685cbcd44bf4d4 | [
"MIT"
] | null | null | null | package com.markby;
public class RandomUtils {
}
| 9.333333 | 27 | 0.678571 |
98efdd0d2aa4e3ebb67c274fe583dae13bdd28ed | 2,586 | kt | Kotlin | kotlin/workflow-runtime/src/test/java/com/squareup/workflow/internal/ChannelUpdatesTest.kt | mongoose700/workflow | afb723c53ec6745525215a23df809e3ceb4c7ce3 | [
"Apache-2.0"
] | null | null | null | kotlin/workflow-runtime/src/test/java/com/squareup/workflow/internal/ChannelUpdatesTest.kt | mongoose700/workflow | afb723c53ec6745525215a23df809e3ceb4c7ce3 | [
"Apache-2.0"
] | null | null | null | kotlin/workflow-runtime/src/test/java/com/squareup/workflow/internal/ChannelUpdatesTest.kt | mongoose700/workflow | afb723c53ec6745525215a23df809e3ceb4c7ce3 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Square 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.
*/
@file:Suppress("EXPERIMENTAL_API_USAGE")
package com.squareup.workflow.internal
import com.squareup.workflow.util.ChannelUpdate
import com.squareup.workflow.util.ChannelUpdate.Closed
import com.squareup.workflow.util.ChannelUpdate.Value
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.selects.select
import kotlinx.coroutines.yield
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
class ChannelUpdatesTest {
@Test fun suspends() {
val channel = Channel<String>(1)
runBlocking {
val result = GlobalScope.async(Dispatchers.Unconfined) {
select<ChannelUpdate<String>> {
onChannelUpdate(channel) { it }
}
}
assertFalse(result.isCompleted)
yield()
assertFalse(result.isCompleted)
result.cancel()
}
}
@Test fun `emits value`() {
val channel = Channel<String>(1)
channel.offer("foo")
val result = runBlocking {
select<ChannelUpdate<String>> {
onChannelUpdate(channel) { it }
}
}
assertEquals(Value("foo"), result)
}
@Test fun `emits close`() {
val channel = Channel<String>()
channel.close()
val result = runBlocking {
select<ChannelUpdate<String>> {
onChannelUpdate(channel) { it }
}
}
assertEquals(Closed, result)
}
@Test fun `handles error`() {
val channel = Channel<String>()
// TODO https://github.com/square/workflow/issues/188 Stop using parameterized cancel.
@Suppress("DEPRECATION")
channel.cancel(ExpectedException())
assertFailsWith<ExpectedException> {
runBlocking {
select<ChannelUpdate<String>> {
onChannelUpdate(channel) { it }
}
}
}
}
private class ExpectedException : RuntimeException()
}
| 25.86 | 90 | 0.701856 |
41b0ac7bf44fd5fafd499aefc34895a85c5c3c2a | 1,362 | h | C | modules/tracktion_engine/model/clips/tracktion_ArrangerClip.h | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 734 | 2018-11-16T09:39:40.000Z | 2022-03-30T16:56:14.000Z | modules/tracktion_engine/model/clips/tracktion_ArrangerClip.h | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 100 | 2018-11-16T18:04:08.000Z | 2022-03-31T17:47:53.000Z | modules/tracktion_engine/model/clips/tracktion_ArrangerClip.h | jbloit/tracktion_engine | b3fa7d6a3a404f64ae419abdf9c801d672cffb16 | [
"MIT",
"Unlicense"
] | 123 | 2018-11-16T15:51:50.000Z | 2022-03-29T12:21:27.000Z | /*
,--. ,--. ,--. ,--.
,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018
'-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software
| | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation
`---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com
Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details.
*/
namespace tracktion_engine
{
//==============================================================================
/**
*/
class ArrangerClip : public Clip
{
public:
ArrangerClip (const juce::ValueTree&, EditItemID, ClipTrack& targetTrack);
~ArrangerClip() override;
using Ptr = juce::ReferenceCountedObjectPtr<ArrangerClip>;
juce::String getSelectableDescription() override;
bool canGoOnTrack (Track&) override;
juce::Colour getDefaultColour() const override;
void initialise() override;
bool isMidi() const override { return false; }
bool isMuted() const override { return false; }
protected:
void valueTreePropertyChanged (juce::ValueTree&, const juce::Identifier&) override;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ArrangerClip)
};
} // namespace tracktion_engine
| 34.05 | 87 | 0.487518 |
2243d90cfeb2f1aed461fc8001f26121393f06cc | 843 | asm | Assembly | programs/oeis/158/A158321.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/158/A158321.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/158/A158321.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A158321: a(n) = 441n^2 + 2n.
; 443,1768,3975,7064,11035,15888,21623,28240,35739,44120,53383,63528,74555,86464,99255,112928,127483,142920,159239,176440,194523,213488,233335,254064,275675,298168,321543,345800,370939,396960,423863,451648,480315,509864,540295,571608,603803,636880,670839,705680,741403,778008,815495,853864,893115,933248,974263,1016160,1058939,1102600,1147143,1192568,1238875,1286064,1334135,1383088,1432923,1483640,1535239,1587720,1641083,1695328,1750455,1806464,1863355,1921128,1979783,2039320,2099739,2161040,2223223,2286288,2350235,2415064,2480775,2547368,2614843,2683200,2752439,2822560,2893563,2965448,3038215,3111864,3186395,3261808,3338103,3415280,3493339,3572280,3652103,3732808,3814395,3896864,3980215,4064448,4149563,4235560,4322439,4410200
mov $1,$0
add $0,1
mul $0,21
pow $0,2
add $0,2
mov $2,$1
mul $2,2
add $0,$2
| 70.25 | 734 | 0.818505 |
1cce3dc260c8a5634a02c0b68ddfcd7b52f03d1b | 292 | swift | Swift | Apple-Frameworks/Apple_FrameworksApp.swift | pklapuch/swiftUI-apple-frameworks | 301b864117ad48dcef83b32caaf69296057b99e6 | [
"MIT"
] | null | null | null | Apple-Frameworks/Apple_FrameworksApp.swift | pklapuch/swiftUI-apple-frameworks | 301b864117ad48dcef83b32caaf69296057b99e6 | [
"MIT"
] | null | null | null | Apple-Frameworks/Apple_FrameworksApp.swift | pklapuch/swiftUI-apple-frameworks | 301b864117ad48dcef83b32caaf69296057b99e6 | [
"MIT"
] | null | null | null | //
// Apple_FrameworksApp.swift
// Apple-Frameworks
//
// Created by Pawel Klapuch on 8/28/21.
//
import SwiftUI
@main
struct Apple_FrameworksApp: App {
var body: some Scene {
WindowGroup {
FrameworkGridView(viewModel: FrameworkGridViewModel())
}
}
}
| 16.222222 | 66 | 0.640411 |
51652865cecb5e62c8530c7aee1035b206407561 | 204 | sql | SQL | Databases Basics - MS SQL Server/Joins Subqueries CTE and Indices/04. Employee Departments.sql | Shtereva/CSharp-DB-Fundametals | 54a9665dac212efff15268c762d240307c61efed | [
"MIT"
] | null | null | null | Databases Basics - MS SQL Server/Joins Subqueries CTE and Indices/04. Employee Departments.sql | Shtereva/CSharp-DB-Fundametals | 54a9665dac212efff15268c762d240307c61efed | [
"MIT"
] | null | null | null | Databases Basics - MS SQL Server/Joins Subqueries CTE and Indices/04. Employee Departments.sql | Shtereva/CSharp-DB-Fundametals | 54a9665dac212efff15268c762d240307c61efed | [
"MIT"
] | null | null | null | SELECT TOP (5) e.EmployeeID,
FirstName,
Salary,
d.Name AS [DepartmentName]
FROM Employees AS e
JOIN Departments as d ON d.DepartmentID = e.DepartmentID
WHERE Salary > 15000
ORDER BY e.DepartmentID | 25.5 | 56 | 0.759804 |
2fdd9404fab0f8bba9511c8ea812a9f47660a8fa | 2,492 | rs | Rust | src/lib.rs | theRookieCoder/furse | b5795c1bd6753465671a64dd4b5080ce62b35f73 | [
"MIT"
] | 3 | 2022-01-19T08:13:25.000Z | 2022-02-07T03:34:11.000Z | src/lib.rs | theRookieCoder/furse | b5795c1bd6753465671a64dd4b5080ce62b35f73 | [
"MIT"
] | null | null | null | src/lib.rs | theRookieCoder/furse | b5795c1bd6753465671a64dd4b5080ce62b35f73 | [
"MIT"
] | null | null | null | //! # Furse
//!
//! Furse is a simple library for using the [CurseForge API](https://docs.curseforge.com/) in Rust projects.
//! It uses [Reqwest](https://docs.rs/reqwest/) as its HTTPS client and deserialises responses to strongly typed structs using [SerDe](https://serde.rs/).
//!
//! ## Features
//!
//! This crate includes the following:
//! - API calls:
//! - Get mod by mod ID (<https://docs.curseforge.com/#get-mod>)
//! - Get mod's HTML description by ID (<https://docs.curseforge.com/#get-mod-description>)
//! - Get mod's files by mod ID (<https://docs.curseforge.com/#get-mod-files>)
//! - Get file by the mod ID and file ID (<https://docs.curseforge.com/#get-mod-file>)
//! - Get file's HTML changelog by mod ID and file ID (<https://docs.curseforge.com/#get-mod-file-changelog>)
//! - Download a file from a `File`
//! - Download a file by mod ID and file ID (<https://docs.curseforge.com/#get-mod-file-download-url>)
//! - Schemas and their dependant schemas:
//! - Mod <https://docs.curseforge.com/#tocS_Mod>
//! - File <https://docs.curseforge.com/#tocS_File>
//!
//! This crate uses [Rustls](https://docs.rs/rustls/) rather than OpenSSL, because OpenSSL is outdated and slower.
mod api_calls;
mod request;
pub mod structures;
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error("{}", .0)]
ReqwestError(#[from] reqwest::Error),
#[error("{}", .0)]
URLParseError(#[from] url::ParseError),
}
pub(crate) type Result<T> = std::result::Result<T, Error>;
/// An instance of the API to invoke API calls on
///
/// To initialise this container,
/// ```rust
/// # use furse::Furse;
/// # #[tokio::main]
/// # async fn main() -> Result<(), furse::Error> {
/// let curseforge = Furse::new(env!("CURSEFORGE_API_KEY"));
/// // Use the instance to call the API
/// let terralith_mod = curseforge.get_mod(513688).await?;
/// # Ok(()) }
/// ```
#[derive(Clone, Debug)]
pub struct Furse {
client: reqwest::Client,
api_key: String,
}
impl Furse {
/// Create a new API instance
///
/// `api_key` should be a CurseForge API key.
/// You can obtain one by applying [here](https://forms.monday.com/forms/dce5ccb7afda9a1c21dab1a1aa1d84eb?r=use1)
///
/// ```rust
/// # use furse::Furse;
/// let curseforge = Furse::new(env!("CURSEFORGE_API_KEY"));
/// ```
pub fn new(api_key: &str) -> Self {
Self {
client: reqwest::Client::new(),
api_key: api_key.into(),
}
}
}
| 35.098592 | 154 | 0.630417 |
ed57e1a9017c7702202b3e174164132d1bfbccea | 3,151 | kt | Kotlin | domain/src/main/java/com/telen/easylineup/domain/model/export/PlayerExport.kt | kaygenzo/EasyLineUp | 3941fb10aee593332bc942f96734971ab3e68600 | [
"Apache-2.0"
] | null | null | null | domain/src/main/java/com/telen/easylineup/domain/model/export/PlayerExport.kt | kaygenzo/EasyLineUp | 3941fb10aee593332bc942f96734971ab3e68600 | [
"Apache-2.0"
] | null | null | null | domain/src/main/java/com/telen/easylineup/domain/model/export/PlayerExport.kt | kaygenzo/EasyLineUp | 3941fb10aee593332bc942f96734971ab3e68600 | [
"Apache-2.0"
] | 1 | 2020-05-26T11:36:03.000Z | 2020-05-26T11:36:03.000Z | package com.telen.easylineup.domain.model.export
import com.google.gson.annotations.SerializedName
/*
Copyright (c) 2020 Kotlin Data Classes Generated from JSON powered by http://www.json2kotlin.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
For support, please feel free to contact me at https://www.linkedin.com/in/syedabsar */
data class PlayerExport (
@SerializedName("id") val id : String,
@SerializedName("name") val name : String,
@SerializedName("image") var image : String?,
@SerializedName("shirtNumber") val shirtNumber : Int,
@SerializedName("licenseNumber") val licenseNumber : String,
@SerializedName("positions") val positions : Int,
@SerializedName("pitching") val pitching : Int,
@SerializedName("batting") val batting : Int,
@SerializedName("email") var email : String?,
@SerializedName("phone") var phone : String?
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as PlayerExport
if (id != other.id) return false
if (name != other.name) return false
if (image != other.image) return false
if (shirtNumber != other.shirtNumber) return false
if (licenseNumber != other.licenseNumber) return false
if (positions != other.positions) return false
if (pitching != other.pitching) return false
if (batting != other.batting) return false
if (email != other.email) return false
if (phone != other.phone) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + name.hashCode()
result = 31 * result + (image?.hashCode() ?: 0)
result = 31 * result + shirtNumber
result = 31 * result + licenseNumber.hashCode()
result = 31 * result + positions
result = 31 * result + pitching
result = 31 * result + batting
result = 31 * result + (email?.hashCode() ?: 0)
result = 31 * result + (phone?.hashCode() ?: 0)
return result
}
} | 49.234375 | 460 | 0.685179 |
170cc7fd251cfdab6b6d1bbe7b35405401f10d5c | 8,546 | h | C | Standard/Rect.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | Standard/Rect.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | Standard/Rect.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | /*
Rect.h
Rect template class
(c)2005 Palestar, Richard Lyle
*/
#ifndef RECT_H
#define RECT_H
#include "Point.h"
#include "Size.h"
//----------------------------------------------------------------------------
template<class T>
class Rect
{
public:
// construction
Rect();
Rect(const Point<T> &point, const Size<T> &size);
Rect(T X, T Y, Size<T> size);
Rect(T left, T top, T right, T bottom);
// accessors
bool valid() const; // is this rectangle valid
T width() const; // right - left + 1
T height() const; // bottom - top + 1
Size<T> size() const; // get the size of the rectangle
bool inRect( int x, int y ) const;
bool inRect( const Point<T> & point ) const;
bool inRect( const Rect<T> & rect ) const;
Point<T> center() const;
Point<T> upperLeft() const; // corners of this rectangle
Point<T> upperRight() const;
Point<T> lowerLeft() const;
Point<T> lowerRight() const;
bool operator==(const Rect<T>& Rhs);
bool operator!=(const Rect<T>& Rhs);
Rect<T> scale(T scaleWidth,T scaleHeight) const;
Rect<T> operator+(const Point<T> &Rhs) const;
Rect<T> operator-(const Point<T> &Rhs) const;
// mutators
Rect<T>& setInvalid();
void setLeft(const T Left);
void setTop(const T Top);
void setRight(const T Right);
void setBottom(const T Bottom);
void setWidth(const T Width); // expands to the right
void setHeight(const T Height); // expands to the bottom
void set(T left,T top,T right,T bottom);
void set(T X, T Y, const Size<T> & size);
void set(const Point<T> &point,const Size<T> &size);
Rect<T>& inset( T inset ); // >0 inset or <0 outset the rectangle
Rect<T>& operator=(const Rect<T> &Rhs);
Rect<T>& operator+=(const Point<T> & Rhs);
Rect<T>& operator-=(const Point<T>& Rhs);
Rect<T>& operator&=(const Rect<T>& Rhs); // Intersection
Rect<T>& operator|=(const Rect<T>& Rhs); // Union
Rect<T>& operator*=(const T Multiplier);
Rect<T>& operator/=(const T Divisor);
Rect<T> operator&(const Rect<T>& Rhs);
Rect<T> operator|(const Rect<T>& Rhs);
// Data
union {
T m_Left, left;
};
union {
T m_Top, top;
};
union {
T m_Right, right;
};
union {
T m_Bottom, bottom;
};
};
//-------------------------------------------------------------------------------
template<class T>
inline Rect<T>::Rect()
{
set(0,0,0,0);
}
template<class T>
inline Rect<T>::Rect(const Point<T> &point, const Size<T> &size)
{
set(point,size);
}
template<class T>
inline Rect<T>::Rect(T X, T Y, Size<T> size)
{
set(X,Y,size);
}
template<class T>
inline Rect<T>::Rect(T left, T top, T right, T bottom)
{
set(left,top,right,bottom);
}
//-------------------------------------------------------------------------------
template<class T>
inline bool Rect<T>::valid() const
{
return( (m_Left <= m_Right) && (m_Top <= m_Bottom) );
}
template<class T>
inline T Rect<T>::width() const
{
return( (m_Right - m_Left) + 1);
}
template<class T>
inline T Rect<T>::height() const
{
return( (m_Bottom - m_Top) + 1);
}
template<class T>
inline Size<T> Rect<T>::size() const
{
return( Size<T>( width(), height() ) );
}
template<class T>
inline bool Rect<T>::inRect( int x, int y ) const
{
return( x >= m_Left && x <= m_Right && y >= m_Top && y <= m_Bottom );
}
template<class T>
inline bool Rect<T>::inRect( const Point<T> & point ) const
{
return( point.x >= m_Left
&& point.x <= m_Right
&& point.y >= m_Top
&& point.y <= m_Bottom );
}
template<class T>
inline bool Rect<T>::inRect( const Rect<T> & rect ) const
{
return( m_Left <= rect.m_Left
&& m_Right >= rect.m_Right
&& m_Top <= rect.m_Top
&& m_Bottom >= rect.m_Bottom );
}
template<class T>
inline Point<T> Rect<T>::center() const
{
return(Point<T>( (m_Left + m_Right) / 2, (m_Top + m_Bottom) / 2 ) );
}
template<class T>
inline Point<T> Rect<T>::upperLeft() const
{
return(Point<T>( m_Left, m_Top) );
}
template<class T>
inline Point<T> Rect<T>::upperRight() const
{
return(Point<T>( m_Right, m_Top) );
}
template<class T>
inline Point<T> Rect<T>::lowerLeft() const
{
return(Point<T>( m_Left, m_Bottom ) );
}
template<class T>
inline Point<T> Rect<T>::lowerRight() const
{
return(Point<T>( m_Right, m_Bottom) );
}
template<class T>
inline Rect<T> Rect<T>::scale(T scaleWidth,T scaleHeight) const
{
Rect<T> result( *this );
result.m_Left *= scaleWidth;
result.m_Right *= scaleWidth;
result.m_Top *= scaleHeight;
result.m_Bottom *= scaleHeight;
return(result);
}
template<class T>
inline bool Rect<T>::operator==(const Rect<T>& Rhs)
{
return(m_Left == Rhs.m_Left && m_Top == Rhs.m_Top &&
m_Right == Rhs.m_Right && m_Bottom == Rhs.m_Bottom);
}
template<class T>
inline bool Rect<T>::operator!=(const Rect<T>& Rhs)
{
return(!(*this == Rhs));
}
//-------------------------------------------------------------------------------
template<class T>
inline Rect<T>& Rect<T>::setInvalid()
{
set( 1,1,-1,-1 );
return( *this );
}
template<class T>
inline void Rect<T>::setLeft(const T Left)
{
m_Left = Left;
}
template<class T>
inline void Rect<T>::setTop(const T Top)
{
m_Top = Top;
}
template<class T>
inline void Rect<T>::setRight(const T Right)
{
m_Right = Right;
}
template<class T>
inline void Rect<T>::setBottom(const T Bottom)
{
m_Bottom = Bottom;
}
template<class T>
inline void Rect<T>::setWidth(const T Width)
{
m_Right = m_Left + (Width - 1);
}
template<class T>
inline void Rect<T>::setHeight(const T Height)
{
m_Bottom = m_Top + (Height - 1);
}
template<class T>
inline void Rect<T>::set(T left,T top,T right,T bottom)
{
m_Left = left;
m_Top = top;
m_Right = right;
m_Bottom = bottom;
}
template<class T>
inline void Rect<T>::set(T X, T Y, const Size<T> & size)
{
m_Left = X;
m_Top = Y;
m_Right = X + size.width - 1;
m_Bottom = Y + size.height - 1;
}
template<class T>
inline void Rect<T>::set(const Point<T> &point,const Size<T> &size)
{
m_Left = point.x;
m_Top = point.y;
m_Right = m_Left + size.width - 1;
m_Bottom = m_Top + size.height - 1;
}
template<class T>
inline Rect<T>& Rect<T>::inset( T inset )
{
m_Left += inset;
m_Top += inset;
m_Right -= inset;
m_Bottom -= inset;
return *this;
}
template<class T>
inline Rect<T>& Rect<T>::operator=(const Rect<T> &Rhs)
{
m_Left = Rhs.m_Left;
m_Top = Rhs.m_Top;
m_Right = Rhs.m_Right;
m_Bottom = Rhs.m_Bottom;
return(*this);
}
template<class T>
inline Rect<T>& Rect<T>::operator+=(const Point<T> & Rhs)
{
m_Left += Rhs.x;
m_Top += Rhs.y;
m_Right += Rhs.x;
m_Bottom += Rhs.y;
return(*this);
}
template<class T>
inline Rect<T>& Rect<T>::operator-=(const Point<T>& Rhs)
{
m_Left -= Rhs.x;
m_Top -= Rhs.y;
m_Right -= Rhs.x;
m_Bottom -= Rhs.y;
return(*this);
}
template<class T>
inline Rect<T> Rect<T>::operator+(const Point<T> &Rhs) const
{
Rect result = *this;
result += Rhs;
return( result );
}
template<class T>
inline Rect<T> Rect<T>::operator-(const Point<T> &Rhs) const
{
Rect result = *this;
result -= Rhs;
return( result );
}
template<class T>
inline Rect<T>& Rect<T>::operator&=(const Rect<T>& Rhs) // intersect with Rhs
{
if(m_Left < Rhs.m_Left)
m_Left = Rhs.m_Left;
if(m_Top < Rhs.m_Top)
m_Top = Rhs.m_Top;
if(m_Right > Rhs.m_Right)
m_Right = Rhs.m_Right;
if(m_Bottom > Rhs.m_Bottom)
m_Bottom = Rhs.m_Bottom;
return(*this);
}
template<class T>
inline Rect<T>& Rect<T>::operator|=(const Rect<T>& Rhs) // union with Rhs
{
if(m_Left > Rhs.m_Left)
m_Left = Rhs.m_Left;
if(m_Top > Rhs.m_Top)
m_Top = Rhs.m_Top;
if(m_Right < Rhs.m_Right)
m_Right = Rhs.m_Right;
if(m_Bottom < Rhs.m_Bottom)
m_Bottom = Rhs.m_Bottom;
return(*this);
}
template<class T>
inline Rect<T>& Rect<T>::operator*=(const T Multiplier)
{
m_Left *= Multiplier;
m_Top *= Multiplier;
m_Right *= Multiplier;
m_Bottom *= Multiplier;
return(*this);
}
template<class T>
inline Rect<T>& Rect<T>::operator/=(const T Divisor)
{
m_Left /= Divisor;
m_Top /= Divisor;
m_Right /= Divisor;
m_Bottom /= Divisor;
return(*this);
}
template<class T>
inline Rect<T> Rect<T>::operator&(const Rect<T>& Rhs)
{
Rect<T> result(*this);
result &= Rhs;
return(result);
}
template<class T>
inline Rect<T> Rect<T>::operator|(const Rect<T>& Rhs)
{
Rect<T> result(*this);
result |= Rhs;
return(result);
}
//-------------------------------------------------------------------------------
typedef Rect<int> RectInt;
typedef Rect<float> RectFloat;
#endif
//----------------------------------------------------------------------------
// EOF
| 19.600917 | 81 | 0.60227 |
4742e3ac5dd0ed58c2b533cd1b73fc5e9a9765d7 | 1,453 | html | HTML | templates/base.html | Zenephi13/build-a-blog | c6d5cef4617145c1d747b16670b55932b09b494b | [
"Unlicense"
] | null | null | null | templates/base.html | Zenephi13/build-a-blog | c6d5cef4617145c1d747b16670b55932b09b494b | [
"Unlicense"
] | null | null | null | templates/base.html | Zenephi13/build-a-blog | c6d5cef4617145c1d747b16670b55932b09b494b | [
"Unlicense"
] | null | null | null | <!DOCTYPE html>
<html>
<head>
<title>Build-A-Blog</title>
<style type="text/css">
body {
font-family: sans-serif;
width: 800px;
margin: 0 auto;
padding: 10px;
}
label {
display: block;
font-size: 20px;
}
input[type=text] {
width: 400px;
font-size: 20px;
padding: 2px;
}
textarea {
width: 400px;
height: 200px;
font-size: 17px;
font-family: monospace;
}
input[type=submit] {
font-size: 24px;
}
hr {
margin: 20px auto;
}
.blog + .blog {
margin-top: 20px;
}
.blog-title {
font-weight: bold;
}
.blog-body {
margin: 0;
font-size: 17px;
}
.error {
color: red;
}
</style>
</head>
<body>
<h1>
<a href="/">Build-A-Blog</a>
</h1>
<ul>
<a href="/newpost">Post New Blog</a>
<a href="/blog">View Recent Blogs</a>
</ul>
{% block content %}
{% endblock %}
</body>
</html>
| 20.180556 | 49 | 0.333792 |
dfc846fa941f2173e3e8be625ca9b1da70b1b19a | 1,361 | ts | TypeScript | app/header-block.component.ts | quantumleeps/dataView | 138ec001cf21599fa1ca5cbb8541348f286206d4 | [
"MIT"
] | null | null | null | app/header-block.component.ts | quantumleeps/dataView | 138ec001cf21599fa1ca5cbb8541348f286206d4 | [
"MIT"
] | null | null | null | app/header-block.component.ts | quantumleeps/dataView | 138ec001cf21599fa1ca5cbb8541348f286206d4 | [
"MIT"
] | null | null | null | import { Component, OnInit } from '@angular/core';
import { FieldDataService } from './field-data.service'
@Component({
selector: 'header-block',
providers: [FieldDataService],
template: `
<h1>Blue Hills Data Entry</h1>
<div class="button-block">
<button>Pretreatment</button>
<button class="btn btn-success">Train 1</button>
<button class="btn">Train 2</button>
<button>Train 3</button>
<button>Train 4</button>
<button>Train 5</button>
<button>Train 6</button>
<button>Post Treatment</button>
<button>Product Transfer</button>
</div>
`,
styles: [`
.button-block {
text-align: center;
margin: 5px;
}
button {
margin-left: 8px;
margin-right: 8px
font-size: 12px;
}
h1 {
margin-bottom: 20px;
}
`]
})
export class HeaderBlockComponent implements OnInit {
equipment:string[] = []
equipmentMap = [
{id: "t01", description: "Train 1"},
{id: "t02", description: "Train 2"},
{id: "t03", description: "Train 3"}
]
test:string[] = ["test1", "test2", "test2", "test2", "test3", "test3"]
tester:string = "test2"
constructor(public fieldDataService: FieldDataService) {}
ngOnInit() {
}
}
| 20.313433 | 73 | 0.5518 |
d7dba33ba10b446f4eb0c26a1aa11ab7edd60b3a | 1,378 | swift | Swift | src/Day6Part2/Sources/Day6Part2/main.swift | nickygerritsen/AdventOfCode2018 | 4a69d4acf8c55e3118e1428fb949afda52ff6b83 | [
"MIT"
] | null | null | null | src/Day6Part2/Sources/Day6Part2/main.swift | nickygerritsen/AdventOfCode2018 | 4a69d4acf8c55e3118e1428fb949afda52ff6b83 | [
"MIT"
] | null | null | null | src/Day6Part2/Sources/Day6Part2/main.swift | nickygerritsen/AdventOfCode2018 | 4a69d4acf8c55e3118e1428fb949afda52ff6b83 | [
"MIT"
] | null | null | null | import Shared
import Foundation
struct Point {
let x: Int
let y: Int
static func distance(_ p1: Point, _ p2: Point) -> Int {
return abs(p1.x - p2.x) + abs(p1.y - p2.y)
}
}
extension Point: Input {
static func convert(contents: String) -> Point? {
let parts = contents.split(separator: ",")
if let x = Int(parts[0]), let y = Int(parts[1].trimmingCharacters(in: .whitespacesAndNewlines)) {
return Point(x: x, y: y)
}
return nil
}
}
if let input: [Point] = readInput(day: 6) {
var points: [Int: Point] = [:]
for idx in 0..<input.count {
points[idx] = input[idx]
}
let maxDistance = 10000
// Determine the max distance we should check: this is maxDistance / #points
let maxCheck = maxDistance / points.count
var answer = 0
if let maxXP = input.min(by: { $0.x > $1.x }),
let maxYP = input.min(by: { $0.y > $1.y }) {
let maxX = maxXP.x
let maxY = maxYP.y
for x in -maxCheck...maxX + maxCheck {
for y in -maxCheck...maxY + maxCheck {
let p = Point(x: x, y: y)
let totalDistance = points.map({ Point.distance(p, $0.value) }).reduce(0, +)
if totalDistance < maxDistance {
answer += 1
}
}
}
}
print(answer)
} | 26.5 | 105 | 0.528302 |
c7635801c3db6ba03fc0704cd38b2271690f6bb1 | 882 | lua | Lua | scripts/entities/box.lua | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | scripts/entities/box.lua | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | scripts/entities/box.lua | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | RegisterClientScript()
RegisterClientAssets("box.png")
ENTITY.IsNetworked = true
ENTITY.CollisionType = 2
ENTITY.PlayerControlled = false
ENTITY.MaxHealth = 1000
ENTITY.Properties = {
{ Name = "asleep", Type = PropertyType.Boolean, Default = false, Shared = true },
{ Name = "dynamic", Type = PropertyType.Boolean, Default = true, Shared = true },
{ Name = "size", Type = PropertyType.Float, Default = 1.0, Shared = true }
}
function ENTITY:Initialize()
local size = self:GetProperty("size")
local colliderSize = Vec2(0.2, 0.2) * size * 256 / 2
self:SetCollider(Rect(-colliderSize, colliderSize))
if (self:GetProperty("dynamic")) then
self:InitRigidBody(size * 50, 10)
-- Temp fix
if (self:GetProperty("asleep")) then
self:ForceSleep()
end
end
if (CLIENT) then
self:AddSprite({
Scale = Vec2(0.2, 0.2) * size,
TexturePath = "box.png"
})
end
end
| 23.837838 | 82 | 0.688209 |
542ba49b49170fd3a0cd756555df13278fe23802 | 2,266 | go | Go | vendor/github.com/google/go-containerregistry/pkg/internal/retry/retry.go | hoozecn/kaniko | ee31dc93b61c36d613a8ec056eeb12f11a7b3634 | [
"Apache-2.0"
] | 9,434 | 2018-04-17T15:58:05.000Z | 2022-03-31T19:01:07.000Z | vendor/github.com/google/go-containerregistry/pkg/internal/retry/retry.go | hoozecn/kaniko | ee31dc93b61c36d613a8ec056eeb12f11a7b3634 | [
"Apache-2.0"
] | 3,103 | 2018-08-24T16:27:12.000Z | 2022-03-31T23:12:07.000Z | vendor/github.com/google/go-containerregistry/pkg/internal/retry/retry.go | hoozecn/kaniko | ee31dc93b61c36d613a8ec056eeb12f11a7b3634 | [
"Apache-2.0"
] | 1,132 | 2018-04-17T17:58:58.000Z | 2022-03-31T12:30:45.000Z | // Copyright 2019 Google LLC 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.
// Package retry provides methods for retrying operations. It is a thin wrapper
// around k8s.io/apimachinery/pkg/util/wait to make certain operations easier.
package retry
import (
"context"
"fmt"
"github.com/google/go-containerregistry/pkg/internal/retry/wait"
)
// Backoff is an alias of our own wait.Backoff to avoid name conflicts with
// the kubernetes wait package. Typing retry.Backoff is aesier than fixing
// the wrong import every time you use wait.Backoff.
type Backoff = wait.Backoff
// This is implemented by several errors in the net package as well as our
// transport.Error.
type temporary interface {
Temporary() bool
}
// IsTemporary returns true if err implements Temporary() and it returns true.
func IsTemporary(err error) bool {
if err == context.DeadlineExceeded {
return false
}
if te, ok := err.(temporary); ok && te.Temporary() {
return true
}
return false
}
// IsNotNil returns true if err is not nil.
func IsNotNil(err error) bool {
return err != nil
}
// Predicate determines whether an error should be retried.
type Predicate func(error) (retry bool)
// Retry retries a given function, f, until a predicate is satisfied, using
// exponential backoff. If the predicate is never satisfied, it will return the
// last error returned by f.
func Retry(f func() error, p Predicate, backoff wait.Backoff) (err error) {
if f == nil {
return fmt.Errorf("nil f passed to retry")
}
if p == nil {
return fmt.Errorf("nil p passed to retry")
}
condition := func() (bool, error) {
err = f()
if p(err) {
return false, nil
}
return true, err
}
wait.ExponentialBackoff(backoff, condition)
return
}
| 29.051282 | 79 | 0.729921 |
56e65b8ddc4e1e0e411fa63edfa07cebd2f85cbc | 125 | ts | TypeScript | test/to.ts | xxczaki/timestampy | d406684ed9ceceb02de3b5e4edc239e804218c2c | [
"MIT"
] | 21 | 2019-07-27T17:49:54.000Z | 2021-11-09T11:06:16.000Z | test/to.ts | xxczaki/timestampy | d406684ed9ceceb02de3b5e4edc239e804218c2c | [
"MIT"
] | null | null | null | test/to.ts | xxczaki/timestampy | d406684ed9ceceb02de3b5e4edc239e804218c2c | [
"MIT"
] | null | null | null | import test from 'ava';
import {toDate} from '../dist';
test('to date', t => {
t.is(toDate(1564146357), '7/26/2019');
});
| 15.625 | 39 | 0.592 |
d07c50d98ffb3c870a402d004cbc592dd88fc0bc | 4,571 | kt | Kotlin | app/src/main/java/com/trinity/sample/fragment/VideoFragment.kt | TianLuluC/trinity | 309618a75782274379c5d3b77472bcc2bcf7adcb | [
"Apache-2.0"
] | 788 | 2019-09-16T03:36:49.000Z | 2022-03-23T01:26:01.000Z | app/src/main/java/com/trinity/sample/fragment/VideoFragment.kt | TianLuluC/trinity | 309618a75782274379c5d3b77472bcc2bcf7adcb | [
"Apache-2.0"
] | 118 | 2019-09-27T15:27:48.000Z | 2021-12-31T16:12:17.000Z | app/src/main/java/com/trinity/sample/fragment/VideoFragment.kt | TianLuluC/trinity | 309618a75782274379c5d3b77472bcc2bcf7adcb | [
"Apache-2.0"
] | 253 | 2019-09-16T08:09:24.000Z | 2022-03-20T10:11:06.000Z | package com.trinity.sample.fragment
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.trinity.sample.R
import com.trinity.sample.adapter.MediaAdapter
import com.trinity.sample.entity.MediaItem
import com.trinity.sample.view.SpacesItemDecoration
import kotlinx.android.synthetic.main.item_media.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.*
class VideoFragment : Fragment() {
private lateinit var mAdapter: MediaAdapter
companion object {
private const val DURATION = "duration"
private val PROJECTION = arrayOf(MediaStore.Files.FileColumns._ID, MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.MIME_TYPE, MediaStore.MediaColumns.WIDTH, MediaStore.MediaColumns.HEIGHT, DURATION)
private const val ORDER_BY = MediaStore.Files.FileColumns._ID + " DESC"
private val QUERY_URI = MediaStore.Files.getContentUri("external")
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_video, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mAdapter = MediaAdapter()
val recyclerView = view.findViewById<RecyclerView>(R.id.recycler_view)
recyclerView.layoutManager = GridLayoutManager(activity, 4)
recyclerView.adapter = mAdapter
recyclerView.addItemDecoration(SpacesItemDecoration(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2f, resources.displayMetrics).toInt(), 4))
GlobalScope.launch(Dispatchers.IO) {
loadVideo()
}
}
fun getSelectMedias(): MutableList<MediaItem> {
return mAdapter.getSelectMedia()
}
private suspend fun loadVideo() {
val medias = mutableListOf<MediaItem>()
activity?.let {
val cursor = it.contentResolver.query(QUERY_URI,
PROJECTION,
getSelectionArgsForSingleMediaCondition(getDurationCondition(0, 0)),
arrayOf(MediaStore.Files.FileColumns.MEDIA_TYPE_VIDEO.toString()), ORDER_BY)
while (cursor?.moveToNext() == true) {
val id = cursor.getLong(cursor.getColumnIndexOrThrow(PROJECTION[0]))
val path = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val uri = QUERY_URI.buildUpon().appendPath(id.toString()).build().toString()
val filePathColumn = arrayOf(MediaStore.MediaColumns.DATA)
val pathCursor = it.contentResolver.query(Uri.parse(uri), filePathColumn, null, null, null)
pathCursor?.moveToFirst()
val columnIndex = pathCursor?.getColumnIndex(filePathColumn[0]) ?: 0
val filePath = pathCursor?.getString(columnIndex) ?: ""
pathCursor?.close()
filePath
} else {
cursor.getString(cursor.getColumnIndexOrThrow(PROJECTION[1]))
}
val pictureType = cursor.getString(cursor.getColumnIndexOrThrow(PROJECTION[2]))
val width = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[3]))
val height = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[4]))
val duration = cursor.getInt(cursor.getColumnIndexOrThrow(PROJECTION[5]))
val item = MediaItem(path, pictureType, width, height)
item.duration = duration
medias.add(item)
}
cursor?.close()
withContext(Dispatchers.Main) {
mAdapter.addMedias(medias)
}
}
}
private fun getSelectionArgsForSingleMediaCondition(timeCondition: String): String {
return (MediaStore.Files.FileColumns.MEDIA_TYPE + "=?"
+ " AND " + MediaStore.MediaColumns.SIZE + ">0"
+ " AND " + timeCondition)
}
private fun getDurationCondition(exMaxLimit: Long, exMinLimit: Long): String {
val videoMinS = 1000L
val videoMaxS = 60 * 5 * 1000L
var maxS = if (videoMaxS == 0L) java.lang.Long.MAX_VALUE else videoMaxS
if (exMaxLimit != 0L) {
maxS = Math.min(maxS, exMaxLimit)
}
return String.format(Locale.CHINA, "%d <%s duration and duration <= %d",
Math.max(exMinLimit, videoMinS),
if (Math.max(exMinLimit, videoMinS) == 0L) "" else "=",
maxS)
}
} | 40.8125 | 208 | 0.725881 |
2a2fe32d1e14a948fa479eb0e2e7f5ff5923bc7f | 25,315 | java | Java | src/test/java/com/android/tools/r8/smali/ConstantFoldingTest.java | MIPS/external-r8 | be69fcefad315b2068a9903019108f879ca4db56 | [
"BSD-3-Clause"
] | 26 | 2017-08-19T03:30:27.000Z | 2021-11-14T18:13:57.000Z | src/test/java/com/android/tools/r8/smali/ConstantFoldingTest.java | Unpublished/r8 | 0541f5685b09694e9f4478f5156921055cb149ae | [
"BSD-3-Clause"
] | 1 | 2021-04-05T09:52:38.000Z | 2021-04-07T02:30:26.000Z | src/test/java/com/android/tools/r8/smali/ConstantFoldingTest.java | Unpublished/r8 | 0541f5685b09694e9f4478f5156921055cb149ae | [
"BSD-3-Clause"
] | 3 | 2018-04-04T17:00:51.000Z | 2021-05-22T08:57:54.000Z | // Copyright (c) 2016, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.smali;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.android.tools.r8.code.Const4;
import com.android.tools.r8.code.DivIntLit8;
import com.android.tools.r8.code.Instruction;
import com.android.tools.r8.code.RemIntLit8;
import com.android.tools.r8.code.Return;
import com.android.tools.r8.code.ReturnWide;
import com.android.tools.r8.graph.DexCode;
import com.android.tools.r8.graph.DexEncodedMethod;
import com.android.tools.r8.ir.code.Cmp.Bias;
import com.android.tools.r8.ir.code.If.Type;
import com.android.tools.r8.ir.code.SingleConstant;
import com.android.tools.r8.ir.code.WideConstant;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class ConstantFoldingTest extends SmaliTestBase {
public void generateBinopTest(String type, String op, List<Long> values, Long result) {
boolean wide = type.equals("long") || type.equals("double");
StringBuilder source = new StringBuilder();
int factor = wide ? 2 : 1;
for (int i = 0; i < values.size(); i++) {
source.append(" ");
source.append(wide ? "const-wide " : "const ");
source.append("v" + (i * factor));
source.append(", ");
source.append("0x" + Long.toHexString(values.get(i)));
source.append(wide ? "L" : "");
source.append("\n");
}
for (int i = 0; i < values.size() - 1; i++) {
source.append(" ");
source.append(op + "-" + type + "/2addr ");
source.append("v" + ((i + 1) * factor));
source.append(", ");
source.append("v" + (i * factor));
source.append("\n");
}
source.append(" ");
source.append(wide ? "return-wide " : "return ");
source.append("v" + ((values.size() - 1) * factor));
DexEncodedMethod method = oneMethodApplication(
type, Collections.singletonList(type),
values.size() * factor,
source.toString());
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
if (wide) {
assertTrue(code.instructions[0] instanceof WideConstant);
assertEquals(result.longValue(), ((WideConstant) code.instructions[0]).decodedValue());
assertTrue(code.instructions[1] instanceof ReturnWide);
} else {
assertTrue(code.instructions[0] instanceof SingleConstant);
assertEquals(
result.longValue(), (long) ((SingleConstant) code.instructions[0]).decodedValue());
assertTrue(code.instructions[1] instanceof Return);
}
}
private long floatBits(float f) {
return Float.floatToIntBits(f);
}
private long doubleBits(double d) {
return Double.doubleToLongBits(d);
}
ImmutableList<Long> arguments = ImmutableList.of(1L, 2L, 3L, 4L);
ImmutableList<Long> floatArguments = ImmutableList.of(
floatBits(1.0f), floatBits(2.0f), floatBits(3.0f), floatBits(4.0f));
ImmutableList<Long> doubleArguments = ImmutableList.of(
doubleBits(1.0), doubleBits(2.0), doubleBits(3.0), doubleBits(4.0));
@Test
public void addFold() {
generateBinopTest("int", "add", arguments, 10L);
generateBinopTest("long", "add", arguments, 10L);
generateBinopTest("float", "add", floatArguments, floatBits(10.0f));
generateBinopTest("double", "add", doubleArguments, doubleBits(10.0));
}
@Test
public void mulFold() {
generateBinopTest("int", "mul", arguments, 24L);
generateBinopTest("long", "mul", arguments, 24L);
generateBinopTest("float", "mul", floatArguments, floatBits(24.0f));
generateBinopTest("double", "mul", doubleArguments, doubleBits(24.0));
}
@Test
public void subFold() {
generateBinopTest("int", "sub", arguments.reverse(), -2L);
generateBinopTest("long", "sub", arguments.reverse(), -2L);
generateBinopTest("float", "sub", floatArguments.reverse(), floatBits(-2.0f));
generateBinopTest("double", "sub", doubleArguments.reverse(), doubleBits(-2.0));
}
@Test
public void divFold() {
ImmutableList<Long> arguments = ImmutableList.of(2L, 24L, 48L, 4L);
ImmutableList<Long> floatArguments = ImmutableList.of(
floatBits(2.0f), floatBits(24.0f), floatBits(48.0f), floatBits(4.0f));
ImmutableList<Long> doubleArguments = ImmutableList.of(
doubleBits(2.0), doubleBits(24.0), doubleBits(48.0), doubleBits(4.0));
generateBinopTest("int", "div", arguments, 1L);
generateBinopTest("long", "div", arguments, 1L);
generateBinopTest("float", "div", floatArguments, floatBits(1.0f));
generateBinopTest("double", "div", doubleArguments, doubleBits(1.0));
}
@Test
public void remFold() {
ImmutableList<Long> arguments = ImmutableList.of(10L, 6L, 3L, 2L);
ImmutableList<Long> floatArguments = ImmutableList.of(
floatBits(10.0f), floatBits(6.0f), floatBits(3.0f), floatBits(2.0f));
ImmutableList<Long> doubleArguments = ImmutableList.of(
doubleBits(10.0), doubleBits(6.0), doubleBits(3.0), doubleBits(2.0));
generateBinopTest("int", "rem", arguments, 2L);
generateBinopTest("long", "rem", arguments, 2L);
generateBinopTest("float", "rem", floatArguments, floatBits(2.0f));
generateBinopTest("double", "rem", doubleArguments, doubleBits(2.0));
}
@Test
public void divIntFoldDivByZero() {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.singletonList("int"),
2,
" const/4 v0, 1 ",
" const/4 v1, 0 ",
" div-int/2addr v0, v1 ",
" return v0\n "
);
DexCode code = method.getCode().asDexCode();
// Division by zero is not folded, but div-int/lit8 is used.
assertEquals(3, code.instructions.length);
assertTrue(code.instructions[0] instanceof Const4);
assertTrue(code.instructions[1] instanceof DivIntLit8);
assertEquals(0, ((DivIntLit8) code.instructions[1]).CC);
assertTrue(code.instructions[2] instanceof Return);
}
@Test
public void divIntFoldRemByZero() {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.singletonList("int"),
2,
" const/4 v0, 1 ",
" const/4 v1, 0 ",
" rem-int/2addr v0, v1 ",
" return v0\n "
);
DexCode code = method.getCode().asDexCode();
// Division by zero is not folded, but rem-int/lit8 is used.
assertEquals(3, code.instructions.length);
assertTrue(code.instructions[0] instanceof Const4);
assertTrue(code.instructions[1] instanceof RemIntLit8);
assertEquals(0, ((RemIntLit8) code.instructions[1]).CC);
assertTrue(code.instructions[2] instanceof Return);
}
public void generateUnopTest(String type, String op, Long value, Long result) {
boolean wide = type.equals("long") || type.equals("double");
StringBuilder source = new StringBuilder();
source.append(" ");
source.append(wide ? "const-wide " : "const ");
source.append("v0 , ");
source.append("0x" + Long.toHexString(value));
source.append(wide ? "L" : "");
source.append("\n");
source.append(" ");
source.append(op + "-" + type + " v0, v0\n");
source.append(" ");
source.append(wide ? "return-wide v0" : "return v0");
DexEncodedMethod method = oneMethodApplication(
type, Collections.singletonList(type),
wide ? 2 : 1,
source.toString());
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
if (wide) {
assertTrue(code.instructions[0] instanceof WideConstant);
assertEquals(result.longValue(), ((WideConstant) code.instructions[0]).decodedValue());
assertTrue(code.instructions[1] instanceof ReturnWide);
} else {
assertTrue(code.instructions[0] instanceof SingleConstant);
assertEquals(
result.longValue(), (long) ((SingleConstant) code.instructions[0]).decodedValue());
assertTrue(code.instructions[1] instanceof Return);
}
}
@Test
public void negFold() {
generateUnopTest("int", "neg", 2L, -2L);
generateUnopTest("int", "neg", -2L, 2L);
generateUnopTest("long", "neg", 2L, -2L);
generateUnopTest("long", "neg", -2L, 2L);
generateUnopTest("float", "neg", floatBits(2.0f), floatBits(-2.0f));
generateUnopTest("float", "neg", floatBits(-2.0f), floatBits(2.0f));
generateUnopTest("float", "neg", floatBits(0.0f), floatBits(-0.0f));
generateUnopTest("float", "neg", floatBits(-0.0f), floatBits(0.0f));
generateUnopTest("double", "neg", doubleBits(2.0), doubleBits(-2.0));
generateUnopTest("double", "neg", doubleBits(-2.0), doubleBits(2.0));
generateUnopTest("double", "neg", doubleBits(0.0), doubleBits(-0.0));
generateUnopTest("double", "neg", doubleBits(-0.0), doubleBits(0.0));
}
private void assertConstValue(int expected, Instruction insn) {
assertTrue(insn instanceof SingleConstant);
assertEquals(expected, ((SingleConstant) insn).decodedValue());
}
private void assertConstValue(long expected, Instruction insn) {
assertTrue(insn instanceof WideConstant);
assertEquals(expected, ((WideConstant) insn).decodedValue());
}
public void testLogicalOperatorsFolding(String op, int[] v) {
int v0 = v[0];
int v1 = v[1];
int v2 = v[2];
int v3 = v[3];
int expected = 0;
switch (op) {
case "and":
expected = v0 & v1 & v2 & v3;
break;
case "or":
expected = v0 | v1 | v2 | v3;
break;
case "xor":
expected = v0 ^ v1 ^ v2 ^ v3;
break;
default:
fail("Unsupported logical binop " + op);
}
DexEncodedMethod method = oneMethodApplication(
"int", Collections.singletonList("int"),
4,
" const v0, " + v0,
" const v1, " + v1,
" const v2, " + v2,
" const v3, " + v3,
// E.g. and-int//2addr v1, v0
" " + op + "-int/2addr v1, v0 ",
" " + op + "-int/2addr v2, v1 ",
" " + op + "-int/2addr v3, v2 ",
" return v3\n "
);
DexCode code = method.getCode().asDexCode();
// Test that this just returns a constant.
assertEquals(2, code.instructions.length);
assertConstValue(expected, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
@Test
public void logicalOperatorsFolding() {
int[][] testValues = new int[][]{
new int[]{0x00, 0x00, 0x00, 0x00},
new int[]{0x0b, 0x06, 0x03, 0x00},
new int[]{0x0f, 0x07, 0x03, 0x01},
new int[]{0x08, 0x04, 0x02, 0x01},
};
for (int[] values : testValues) {
testLogicalOperatorsFolding("and", values);
testLogicalOperatorsFolding("or", values);
testLogicalOperatorsFolding("xor", values);
}
}
private void testShiftOperatorsFolding(String op, int[] v) {
int v0 = v[0];
int v1 = v[1];
int v2 = v[2];
int v3 = v[3];
int expected = 0;
switch (op) {
case "shl":
v0 = v0 << v1;
v0 = v0 << v2;
v0 = v0 << v3;
break;
case "shr":
v0 = v0 >> v1;
v0 = v0 >> v2;
v0 = v0 >> v3;
break;
case "ushr":
v0 = v0 >>> v1;
v0 = v0 >>> v2;
v0 = v0 >>> v3;
break;
default:
fail("Unsupported shift " + op);
}
expected = v0;
DexEncodedMethod method = oneMethodApplication(
"int", Collections.singletonList("int"),
4,
" const v0, " + v[0],
" const v1, " + v[1],
" const v2, " + v[2],
" const v3, " + v[3],
// E.g. and-int//2addr v1, v0
" " + op + "-int/2addr v0, v1 ",
" " + op + "-int/2addr v0, v2 ",
" " + op + "-int/2addr v0, v3 ",
" return v0\n "
);
DexCode code = method.getCode().asDexCode();
// Test that this just returns a constant.
assertEquals(2, code.instructions.length);
assertConstValue(expected, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
@Test
public void shiftOperatorsFolding() {
int[][] testValues = new int[][]{
new int[]{0x01, 0x01, 0x01, 0x01},
new int[]{0x01, 0x02, 0x03, 0x04},
new int[]{0x7f000000, 0x01, 0x2, 0x03},
new int[]{0x80000000, 0x01, 0x2, 0x03},
new int[]{0xffffffff, 0x01, 0x2, 0x03},
};
for (int[] values : testValues) {
testShiftOperatorsFolding("shl", values);
testShiftOperatorsFolding("shr", values);
testShiftOperatorsFolding("ushr", values);
}
}
private void testShiftOperatorsFoldingWide(String op, long[] v) {
long v0 = v[0];
int v2 = (int) v[1];
int v4 = (int) v[2];
int v6 = (int) v[3];
long expected = 0;
switch (op) {
case "shl":
v0 = v0 << v2;
v0 = v0 << v4;
v0 = v0 << v6;
break;
case "shr":
v0 = v0 >> v2;
v0 = v0 >> v4;
v0 = v0 >> v6;
break;
case "ushr":
v0 = v0 >>> v2;
v0 = v0 >>> v4;
v0 = v0 >>> v6;
break;
default:
fail("Unsupported shift " + op);
}
expected = v0;
DexEncodedMethod method = oneMethodApplication(
"long", Collections.singletonList("long"),
5,
" const-wide v0, 0x" + Long.toHexString(v[0]) + "L",
" const v2, " + v[1],
" const v3, " + v[2],
" const v4, " + v[3],
// E.g. and-long//2addr v1, v0
" " + op + "-long/2addr v0, v2 ",
" " + op + "-long/2addr v0, v3 ",
" " + op + "-long/2addr v0, v4 ",
" return-wide v0\n "
);
DexCode code = method.getCode().asDexCode();
// Test that this just returns a constant.
assertEquals(2, code.instructions.length);
assertConstValue(expected, code.instructions[0]);
assertTrue(code.instructions[1] instanceof ReturnWide);
}
@Test
public void shiftOperatorsFoldingWide() {
long[][] testValues = new long[][]{
new long[]{0x01, 0x01, 0x01, 0x01},
new long[]{0x01, 0x02, 0x03, 0x04},
new long[]{0x7f0000000000L, 0x01, 0x2, 0x03},
new long[]{0x800000000000L, 0x01, 0x2, 0x03},
new long[]{0x7f00000000000000L, 0x01, 0x2, 0x03},
new long[]{0x8000000000000000L, 0x01, 0x2, 0x03},
new long[]{0xffffffffffffffffL, 0x01, 0x2, 0x03},
};
for (long[] values : testValues) {
testShiftOperatorsFoldingWide("shl", values);
testShiftOperatorsFoldingWide("shr", values);
testShiftOperatorsFoldingWide("ushr", values);
}
}
@Test
public void notIntFold() {
int[] testValues = new int[]{0, 1, 0xff, 0xffffffff, 0xff000000, 0x80000000};
for (int value : testValues) {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.emptyList(),
1,
" const v0, " + value,
" not-int v0, v0",
" return v0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
assertConstValue(~value, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
}
@Test
public void notLongFold() {
long[] testValues = new long[]{
0L,
1L,
0xffL,
0xffffffffffffffffL,
0x00ffffffffffffffL,
0xff00000000000000L,
0x8000000000000000L
};
for (long value : testValues) {
DexEncodedMethod method = oneMethodApplication(
"long", Collections.emptyList(),
2,
" const-wide v0, 0x" + Long.toHexString(value) + "L",
" not-long v0, v0",
" return-wide v0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
assertConstValue(~value, code.instructions[0]);
assertTrue(code.instructions[1] instanceof ReturnWide);
}
}
@Test
public void negIntFold() {
int[] testValues = new int[]{0, 1, 0xff, 0xffffffff, 0xff000000, 0x80000000};
for (int value : testValues) {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.emptyList(),
1,
" const v0, " + value,
" neg-int v0, v0",
" return v0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
assertConstValue(-value, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
}
@Test
public void negLongFold() {
long[] testValues = new long[]{
0L,
1L,
0xffL,
0xffffffffffffffffL,
0x00ffffffffffffffL,
0xff00000000000000L,
0x8000000000000000L
};
for (long value : testValues) {
DexEncodedMethod method = oneMethodApplication(
"long", Collections.emptyList(),
2,
" const-wide v0, 0x" + Long.toHexString(value) + "L",
" neg-long v0, v0",
" return-wide v0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
long expected = -value;
assertConstValue(-value, code.instructions[0]);
assertTrue(code.instructions[1] instanceof ReturnWide);
}
}
@Test
public void cmpFloatFold() {
String[] ifOpcode = new String[6];
ifOpcode[Type.EQ.ordinal()] = "if-eqz";
ifOpcode[Type.NE.ordinal()] = "if-nez";
ifOpcode[Type.LE.ordinal()] = "if-lez";
ifOpcode[Type.GE.ordinal()] = "if-gez";
ifOpcode[Type.LT.ordinal()] = "if-ltz";
ifOpcode[Type.GT.ordinal()] = "if-gtz";
class FloatTestData {
final float a;
final float b;
final boolean results[];
FloatTestData(float a, float b) {
this.a = a;
this.b = b;
results = new boolean[6];
results[Type.EQ.ordinal()] = a == b;
results[Type.NE.ordinal()] = a != b;
results[Type.LE.ordinal()] = a <= b;
results[Type.GE.ordinal()] = a >= b;
results[Type.LT.ordinal()] = a < b;
results[Type.GT.ordinal()] = a > b;
}
}
float[] testValues = new float[]{
Float.NEGATIVE_INFINITY,
-100.0f,
-0.0f,
0.0f,
100.0f,
Float.POSITIVE_INFINITY,
Float.NaN
};
List<FloatTestData> tests = new ArrayList<>();
for (int i = 0; i < testValues.length; i++) {
for (int j = 0; j < testValues.length; j++) {
tests.add(new FloatTestData(testValues[i], testValues[j]));
}
}
for (FloatTestData test : tests) {
for (Type type : Type.values()) {
for (Bias bias : Bias.values()) {
if (bias == Bias.NONE) {
// Bias NONE is only for long comparison.
continue;
}
// If no NaNs are involved either bias produce the same result.
if (Float.isNaN(test.a) || Float.isNaN(test.b)) {
// For NaN comparison only test with the bias that provide Java semantics.
// The Java Language Specification 4.2.3. Floating-Point Types, Formats, and Values
// says:
//
// The numerical comparison operators <, <=, >, and >= return false if either or both
// operands are NaN
if ((type == Type.GE || type == Type.GT) && bias == Bias.GT) {
continue;
}
if ((type == Type.LE || type == Type.LT) && bias == Bias.LT) {
continue;
}
}
String cmpInstruction;
if (bias == Bias.LT) {
cmpInstruction = " cmpl-float v0, v0, v1";
} else {
cmpInstruction = " cmpg-float v0, v0, v1";
}
DexEncodedMethod method = oneMethodApplication(
"int", Collections.emptyList(),
2,
" const v0, 0x" + Integer.toHexString(Float.floatToRawIntBits(test.a)),
" const v1, 0x" + Integer.toHexString(Float.floatToRawIntBits(test.b)),
cmpInstruction,
" " + ifOpcode[type.ordinal()] + " v0, :label_2",
" const v0, 0",
":label_1",
" return v0",
":label_2",
" const v0, 1",
" goto :label_1"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
int expected = test.results[type.ordinal()] ? 1 : 0;
assertConstValue(expected, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
}
}
}
@Test
public void cmpDoubleFold() {
String[] ifOpcode = new String[6];
ifOpcode[Type.EQ.ordinal()] = "if-eqz";
ifOpcode[Type.NE.ordinal()] = "if-nez";
ifOpcode[Type.LE.ordinal()] = "if-lez";
ifOpcode[Type.GE.ordinal()] = "if-gez";
ifOpcode[Type.LT.ordinal()] = "if-ltz";
ifOpcode[Type.GT.ordinal()] = "if-gtz";
class DoubleTestData {
final double a;
final double b;
final boolean results[];
DoubleTestData(double a, double b) {
this.a = a;
this.b = b;
results = new boolean[6];
results[Type.EQ.ordinal()] = a == b;
results[Type.NE.ordinal()] = a != b;
results[Type.LE.ordinal()] = a <= b;
results[Type.GE.ordinal()] = a >= b;
results[Type.LT.ordinal()] = a < b;
results[Type.GT.ordinal()] = a > b;
}
}
double[] testValues = new double[]{
Double.NEGATIVE_INFINITY,
-100.0f,
-0.0f,
0.0f,
100.0f,
Double.POSITIVE_INFINITY,
Double.NaN
};
List<DoubleTestData> tests = new ArrayList<>();
for (int i = 0; i < testValues.length; i++) {
for (int j = 0; j < testValues.length; j++) {
tests.add(new DoubleTestData(testValues[i], testValues[j]));
}
}
for (DoubleTestData test : tests) {
for (Type type : Type.values()) {
for (Bias bias : Bias.values()) {
if (bias == Bias.NONE) {
// Bias NONE is only for long comparison.
continue;
}
if (Double.isNaN(test.a) || Double.isNaN(test.b)) {
// For NaN comparison only test with the bias that provide Java semantics.
// The Java Language Specification 4.2.3. Doubleing-Point Types, Formats, and Values
// says:
//
// The numerical comparison operators <, <=, >, and >= return false if either or both
// operands are NaN
if ((type == Type.GE || type == Type.GT) && bias == Bias.GT) {
continue;
}
if ((type == Type.LE || type == Type.LT) && bias == Bias.LT) {
continue;
}
}
String cmpInstruction;
if (bias == Bias.LT) {
cmpInstruction = " cmpl-double v0, v0, v2";
} else {
cmpInstruction = " cmpg-double v0, v0, v2";
}
DexEncodedMethod method = oneMethodApplication(
"int", Collections.emptyList(),
4,
" const-wide v0, 0x" + Long.toHexString(Double.doubleToRawLongBits(test.a)) + "L",
" const-wide v2, 0x" + Long.toHexString(Double.doubleToRawLongBits(test.b)) + "L",
cmpInstruction,
" " + ifOpcode[type.ordinal()] + " v0, :label_2",
" const v0, 0",
":label_1",
" return v0",
":label_2",
" const v0, 1",
" goto :label_1"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
int expected = test.results[type.ordinal()] ? 1 : 0;
assertConstValue(expected, code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
}
}
}
@Test
public void cmpLongFold() {
long[][] longValues = new long[][]{
{Long.MIN_VALUE, 1L},
{Long.MAX_VALUE, 1L},
{Long.MIN_VALUE, 0L},
{Long.MAX_VALUE, 0L},
{Long.MIN_VALUE, -1L},
{Long.MAX_VALUE, -1L},
};
for (long[] values : longValues) {
DexEncodedMethod method = oneMethodApplication(
"int", Collections.emptyList(),
4,
" const-wide v0, 0x" + Long.toHexString(values[0]) + "L",
" const-wide v2, 0x" + Long.toHexString(values[1]) + "L",
" cmp-long v0, v0, v2",
" return v0"
);
DexCode code = method.getCode().asDexCode();
assertEquals(2, code.instructions.length);
assertConstValue(Long.compare(values[0], values[1]), code.instructions[0]);
assertTrue(code.instructions[1] instanceof Return);
}
}
}
| 34.209459 | 99 | 0.574363 |
16cff0463d3ab978f1231c8b963e4d217edbfac3 | 2,667 | ts | TypeScript | sources/components/Program.ts | cedric-demongivert/gl-tool-shader | 1556b71840070bceca573bd25be0a211ddd07b85 | [
"MIT"
] | null | null | null | sources/components/Program.ts | cedric-demongivert/gl-tool-shader | 1556b71840070bceca573bd25be0a211ddd07b85 | [
"MIT"
] | null | null | null | sources/components/Program.ts | cedric-demongivert/gl-tool-shader | 1556b71840070bceca573bd25be0a211ddd07b85 | [
"MIT"
] | null | null | null | import { Component } from '@cedric-demongivert/gl-tool-ecs'
import { ProgramIdentifier } from '../ProgramIdentifier'
import { ShaderIdentifier } from '../ShaderIdentifier'
import { Shader } from './Shader'
export class Program {
/**
* Identifier of this program.
*/
public identifier : ProgramIdentifier
/**
* Vertex shader associated to this program.
*/
public vertex : Component<Shader>
/**
* Fragment shader associated to this program.
*/
public fragment : Component<Shader>
/**
* Create a new program.
*/
public constructor (
identifier : ProgramIdentifier = ProgramIdentifier.UNDEFINED
) {
this.identifier = identifier
this.vertex = null
this.fragment = null
}
public getVertexShaderIdentifier () : ShaderIdentifier {
if (this.vertex) {
return this.vertex.data.identifier
} else {
return ShaderIdentifier.UNDEFINED
}
}
public getFragmentShaderIdentifier () : ShaderIdentifier {
if (this.fragment) {
return this.fragment.data.identifier
} else {
return ShaderIdentifier.UNDEFINED
}
}
/**
* Copy the state of the given component.
*
* @param toCopy - A component instance to copy.
*/
public copy (toCopy : Program) : void {
this.identifier = toCopy.identifier
this.vertex = toCopy.vertex
this.fragment = toCopy.fragment
}
/**
* Reset the state of this component to it's default state.
*/
public clear () : void {
this.identifier = ProgramIdentifier.UNDEFINED
this.vertex = null
this.fragment = null
}
/**
* @return An instance of shader equals to this one.
*/
public clone () : Program {
const clone : Program = new Program()
clone.copy(this)
return clone
}
/**
* @see Object.equals
*/
public equals (other : any) : boolean {
if (other == null) return false
if (other === this) return true
if (other instanceof Program) {
return other.identifier === this.identifier &&
Component.equals(other.vertex, this.vertex) &&
Component.equals(other.fragment, this.fragment)
}
return false
}
}
export namespace Program {
export function copy (toCopy : undefined) : undefined
export function copy (toCopy : null) : null
export function copy (toCopy : Program) : Program
/**
* Return an instance of program that is equal to the given one.
*
* @param toCopy - A program instance to copy.
* @return An instance of program that is equal to the given one.
*/
export function copy (toCopy : Program | undefined | null) : Program | undefined | null {
return toCopy == null ? toCopy : toCopy.clone()
}
}
| 24.027027 | 91 | 0.656918 |
bb2bd17406a435e80868cc12e8ce0dbaf7b4de93 | 1,255 | kt | Kotlin | app/src/main/java/io/github/samueljarosinski/ambilight/permission/ScreenCapturePermissionRequester.kt | samueljarosinski/Ambilight | 300ea1579f59b3b3c43e7cdd5b53c12a9eae4ab1 | [
"MIT"
] | null | null | null | app/src/main/java/io/github/samueljarosinski/ambilight/permission/ScreenCapturePermissionRequester.kt | samueljarosinski/Ambilight | 300ea1579f59b3b3c43e7cdd5b53c12a9eae4ab1 | [
"MIT"
] | null | null | null | app/src/main/java/io/github/samueljarosinski/ambilight/permission/ScreenCapturePermissionRequester.kt | samueljarosinski/Ambilight | 300ea1579f59b3b3c43e7cdd5b53c12a9eae4ab1 | [
"MIT"
] | null | null | null | package io.github.samueljarosinski.ambilight.permission
import android.content.Context
import android.content.Intent
import timber.log.Timber
data class PermissionResult(val code: Int, val data: Intent)
typealias OnPermissionGrantedListener = () -> Unit
object ScreenCapturePermissionRequester {
private var onPermissionGrantedListener: OnPermissionGrantedListener? = null
var permissionResult: PermissionResult? = null
internal set(value) {
field = value
if (value != null) {
notifyResultListener()
}
}
fun requestScreenCapturePermission(context: Context, resultListener: OnPermissionGrantedListener) {
Timber.d("Requesting screen capture permission.")
onPermissionGrantedListener = resultListener
if (permissionResult != null) {
Timber.d("Permission already granted.")
notifyResultListener()
} else {
context.startActivity(ActivityScreenCapturePermission.createStartIntent(context))
}
}
private fun notifyResultListener() {
Timber.d("Notifying about permission result.")
onPermissionGrantedListener?.invoke()
onPermissionGrantedListener = null
}
}
| 27.888889 | 103 | 0.69004 |
70cef7bce1dc0f24d6f1a975a9896ddb0c6e70f0 | 3,409 | h | C | kirke/include/kirke/error.h | this-kirke/kirke | 5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c | [
"MIT"
] | null | null | null | kirke/include/kirke/error.h | this-kirke/kirke | 5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c | [
"MIT"
] | null | null | null | kirke/include/kirke/error.h | this-kirke/kirke | 5f0f994a9a86e8bb0711c093f60d0023c6ce3f0c | [
"MIT"
] | null | null | null | /**
* \file kirke/error.h
*/
#ifndef KIRKE__ERROR__H
#define KIRKE__ERROR__H
// System Includes
#include <stdbool.h>
// Internal Includes
#include "kirke/macros.h"
BEGIN_DECLARATIONS
/**
* \defgroup error Error
* @{
*/
/**
* Generally, we consider three types of errors: Machine errors, Programming errors, and User errors
*
* Machine errors occur when the hardware is incapable of handling some operation. The most common
* example of this is out of memory errors. A typical response to these is to panic and exit, but we leave
* the decision of how to handle this situation to the user. For example, the user is notfieid of an out of
* memory error by allocator->out_of_memory().
*
* Programming errors should notify the developer that something is incorrect. We handle these with log
* messages, as in log__warning() or log__error().
*
* User errors are only detectable at runtime, and include issues such as improper input - file not found,
* or invalid formatting, for example. The proper way to handle these is to notify the user, and gracefully
* exit the program.
*
* Handling user errors is the purpose of the Error structure.
*
* The type field is the broad category of error which was encountered. This is generally the name of the
* class which defines and throws the error.
*
* The code field is an integral identifier for the specific error encountered
*
* The message field allows the developer to provide a detailed message describing the error and relevant
* conditions of the error when encountered
*/
/**
* \brief A structure which represents a recoverable runtime error which was encountered.
*/
typedef struct Error{
/**
* A null-terminated C-style string of characters describing the error's broad type
*/
char type[ 32 ];
/**
* An identifier for this error, unique within its type.
*/
unsigned long long code;
/**
* A null-terminated C-style string of characters which describes the specific error condition
*/
char message[ 256 ];
} Error;
/**
* /def ERROR_CODE__NONE
* The error code stored in a default-initialized error. Denotes that no error has occurred, and the contents of
* fields type and message are not defined.
*/
#define Error__None 0
/**
* \brief This method sets the type, code and message of an Error structure.
* \param error A pointer to an Error structure. Upon completion, this will store the specified type,
* code and message.
* \param type A null-terminated C-style string which describes the general type of the message, such
* as the class in which the error originated.
* \param code An identifier for this particular error, unique within its type.
* \param format A format specifier with string replacement tokens, in the style of printf, which are
* used for creating the message
* field.
*/
void error__set( Error *error, const char* type, unsigned long long code, const char* format, ... );
/**
* \brief This method compares two Error structures for equality.
* \param first A pointer to the first error to be compared.
* \param second A pointer to the second error to be compared.
* \returns 1 if the two Error structures contain the same type and code, and 0 otherwise.
*/
bool error__equals( Error* first, Error* second );
/**
* @} group error
*/
END_DECLARATIONS
#endif // KIRKE__ERROR__H
| 34.09 | 113 | 0.722499 |
2f5e0f4e7aa99eee65d8f1679ab4d4716e1635dd | 189 | sql | SQL | egov/egov-wtms/src/main/resources/db/migration/main/V20170605160758__wcms_closeconnection_workflow_nextstate_update.sql | getwasim/egov-smartcity-suites-test | 361238c743d046080d66b7fcbe44673a8a784be2 | [
"MIT"
] | 1 | 2019-07-25T12:44:57.000Z | 2019-07-25T12:44:57.000Z | egov/egov-wtms/src/main/resources/db/migration/main/V20170605160758__wcms_closeconnection_workflow_nextstate_update.sql | getwasim/egov-smartcity-suites-test | 361238c743d046080d66b7fcbe44673a8a784be2 | [
"MIT"
] | 13 | 2020-03-05T00:01:16.000Z | 2022-02-09T22:58:42.000Z | egov/egov-wtms/src/main/resources/db/migration/main/V20170605160758__wcms_closeconnection_workflow_nextstate_update.sql | getwasim/egov-smartcity-suites-test | 361238c743d046080d66b7fcbe44673a8a784be2 | [
"MIT"
] | 1 | 2021-02-22T21:09:08.000Z | 2021-02-22T21:09:08.000Z | update eg_wf_matrix set nextstate='Close forwared By Approver' where objecttype ='WaterConnectionDetails' and additionalrule ='CLOSECONNECTION' and currentState = 'Close Connection By AE'; | 189 | 189 | 0.825397 |
1a37d58cb3616c12af7be7bb20f6cbdc5ad41526 | 210 | sql | SQL | VsixMvcAppResult/VsixMvcAppResult.Database.Membership/Security/aspnet_Roles_BasicAccess.sql | jordivila/Net_MVC_NLayer_Result | d20040ecdcc7cb8bdf64c9cf980c0af34654e027 | [
"MIT"
] | null | null | null | VsixMvcAppResult/VsixMvcAppResult.Database.Membership/Security/aspnet_Roles_BasicAccess.sql | jordivila/Net_MVC_NLayer_Result | d20040ecdcc7cb8bdf64c9cf980c0af34654e027 | [
"MIT"
] | null | null | null | VsixMvcAppResult/VsixMvcAppResult.Database.Membership/Security/aspnet_Roles_BasicAccess.sql | jordivila/Net_MVC_NLayer_Result | d20040ecdcc7cb8bdf64c9cf980c0af34654e027 | [
"MIT"
] | null | null | null | CREATE ROLE aspnet_Roles_BasicAccess
GO
--ALTER ROLE [aspnet_Roles_BasicAccess] ADD MEMBER [aspnet_Roles_FullAccess];
GO
EXEC sp_addrolemember N'aspnet_Roles_BasicAccess', N'aspnet_Roles_FullAccess' | 23.333333 | 78 | 0.819048 |
0ef345883507dc5d0e46b51d815417031b8b0ad7 | 777 | tsx | TypeScript | examples/a.tsx | MisterLuffy/ts-document | c7a8b7c206f79297045a7b58125c193a3bbda646 | [
"MIT"
] | null | null | null | examples/a.tsx | MisterLuffy/ts-document | c7a8b7c206f79297045a7b58125c193a3bbda646 | [
"MIT"
] | null | null | null | examples/a.tsx | MisterLuffy/ts-document | c7a8b7c206f79297045a7b58125c193a3bbda646 | [
"MIT"
] | null | null | null | /**
* @title Plus
* @zh 两数相乘
* @en Multiply two numbers
* @returns Product of two numbers
*/
type Plus = (
/**
* @en First number
* @zh 被乘数
*/
a: number,
/**
* @en Second number
* @zh 乘数
* @defaultValue 1
*/
b: number
) => number;
/**
* @title Add
* @en Add two numbers
* @zh 两数相加
* @returns Sum of two numbers
* @version 1.0.0
*/
function Add(
/**
* @zh 被加数
* @en First number
*/
a: number,
/**
* @zh 加数
* @en Second number
*/
b = 5
) {
return a + b;
}
/**
* @title Button
* @zh 按钮
* @en Button
*/
type ButtonType = {
/**
* @zh 尺寸
* @en Size
* @defaultValue default
*/
size?: 'mini' | 'large' | 'default';
/**
* @zh 颜色
* @en Color
* @version 1.2.0
*/
color?: string;
};
| 12.532258 | 38 | 0.490347 |
4a3fd5e50f255bc887662f3adb7aaae1f1098082 | 16,394 | js | JavaScript | dist/11.chunk.js | YolkPie/yolkworks-preview | 667fb6c01bd11bb5920354fa67fb44997656feb3 | [
"MIT"
] | null | null | null | dist/11.chunk.js | YolkPie/yolkworks-preview | 667fb6c01bd11bb5920354fa67fb44997656feb3 | [
"MIT"
] | 6 | 2020-06-07T22:20:08.000Z | 2022-02-13T07:10:56.000Z | dist/11.chunk.js | YolkPie/yolkworks-preview | 667fb6c01bd11bb5920354fa67fb44997656feb3 | [
"MIT"
] | null | null | null | webpackJsonp([11],{106:/*!*************************************************!*\
!*** ./node_modules/marked3/dist/marked3.es.js ***!
\*************************************************//*! exports provided: default *//*! all exports used */function(a,b,c){"use strict";function d(a){for(var b,c,d=arguments,e=1;e<arguments.length;e++)for(c in b=d[e],b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c]);return a}function e(){}function f(a,b){return a.replace(b?/&/g:/&(?!#?\w+;)/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function g(a){return a.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/g,function(a,b){var c=String.fromCharCode;return b=b.toLowerCase(),"colon"===b?":":"#"===b.charAt(0)?"x"===b.charAt(1)?c(parseInt(b.substring(2),16)):c(+b.substring(1)):""})}function h(a,b){return a=a.source,b=b||"",function c(d,e){return d?(e=e.source||e,e=e.replace(/(^|[^\[])\^/g,"$1"),a=a.replace(d,e),c):new RegExp(a,b)}}function i(a,b){try{return b&&(b=d({},m,b)),p.parse(r.lex(a,b),b)}catch(a){if(a.message+="\nPlease report this to https://github.com/egoist/marked3.",(b||m).silent)return"<p>An error occurred:</p><pre>"+escape(a.message+"",!0)+"</pre>";throw a}}Object.defineProperty(b,"__esModule",{value:!0});var j=c(/*! slugo */270),k=c.n(j);e.exec=e;var l=function(a){this.options=a||{},this._headings=[]};l.prototype.code=function(a,b,c){if(this.options.highlight){var d=this.options.highlight(a,b);null!==d&&d!==a&&(c=!0,a=d)}return b?"<pre><code class=\""+this.options.langPrefix+f(b,!0)+"\">"+(c?a:f(a,!0))+"\n</code></pre>\n":"<pre><code>"+(c?a:f(a,!0))+"\n</code></pre>"},l.prototype.blockquote=function(a){return"<blockquote>\n"+a+"</blockquote>\n"},l.prototype.html=function(a){return a},l.prototype.heading=function(a,b,c){var d=k()(c),e=this._headings.filter(function(a){return a===c}).length;return 0<e&&(d+="-"+e),this._headings.push(c),"<h"+b+" id=\""+this.options.headerPrefix+d+"\">"+a+"</h"+b+">\n"},l.prototype.hr=function(){return this.options.xhtml?"<hr/>\n":"<hr>\n"},l.prototype.list=function(a,b,c){var d=b?"ol":"ul",e=c?" class=\"task-list\"":"";return"<"+d+e+">\n"+a+"</"+d+">\n"},l.prototype.listitem=function(a,b){return void 0===b?"<li>"+a+"</li>\n":"<li class=\"task-list-item\"><input type=\"checkbox\" class=\"task-list-item-checkbox\""+(b?" checked":"")+"> "+a+"</li>\n"},l.prototype.paragraph=function(a){return"<p>"+a+"</p>\n"},l.prototype.table=function(a,b){return"<table>\n<thead>\n"+a+"</thead>\n<tbody>\n"+b+"</tbody>\n</table>\n"},l.prototype.tablerow=function(a){return"<tr>\n"+a+"</tr>\n"},l.prototype.tablecell=function(a,b){var c=b.header?"th":"td",d=b.align?"<"+c+" style=\"text-align:"+b.align+"\">":"<"+c+">";return d+a+"</"+c+">\n"},l.prototype.strong=function(a){return"<strong>"+a+"</strong>"},l.prototype.em=function(a){return"<em>"+a+"</em>"},l.prototype.codespan=function(a){return"<code>"+a+"</code>"},l.prototype.br=function(){return this.options.xhtml?"<br/>":"<br>"},l.prototype.del=function(a){return"<del>"+a+"</del>"},l.prototype.link=function(a,b,c){if(this.options.sanitize){var d;try{d=decodeURIComponent(g(a)).replace(/[^\w:]/g,"").toLowerCase()}catch(a){return""}if(0===d.indexOf("javascript:")||0===d.indexOf("vbscript:")||0===d.indexOf("data:"))return""}var e="<a href=\""+a+"\"";return b&&(e+=" title=\""+b+"\""),this.options.linksInNewTab&&(e+=" target=\"_blank\""),e+=">"+c+"</a>",e},l.prototype.image=function(a,b,c){var d="<img src=\""+a+"\" alt=\""+c+"\"";return b&&(d+=" title=\""+b+"\""),d+=this.options.xhtml?"/>":">",d},l.prototype.text=function(a){return a};var m={gfm:!0,tables:!0,taskLists:!0,breaks:!1,pedantic:!1,sanitize:!1,sanitizer:null,mangle:!0,smartLists:!1,silent:!1,highlight:null,langPrefix:"lang-",smartypants:!1,headerPrefix:"",renderer:new l,xhtml:!1},n={escape:/^\\([\\`*{}[\]()#+\-.!_>])/,autolink:/^<([^ >]+(@|:\/)[^ >]+)>/,url:e,tag:/^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,link:/^!?\[(inside)\]\(href\)/,reflink:/^!?\[(inside)\]\s*\[([^\]]*)\]/,nolink:/^!?\[((?:\[[^\]]*\]|[^[\]])*)\]/,strong:/^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,em:/^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,code:/^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,br:/^ {2,}\n(?!\s*$)/,del:e,text:/^[\s\S]+?(?=[\\<![_*`]| {2,}\n|$)/};n._inside=/(?:\[[^\]]*\]|[^[\]]|\](?=[^[]*\]))*/,n._href=/\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/,n.link=h(n.link)("inside",n._inside)("href",n._href)(),n.reflink=h(n.reflink)("inside",n._inside)(),n.normal=d({},n),n.pedantic=d({},n.normal,{strong:/^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,em:/^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/}),n.gfm=d({},n.normal,{escape:h(n.escape)("])","~|])")(),url:/^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,del:/^~~(?=\S)([\s\S]*?\S)~~/,text:h(n.text)("]|","~]|")("|","|https?://|")()}),n.breaks=d({},n.gfm,{br:h(n.br)("{2,}","*")(),text:h(n.gfm.text)("{2,}","*")()});var o=function(a,b){if(void 0===b&&(b=m),this.options=b,this.links=a,this.renderer=this.options.renderer||new l,this.renderer.options=this.options,!this.links)throw new Error("Tokens array requires a `links` property.");this.rules=this.options.gfm?this.options.breaks?n.breaks:n.gfm:this.options.pedantic?n.pedantic:n.normal};o.output=function(a,b,c){return new o(b,c).output(a)},o.prototype.output=function(a){for(var b,c,d,e,g=this,h="";a;){if(e=g.rules.escape.exec(a)){a=a.substring(e[0].length),h+=e[1];continue}if(e=g.rules.autolink.exec(a)){a=a.substring(e[0].length),"@"===e[2]?(c=":"===e[1].charAt(6)?g.mangle(e[1].substring(7)):g.mangle(e[1]),d=g.mangle("mailto:")+c):(c=f(e[1]),d=c),h+=g.renderer.link(d,null,c);continue}if(!g.inLink&&(e=g.rules.url.exec(a))){a=a.substring(e[0].length),c=f(e[1]),d=c,h+=g.renderer.link(d,null,c);continue}if(e=g.rules.tag.exec(a)){!g.inLink&&/^<a /i.test(e[0])?g.inLink=!0:g.inLink&&/^<\/a>/i.test(e[0])&&(g.inLink=!1),a=a.substring(e[0].length),h+=g.options.sanitize?g.options.sanitizer?g.options.sanitizer(e[0]):f(e[0]):e[0];continue}if(e=g.rules.link.exec(a)){a=a.substring(e[0].length),g.inLink=!0,h+=g.outputLink(e,{href:e[2],title:e[3]}),g.inLink=!1;continue}if((e=g.rules.reflink.exec(a))||(e=g.rules.nolink.exec(a))){if(a=a.substring(e[0].length),b=(e[2]||e[1]).replace(/\s+/g," "),b=g.links[b.toLowerCase()],!b||!b.href){h+=e[0].charAt(0),a=e[0].substring(1)+a;continue}g.inLink=!0,h+=g.outputLink(e,b),g.inLink=!1;continue}if(e=g.rules.strong.exec(a)){a=a.substring(e[0].length),h+=g.renderer.strong(g.output(e[2]||e[1]));continue}if(e=g.rules.em.exec(a)){a=a.substring(e[0].length),h+=g.renderer.em(g.output(e[2]||e[1]));continue}if(e=g.rules.code.exec(a)){a=a.substring(e[0].length),h+=g.renderer.codespan(f(e[2],!0));continue}if(e=g.rules.br.exec(a)){a=a.substring(e[0].length),h+=g.renderer.br();continue}if(e=g.rules.del.exec(a)){a=a.substring(e[0].length),h+=g.renderer.del(g.output(e[1]));continue}if(e=g.rules.text.exec(a)){a=a.substring(e[0].length),h+=g.renderer.text(f(g.smartypants(e[0])));continue}if(a)throw new Error("Infinite loop on byte: "+a.charCodeAt(0))}return h},o.prototype.outputLink=function(a,b){var c=f(b.href),d=b.title?f(b.title):null;return"!"===a[0].charAt(0)?this.renderer.image(c,d,f(a[1])):this.renderer.link(c,d,this.output(a[1]))},o.prototype.smartypants=function(a){return this.options.smartypants?a.replace(/---/g,"\u2014").replace(/--/g,"\u2013").replace(/(^|[-\u2014/(\[{"\s])'/g,"$1\u2018").replace(/'/g,"\u2019").replace(/(^|[-\u2014/(\[{\u2018\s])"/g,"$1\u201C").replace(/"/g,"\u201D").replace(/\.{3}/g,"\u2026"):a},o.prototype.mangle=function(a){if(!this.options.mangle)return a;for(var b,c="",d=0;d<a.length;d++)b=a.charCodeAt(d),0.5<Math.random()&&(b="x"+b.toString(16)),c+="&#"+b+";";return c},o.rules=n;var p=function(a){void 0===a&&(a=m),this.tokens=[],this.token=null,this.options=a,this.options.renderer=this.options.renderer||new l,this.renderer=this.options.renderer,this.renderer.options=this.options};p.parse=function(a,b,c){return new p(b,c).parse(a)},p.prototype.parse=function(a){var b=this;this.inline=new o(a.links,this.options,this.renderer),this.tokens=a.reverse();for(var c="";this.next();)c+=b.tok();return this.renderer._headings=[],c},p.prototype.next=function(){return this.token=this.tokens.pop(),this.token},p.prototype.peek=function(){return this.tokens[this.tokens.length-1]||0},p.prototype.parseText=function(){for(var a=this,b=this.token.text;"text"===this.peek().type;)b+="\n"+a.next().text;return this.inline.output(b)},p.prototype.tok=function(){var a=this;switch(this.token.type){case"space":return"";case"hr":return this.renderer.hr();case"heading":return this.renderer.heading(this.inline.output(this.token.text),this.token.depth,this.token.text);case"code":return this.renderer.code(this.token.text,this.token.lang,this.token.escaped);case"table":{var b,c,d,e,f="",g="";for(d="",b=0;b<this.token.header.length;b++)d+=a.renderer.tablecell(a.inline.output(a.token.header[b]),{header:!0,align:a.token.align[b]});for(f+=this.renderer.tablerow(d),b=0;b<this.token.cells.length;b++){for(c=a.token.cells[b],d="",e=0;e<c.length;e++)d+=a.renderer.tablecell(a.inline.output(c[e]),{header:!1,align:a.token.align[e]});g+=a.renderer.tablerow(d)}return this.renderer.table(f,g)}case"blockquote_start":{for(var h="";"blockquote_end"!==this.next().type;)h+=a.tok();return this.renderer.blockquote(h)}case"list_start":{for(var i="",j=!1,k=this.token.ordered;"list_end"!==this.next().type;)void 0!==a.token.checked&&(j=!0),i+=a.tok();return this.renderer.list(i,k,j)}case"list_item_start":{for(var l="",m=this.token.checked;"list_item_end"!==this.next().type;)l+="text"===a.token.type?a.parseText():a.tok();return this.renderer.listitem(l,m)}case"loose_item_start":{for(var n="",o=this.token.checked;"list_item_end"!==this.next().type;)n+=a.tok();return this.renderer.listitem(n,o)}case"html":{var p=this.token.pre||this.options.pedantic?this.token.text:this.inline.output(this.token.text);return this.renderer.html(p)}case"paragraph":return this.renderer.paragraph(this.inline.output(this.token.text));case"text":return this.renderer.paragraph(this.parseText());default:throw new Error("Unknow type");}};var q={newline:/^\n+/,code:/^( {4}[^\n]+\n*)+/,fences:e,hr:/^( *[-*_]){3,} *(?:\n+|$)/,heading:/^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,nptable:e,lheading:/^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,blockquote:/^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,list:/^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,html:/^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,table:e,paragraph:/^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,text:/^[^\n]+/};q.bullet=/(?:[*+-]|\d+\.)/,q.item=/^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/,q.item=h(q.item,"gm")(/bull/g,q.bullet)(),q.list=h(q.list)(/bull/g,q.bullet)("hr","\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))")("def","\\n+(?="+q.def.source+")")(),q.blockquote=h(q.blockquote)("def",q.def)(),q._tag="(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b",q.html=h(q.html)("comment",/<!--[\s\S]*?-->/)("closed",/<(tag)[\s\S]+?<\/\1>/)("closing",/<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)(/tag/g,q._tag)(),q.paragraph=h(q.paragraph)("hr",q.hr)("heading",q.heading)("lheading",q.lheading)("blockquote",q.blockquote)("tag","<"+q._tag)("def",q.def)(),q.normal=d({},q),q.gfm=d({},q.normal,{fences:/^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/,paragraph:/^/,heading:/^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/,checkbox:/^\[([ x])\] +/}),q.gfm.paragraph=h(q.paragraph)("(?!","(?!"+q.gfm.fences.source.replace("\\1","\\2")+"|"+q.list.source.replace("\\1","\\3")+"|")(),q.tables=d({},q.gfm,{nptable:/^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,table:/^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/});var r=function(a){void 0===a&&(a=m),this.tokens=[],this.tokens.links={},this.options=a,this.rules=this.options.gfm?this.options.tables?q.tables:q.gfm:q.normal};r.lex=function(a,b){return new r(b).lex(a)},r.prototype.lex=function(a){return a=a.replace(/\r\n|\r/g,"\n").replace(/\t/g," ").replace(/\u00a0/g," ").replace(/\u2424/g,"\n"),this.token(a,!0)},r.prototype.token=function(a,c,d){var e=this;a=a.replace(/^ +$/gm,"");for(var f,g,h,j,k,b,m,n,i,l;a;){if((h=e.rules.newline.exec(a))&&(a=a.substring(h[0].length),1<h[0].length&&e.tokens.push({type:"space"})),h=e.rules.code.exec(a)){a=a.substring(h[0].length),h=h[0].replace(/^ {4}/gm,""),e.tokens.push({type:"code",text:e.options.pedantic?h:h.replace(/\n+$/,"")});continue}if(h=e.rules.fences.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"code",lang:h[2],text:h[3]||""});continue}if(h=e.rules.heading.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"heading",depth:h[1].length,text:h[2]});continue}if(c&&(h=e.rules.nptable.exec(a))){for(a=a.substring(h[0].length),b={type:"table",header:h[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:h[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:h[3].replace(/\n$/,"").split("\n")},n=0;n<b.align.length;n++)b.align[n]=/^ *-+: *$/.test(b.align[n])?"right":/^ *:-+: *$/.test(b.align[n])?"center":/^ *:-+ *$/.test(b.align[n])?"left":null;for(n=0;n<b.cells.length;n++)b.cells[n]=b.cells[n].split(/ *\| */);e.tokens.push(b);continue}if(h=e.rules.lheading.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"heading",depth:"="===h[2]?1:2,text:h[1]});continue}if(h=e.rules.hr.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"hr"});continue}if(h=e.rules.blockquote.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"blockquote_start"}),h=h[0].replace(/^ *> ?/gm,""),e.token(h,c,!0),e.tokens.push({type:"blockquote_end"});continue}if(h=e.rules.list.exec(a)){for(a=a.substring(h[0].length),j=h[2],e.tokens.push({type:"list_start",ordered:1<j.length}),h=h[0].match(e.rules.item),f=!1,i=h.length,n=0;n<i;n++)b=h[n],m=b.length,b=b.replace(/^ *([*+-]|\d+\.) +/,""),e.options.gfm&&e.options.taskLists&&(l=e.rules.checkbox.exec(b),l?(l="x"===l[1],b=b.replace(e.rules.checkbox,"")):l=void 0),-1!==b.indexOf("\n ")&&(m-=b.length,b=e.options.pedantic?b.replace(/^ {1,4}/gm,""):b.replace(new RegExp("^ {1,"+m+"}","gm"),"")),e.options.smartLists&&n!==i-1&&(k=e.rules.bullet.exec(h[n+1])[0],j!==k&&!(1<j.length&&1<k.length)&&(a=h.slice(n+1).join("\n")+a,n=i-1)),g=f||/\n\n(?!\s*$)/.test(b),n!==i-1&&(f="\n"===b.charAt(b.length-1),!g&&(g=f)),e.tokens.push({checked:l,type:g?"loose_item_start":"list_item_start"}),e.token(b,!1,d),e.tokens.push({type:"list_item_end"});e.tokens.push({type:"list_end"});continue}if(h=e.rules.html.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:e.options.sanitize?"paragraph":"html",pre:!e.options.sanitizer&&("pre"===h[1]||"script"===h[1]||"style"===h[1]),text:h[0]});continue}if(!d&&c&&(h=e.rules.def.exec(a))){a=a.substring(h[0].length),e.tokens.links[h[1].toLowerCase()]={href:h[2],title:h[3]};continue}if(c&&(h=e.rules.table.exec(a))){for(a=a.substring(h[0].length),b={type:"table",header:h[1].replace(/^ *| *\| *$/g,"").split(/ *\| */),align:h[2].replace(/^ *|\| *$/g,"").split(/ *\| */),cells:h[3].replace(/(?: *\| *)?\n$/,"").split("\n")},n=0;n<b.align.length;n++)b.align[n]=/^ *-+: *$/.test(b.align[n])?"right":/^ *:-+: *$/.test(b.align[n])?"center":/^ *:-+ *$/.test(b.align[n])?"left":null;for(n=0;n<b.cells.length;n++)b.cells[n]=b.cells[n].replace(/^ *\| *| *\| *$/g,"").split(/ *\| */);e.tokens.push(b);continue}if(c&&(h=e.rules.paragraph.exec(a))){a=a.substring(h[0].length),e.tokens.push({type:"paragraph",text:"\n"===h[1].charAt(h[1].length-1)?h[1].slice(0,-1):h[1]});continue}if(h=e.rules.text.exec(a)){a=a.substring(h[0].length),e.tokens.push({type:"text",text:h[0]});continue}if(a)throw new Error("Infinite loop on byte: "+a.charCodeAt(0))}return this.tokens},r.rules=q,i.Renderer=l,i.Parser=p,i.Lexer=r,i.InlineLexer=o,b["default"]=i},270:/*!******************************************!*\
!*** ./node_modules/slugo/dist/slugo.js ***!
\******************************************//*! dynamic exports provided *//*! exports used: default */function(a){(function(b,c){a.exports=c()})(this,function(){"use strict";return function(a){return a.replace(/<(?:.|\n)*?>/gm,"").replace(/[!\"#$%&'\(\)\*\+,\/:;<=>\?\@\[\\\]\^`\{\|\}~]/g,"").replace(/(\s|\.)/g,"-").toLowerCase()}})}}); | 3,278.8 | 15,873 | 0.590155 |
2656b675fad277c6acef939b98e21c6f16ab24cc | 2,373 | java | Java | src/main/java/lk/chathurabuddi/file/type/jrxml/JrxmlFileTypeFactory.java | slestak/intellij-jasper-report-support | e9753916d0a57eeb35331338173e86ff1cda15bc | [
"MIT"
] | 11 | 2019-06-21T17:33:20.000Z | 2021-08-06T17:53:51.000Z | src/main/java/lk/chathurabuddi/file/type/jrxml/JrxmlFileTypeFactory.java | slestak/intellij-jasper-report-support | e9753916d0a57eeb35331338173e86ff1cda15bc | [
"MIT"
] | 15 | 2019-10-04T01:02:13.000Z | 2022-01-06T17:22:45.000Z | src/main/java/lk/chathurabuddi/file/type/jrxml/JrxmlFileTypeFactory.java | slestak/intellij-jasper-report-support | e9753916d0a57eeb35331338173e86ff1cda15bc | [
"MIT"
] | 17 | 2019-09-25T17:21:52.000Z | 2022-03-22T03:22:14.000Z | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Chathura Buddhika
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package lk.chathurabuddi.file.type.jrxml;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.FileTypeManager;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiFile;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public class JrxmlFileTypeFactory {
@NonNls public static final String JRXML_EXTENSION = "jrxml";
@NonNls static final String DOT_JRXML_EXTENSION = "." + JRXML_EXTENSION;
public static boolean isJrxml(@NotNull PsiFile file) {
final VirtualFile virtualFile = file.getViewProvider().getVirtualFile();
return isJrxml(virtualFile);
}
public static boolean isJrxml(@NotNull VirtualFile virtualFile) {
if (JRXML_EXTENSION.equals(virtualFile.getExtension())) {
final FileType fileType = virtualFile.getFileType();
if (fileType == getFileType() && !fileType.isBinary()) {
return virtualFile.getName().endsWith(DOT_JRXML_EXTENSION);
}
}
return false;
}
@NotNull
public static FileType getFileType() {
return FileTypeManager.getInstance().getFileTypeByExtension(JRXML_EXTENSION);
}
}
| 40.913793 | 85 | 0.736199 |
d7b33c9bcedc14cbcac68e9880c4a5585e01159d | 27,692 | lua | Lua | Toribio/deviceloaders/dynamixel/motor.lua | Yatay/1.0 | a553fbb0fd148b613e2bb6b2397c6f5a550236db | [
"MIT"
] | null | null | null | Toribio/deviceloaders/dynamixel/motor.lua | Yatay/1.0 | a553fbb0fd148b613e2bb6b2397c6f5a550236db | [
"MIT"
] | null | null | null | Toribio/deviceloaders/dynamixel/motor.lua | Yatay/1.0 | a553fbb0fd148b613e2bb6b2397c6f5a550236db | [
"MIT"
] | null | null | null | --- Library for Dynamixel motors.
-- This library allows to manipulate devices that use Dynamixel
-- protocol, such as AX-12 robotic servo motors.
-- For basic manipulation, it is enough to use the @{rotate_to_angle} and @{spin} functions,
-- and perhaps set the @{set.torque_enable}. For more sophisticated tasks, the full
-- Dynamixel functionality is available trough getter and setter functions.
-- When available, each connected motor will be published
-- as a device in torobio.devices table, named
-- (for example) 'ax12:1', labeled as module 'ax'. Aditionally, an 'ax:all'
-- device will represent the broadcast wide motor. Also, 'ax:sync' motors can be used to
-- control several motors at the same time. Notice you can not read from broadcast nor sync
-- motors, only send commands to them.
-- Some of the setable parameters set are located on the motors EEPROM (marked "persist"),
-- and others are on RAM (marked "volatile"). The attributes stored in RAM are reset when the
-- motor is powered down.
-- For defaut values, check the Dynamixel documentation.
-- @module dynamixel-motor
-- @usage local toribio = require 'toribio'
--local motor = toribio.wait_for_device('ax12:1')
--motor.set.led(true)
-- @alias Motor
--local my_path = debug.getinfo(1, "S").source:match[[^@?(.*[\/])[^\/]-$]]
local log = require 'log'
local M = {}
local function getunsigned_2bytes(s)
return s:byte(1) + 256*s:byte(2)
end
local function get2bytes_unsigned(n)
if n<0 then n=0
elseif n>1023 then n=1023 end
local lowb, highb = n%256, math.floor(n/256)
return lowb, highb
end
local function get2bytes_signed(n)
if n<-1023 then n=-1023
elseif n>1023 then n=1023 end
if n < 0 then n = 1024 - n end
local lowb, highb = n%256, math.floor(n/256)
return lowb, highb
end
local function log2( x )
return math.log( x ) / math.log( 2 )
end
M.get_motor= function (busdevice, motor_id)
local read_data = busdevice.read_data
local write_method
local idb
local motor_mode -- 'joint' or 'wheel'
local motor_type -- 'single', 'sync' or 'broadcast'
local status_return_level
if type(motor_id) == 'table' then
motor_type = 'sync'
elseif motor_id == 0xFE then
motor_type = 'broadcast'
else
motor_type = 'single'
end
if motor_type~='sync' then
idb = string.char(motor_id)
write_method='write_data'
else
idb = {}
for i, anid in ipairs(motor_id) do
idb[i] = string.char(anid)
end
write_method='sync_write'
end
--Check wether the motor with id actually exists. If not, return nil.
if motor_type == 'single' then
if not busdevice.ping(idb) then
return nil
end
end
-- It exists, let's start building the object.
local Motor = {
--- Device file of the bus.
-- Filename of the bus to which the motor is connected.
-- For example, _'/dev/ttyUSB0'_
filename = busdevice.filename,
--- Bus device.
-- The dynamixel bus Device to which the motor is connected
busdevice = busdevice,
--- Dynamixel ID number.
motor_id = motor_id,
}
if motor_type == 'single' then
--- Ping the motor.
-- Only available for single motors, not sync nor broadcast.
-- @return a dynamixel error code
Motor.ping = function()
return busdevice.ping(idb)
end
end
-- calls that are only avalable on proper motors (not 'syncs motors')
if motor_type ~= 'sync' then
--- Reset configuration to factory default.
-- Use with care, as it also resets the ID number and baud rate.
-- For factory defaults, check Dynamixal documentation.
-- This command only works for single motors (not sync nor broadcast).
-- For defaut values, check the Dynamixel documentation.
-- @return a dynamixel error code
Motor.reset_factory_default = function()
return busdevice.reset(idb, status_return_level)
end
--- Starts a register write mode.
-- In reg_write mode changes in configuration to devices
-- are not applied until a @{reg_write_action} call.
-- This command only works for single motors (not sync nor broadcast).
Motor.reg_write_start = function()
write_method='reg_write_data'
end
--- Finishes a register write mode.
-- All changes in configuration applied after a previous
-- @{reg_write_start} are commited.
-- This command only works for single motors (not sync nor broadcast).
Motor.reg_write_action = function()
busdevice.action(idb,status_return_level)
write_method='write_data'
end
end -- /calls that are only avalable on proper motors (not 'syncs motors')
local control_getters = {
rotation_mode = function()
local ret, err = read_data(idb,0x06,4,status_return_level)
if ret==string.char(0x00,0x00,0x00,0x00) then
motor_mode = 'wheel'
else
motor_mode = 'joint'
end
return motor_mode, err
end,
model_number = function()
local ret, err = read_data(idb,0x00,2, status_return_level)
if ret then return getunsigned_2bytes(ret), err end
end,
firmware_version = function()
return read_data(idb,0x02,1, status_return_level)
end,
id = function()
return read_data(idb,0x03,1, status_return_level)
end,
baud_rate = function()
local ret, err = read_data(idb,0x04,1, status_return_level)
if ret then return math.floor(2000000/(ret+1)), err end --baud
end,
return_delay_time = function()
local ret, err = read_data(idb,0x05,1, status_return_level)
if ret then return (ret*2)/1000000, err end --sec
end,
angle_limit = function()
local ret, err = read_data(idb,0x06,4, status_return_level)
if ret then
local cw = 0.29*(ret:byte(1) + 256*ret:byte(2))
local ccw = 0.29*(ret:byte(3) + 256*ret:byte(4))
return cw, ccw, err
end -- deg
end,
limit_temperature = function()
return read_data(idb,0x0B,1, status_return_level)
end,
limit_voltage = function()
local ret, err = read_data(idb,0x0C,2, status_return_level)
if ret then return ret:byte(1)/10, ret:byte(2)/10, err end
end,
max_torque = function()
local ret, err = read_data(idb,0x0E,2, status_return_level)
if ret then return getunsigned_2bytes(ret) / 10.23, err end--% of max torque
end,
status_return_level = function()
local ret, err = read_data(idb,0x10,1, status_return_level or 2)
local return_levels = {
[0] = 'ONLY_PING',
[1] = 'ONLY_READ',
[2]= 'ALL'
}
if ret then
local code = ret:byte()
status_return_level = code
return return_levels[code], err
end
end,
alarm_led = function()
local ret, err = read_data(idb,0x11,1, status_return_level)
if ret then
return busdevice.has_errors(ret), err
end
end,
alarm_shutdown = function()
local ret, err = read_data(idb,0x12,1, status_return_level)
if ret then
local _, errorset = busdevice.has_errors(ret)
return errorset, err
end
end,
torque_enable = function()
local ret, err = read_data(idb,0x18,1, status_return_level)
if ret then return ret:byte()==0x01, err end
end,
led = function()
local ret, err = read_data(idb,0x19,1, status_return_level)
if ret then return ret:byte()==0x01, err end
end,
compliance_margin = function()
local ret, err = read_data(idb,0x1A,2, status_return_level)
if ret then return 0.29*ret:byte(1), 0.29*ret:byte(2), err end --deg
end,
compliance_slope = function()
local ret, err = read_data(idb,0x1C,2, status_return_level)
if ret then
return log2(ret:byte(1)), log2(ret:byte(2)), err
end
end,
goal_position = function()
local ret, err = read_data(idb,0x1E,2, status_return_level)
if ret then
local ang=0.29*getunsigned_2bytes(ret)
return ang, err -- deg
end
end,
moving_speed = function()
local ret, err = read_data(idb,0x20,2, status_return_level)
if ret then
local vel = getunsigned_2bytes(ret)
if motor_mode=='joint' then
return vel / 1.496, err --deg/sec
elseif motor_mode=='wheel' then
return vel / 10.23, err --% of max torque
end
end
end,
torque_limit = function()
local ret, err = read_data(idb,0x22,2, status_return_level)
if ret then
local ang=getunsigned_2bytes(ret) / 10.23
return ang, err -- % max torque
end
end,
present_position = function()
local ret, err = read_data(idb,0x24,2, status_return_level)
if ret then
local ang=0.29*getunsigned_2bytes(ret)
return ang, err -- deg
end
end,
present_speed = function()
local ret, err = read_data(idb,0x26,2, status_return_level)
local vel = getunsigned_2bytes(ret)
if vel > 1023 then vel =1024-vel end
if motor_mode=='joint' then
return vel / 1.496, err --deg/sec
elseif motor_mode=='wheel' then
return vel / 10.23, err --% of max torque
end
end,
present_load = function()
local ret, err = read_data(idb,0x28,2, status_return_level)
if ret then
local load = ret:byte(1) + 256*ret:byte(2)
if load > 1023 then load = 1024-load end
return load/10.23, err -- % of torque max
end
end,
present_voltage = function()
local ret, err = read_data(idb,0x2A,1, status_return_level)
if ret then return ret:byte()/10, err end
end,
present_temperature = function()
local ret, err = read_data(idb,0x2B,1, status_return_level)
if ret then return ret:byte(), err end
end,
registered = function()
local ret, err = read_data(idb,0x2C,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
moving = function()
local ret, err = read_data(idb,0x2E,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
lock = function()
local ret, err = read_data(idb,0x2F,1, status_return_level)
if ret then return ret:byte()==1, err end --bool
end,
punch = function()
local ret, err = read_data(idb,0x30,2, status_return_level)
if ret then
local load = ret:byte(1) + 256*ret:byte(2)
return load/10.23, err -- % of torque max
end
end
}
local control_setters = {
rotation_mode = function (mode)
local ret
if mode == 'wheel' then
ret = busdevice[write_method](idb,0x06,string.char(0, 0, 0, 0),status_return_level)
else
local max=1023
local maxlowb, maxhighb = get2bytes_unsigned(max)
ret = busdevice[write_method](idb,0x06,string.char(0, 0, maxlowb, maxhighb),status_return_level)
end
motor_mode = mode
return ret
end,
id = function(newid)
assert(newid>=0 and newid<=0xFD, 'Invalid ID: '.. tostring(newid))
motor_id, idb = newid, string.char(newid)
return busdevice[write_method](idb,0x3,string.char(newid),status_return_level)
end,
baud_rate = function(baud)
local n = math.floor(2000000/baud)-1
assert(n>=1 and n<=207, "Attempt to set serial speed: "..n)
return busdevice[write_method](idb,0x04,n,status_return_level)
end,
return_delay_time = function(sec)
local parameter = math.floor(sec * 1000000 / 2)
return busdevice[write_method](idb,0x05,string.char(parameter),status_return_level)
end,
angle_limit = function(cw, ccw)
if cw then cw=math.floor(cw/0.29)
else cw=0 end
if ccw then ccw=math.floor(ccw/0.29)
else ccw=1023 end
local minlowb, maxhighb = get2bytes_unsigned(cw)
local maxlowb, maxnhighb = get2bytes_unsigned(ccw)
local ret = busdevice[write_method](idb,0x06,string.char(minlowb, maxhighb, maxlowb, maxnhighb),status_return_level)
if cw==0 and ccw==0 then
motor_mode='wheel'
else
motor_mode='joint'
end
return ret
end,
limit_temperature = function(deg)
return busdevice[write_method](idb,0x0B,deg,status_return_level)
end,
limit_voltage = function(min, max)
local min, max = min*10, max*10
if min<=255 and min>0 and max<=255 and max>0 then
return busdevice[write_method](idb,0x0C,string.char(min, max),status_return_level)
end
end,
max_torque = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x0E,string.char(lowb,highb),status_return_level)
end,
status_return_level = function(level)
local level_codes= {
ONLY_PING = 0,
ONLY_READ = 1,
ALL = 2
}
local code = level_codes[level or 'ALL']
status_return_level = code
return busdevice[write_method](idb,0x10,string.char(code),status_return_level or 2)
end,
alarm_led = function(errors)
local code = 0
for _, err in ipairs(errors) do
code = code + (busdevice.ax_errors[err] or 0)
end
return busdevice[write_method](idb,0x11,string.char(code),status_return_level)
end,
alarm_shutdown = function(errors)
local code = 0
for _, err in ipairs(errors) do
code = code + (busdevice.ax_errors[err] or 0)
end
return busdevice[write_method](idb,0x12,string.char(code),status_return_level)
end,
torque_enable = function (value)
--boolean
local parameter
if value then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
return busdevice[write_method](idb,0x18,parameter,status_return_level)
end,
led = function (value)
local parameter
if value then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
assert(status_return_level, debug.traceback())
return busdevice[write_method](idb,0x19,parameter,status_return_level)
end,
compliance_margin = function(angle)
local ang=math.floor(angle/0.29)
local lowb, highb = get2bytes_unsigned(ang)
return busdevice[write_method](idb,0x1A,string.char(lowb,highb),status_return_level)
end,
compliance_slope = function(cw, ccw)
cw, ccw = math.floor(2^cw), math.floor(2^ccw)
return busdevice[write_method](idb,0x1C,string.char(cw,ccw),status_return_level)
end,
goal_position = function(angle)
local ang=math.floor(angle/0.29)
local lowb, highb = get2bytes_unsigned(ang)
return busdevice[write_method](idb,0x1E,string.char(lowb,highb),status_return_level)
end,
moving_speed = function(value)
if motor_mode=='joint' then
-- 0 .. 684 deg/sec
local vel=math.floor(value * 1.496)
local lowb, highb = get2bytes_unsigned(vel)
return busdevice[write_method](idb,0x20,string.char(lowb,highb),status_return_level)
elseif motor_mode=='wheel' then
-- -100% .. +100% max torque
local vel=math.floor(value * 10.23)
local lowb, highb = get2bytes_signed(vel)
return busdevice[write_method](idb,0x20,string.char(lowb,highb),status_return_level)
end
end,
torque_limit = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x22,string.char(lowb,highb),status_return_level)
end,
lock = function(enable)
local parameter
if enable then
parameter=string.char(0x01)
else
parameter=string.char(0x00)
end
return busdevice[write_method](idb,0x2F,parameter,status_return_level)
end,
punch = function(value)
-- 0% .. 100% max torque
local torque=math.floor(value * 10.23)
local lowb, highb = get2bytes_unsigned(torque)
return busdevice[write_method](idb,0x30,string.char(lowb,highb),status_return_level)
end
}
local last_speed
--- Rotate to the indicated angle.
-- @param angle Position in degrees in the 0-300 range.
-- @param speed optional rotational speed, in deg/sec in the 1 .. 684 range.
-- Defaults to max unregulated speed.
Motor.rotate_to_angle = function (angle, speed)
if motor_mode ~= 'joint' then
control_setters.rotation_mode('joint')
end
if speed ~= last_speed then
control_setters.moving_speed(speed or 0)
end
return control_setters.goal_position(angle)
end
--- Spin at the indicated torque.
-- @param power % of max torque, in the -100% .. 100% range.
Motor.spin = function (power)
if motor_mode ~= 'joint' then
control_setters.rotation_mode('wheel')
end
return control_setters.moving_speed(power)
end
Motor.set = control_setters
--- Name of the device.
-- Of the form _'ax12:5'_, _ax:all_ for a broadcast motor, or ax:sync (sync motor set).
--- Module name (_'ax'_, ax-all or _'ax-sync'_ in this case)
-- _'ax'_ is for actuators, _'ax-sync'_ is for sync-motor objects
if motor_type=='sync' then
--initialize local state
status_return_level = 0
Motor.module = 'ax-sync'
Motor.name = 'ax-sync:'..tostring(math.random(2^30))
elseif motor_type=='broadcast' then
--initialize local state
status_return_level = 0
Motor.module = 'ax-all'
Motor.name = 'ax:all'
elseif motor_type=='single' then
Motor.get = control_getters
--initialize local state
_, _ = control_getters.status_return_level()
_, _ = control_getters.rotation_mode()
Motor.module = 'ax'
Motor.name = 'ax'..((control_getters.model_number()) or '??')..':'..motor_id
end
log('AXMOTOR', 'INFO', 'device object created: %s', Motor.name)
--toribio.add_device(busdevice)
return Motor
end
return M
--- Atribute getters.
-- Functions used to get values from the Dynamixel control table. These functions
-- are not available for broadcast nor sync motors.
-- @section getters
--- Get the dynamixel model number.
-- For an AX-12 this will return 12.
-- @function get.model_number
-- @return a model number, followed by a dynamixel error code.
--- Get the version of the actuator's firmware.
-- For an AX-12 this will return 12.
-- @function get.firmware_version
-- @return a version number, followed by a dynamixel error code.
--- Get the ID number of the actuator.
-- @function get.id
-- @return a ID number, followed by a dynamixel error code.
--- Get the baud rate.
-- @function get.baud_rate
-- @return a serial bus speed in bps, followed by a dynamixel error code.
--- Get the response delay.
-- The time in secs an actuator waits before answering a call.
-- @function get.return_delay_time
-- @return the edlay time in secs, followed by a dynamixel error code.
--- Get the rotation mode.
-- Wheel mode is equivalent to having limits cw=0, ccw=0, and mode joint is equivalent to cw=0, ccw=300
-- @function get.rotation_mode
-- @return Either 'wheel' or 'joint', followed by a dynamixel error code.
--- Get the angle limit.
-- The extreme positions possible for the Joint mode.
-- @function get.angle_limit
-- @return the cw limit, then the ccw limit, followed by a dynamixel error code.
--- Get the temperature limit.
-- @function get.limit_temperature
-- @return The maximum allowed temperature in degrees Celsius, followed by a dynamixel error code.
--- Get the voltage limit.
-- @function get.limit_voltage
-- @return The minumum and maximum allowed voltage in Volts, followed by a dynamixel error code.
--- Get the torque limit.
-- This is also the default value for `torque_limit`.
-- @function get.max_torque
-- @return the maximum producible torque, as percentage of maximum possible (in the 0% - 100% range),
-- followed by a dynamixel error code.
--- Get the Return Level.
-- Control what commands must generate a status response
-- from the actuator. Possible values are 'ONLY\_PING', 'ONLY\_READ' and 'ALL' (default)
-- @function get.status_return_level
-- @return the return level, followed by a dynamixel error code.
--- Get the LED alarm setup.
-- A list of error conditions that cause the LED to blink.
-- @function get.alarm_led
-- @return A double indexed set, by entry number and error code, followed by a dynamixel error code. The possible
-- error codes in the list are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- 'ERROR\_RANGE', 'ERROR\_CHECKSUM', 'ERROR\_OVERLOAD' and 'ERROR\_INSTRUCTION'.
--- Get the alarm shutdown setup.
-- A list of error conditions that cause the `torque_limit` attribute to
-- be set to 0, halting the motor.
-- @function get.alarm_shutodown
-- @return A double indexed set, by entry number and error code, followed by a dynamixel error code. The possible
-- error codes in the list are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- 'ERROR\_RANGE', 'ERROR\_CHECKSUM', 'ERROR\_OVERLOAD' and 'ERROR\_INSTRUCTION'.
--- Get the Torque Enable status.
-- Control the power supply to the motor.
-- @function get.torque_enable
-- @return Boolean
--- Get the Compliance Margin.
-- See Dynamiel reference.
-- @function get.compliance_margin
-- @return cw margin, ccw margin (both in degrees), followed by a Dynamiel error code.
--- Get the Compliance Slope.
-- See Dynamiel reference.
-- @function get.compliance_slope
-- @return the step value, followed by a Dynamiel error code.
--- Get the Punch value.
-- See Dynamiel reference.
-- @function get.punch
-- @return punch as % of max torque (in the 0..100 range)
--- Get the goal angle.
-- The target position for the actuator is going to. Only works in joint mode.
-- @function get.goal_position
-- @return the target angle in degrees, followed by a Dynamiel error code.
--- Get rotation speed.
-- @function get.moving_speed
-- @return If motor in joint mode, speed in deg/sec (0 means max unregulated speed), if in wheel
-- mode, as a % of max torque, followed by a Dynamiel error code.
--- Get the torque limit.
-- Controls the 'ERROR\_OVERLOAD' error triggering.
-- @function get.torque_limit
-- @return The torque limit as percentage of maximum possible.
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range)
-- , followed by a Dynamiel error code.
--- Get the axle position.
-- @function get.present_position
-- @return The current position of the motor axle, in degrees (only valid in the
-- 0 .. 300 range), followed by a Dynamiel error code.
--- Get the actual rotation speed.
-- Only valid in the 0..300 deg position.
-- @function get.present_speed
-- @return If motor in joint mode, speed in deg/sec, if in wheel
-- mode, as a % of max torque, followed by a Dynamiel error code.
--- Get the motor load.
-- Only valid in the 0..300 deg position, and aproximate.
-- @function get.present_load
-- @return Percentage of max torque (positive is clockwise, negative is
-- counterclockwise), followed by a Dynamiel error code.
--- Get the supplied voltage.
-- @function get.present_voltage
-- @return The supplied voltage in Volts, followed by a Dynamiel error code.
--- Get the internal temperature.
-- @function get.present_temperature
-- @return The Internal temperature in degrees Celsius, followed by a Dynamiel error code.
--- Get registered commands status.
-- Wether there are registerd commands (see @{reg_write_start} and @{reg_write_action})
-- @function get.registered
-- @return A boolean, followed by a Dynamiel error code.
--- Get the moving status.
-- Wether the motor has reached @{get.goal_position}.
-- @function get.present_temperature
-- @return A boolean, followed by a Dynamiel error code.
--- Get the lock status.
-- Whether the EEPROM (persistent) attributes are blocked for writing.
-- @function get.lock
-- @return boolean, followed by a Dynamiel error code.
--- Atribute setters.
-- Functions used to set values for the Dynamixel control table.
-- Some of the setable parameters set are located on the motors EEPROM (marked "persist"),
-- and others are on RAM (marked "volatile"). The attributes stored in RAM are reset when the
-- motor is powered down.
-- @section setters
--- Set the ID number of the actuator (persist).
--- @function set.id
-- @param ID number, must be in the 0 .. 253 range.
-- @return A dynamixel error code.
--- Set the baud rate (persist).
-- @function set.baud_rate
-- @param bps bus rate in bps, in the 9600 to 1000000 range. Check the Dynamixel docs for supported values.
-- @return A dynamixel error code.
--- Set the response delay (persist).
-- The time in secs an actuator waits before answering a call.
-- @function set.return_delay_time
-- @param sec a time in sec.
-- @return A dynamixel error code.
--- Set the rotation mode (persist).
-- Wheel mode is for continuous rotation, Joint is for servo. Setting this attribute resets the
-- `angle_limit` parameter. Wheel mode is equivalent to having limits cw=0, ccw=0, and mode joint is equivalent to cw=0, ccw=300
-- @function set.rotation_mode
-- @param mode Either 'wheel' or 'joint'.
-- @return A dynamixel error code.
--- Set the angle limit (persist).
-- The extreme positions possible for the Joint mode. The angles are given in degrees, and must be in the 0<=cw<=ccw<=300 range.
-- @function set.angle_limit
-- @param cw the clockwise limit.
-- @param ccw the clockwise limit.
-- @return A dynamixel error code.
--- Set the temperature limit (persist).
-- @function set.limit_temperature
-- @param deg the temperature in degrees Celsius.
-- @return A dynamixel error code.
--- Set the voltage limit (persist).
-- @function set.limit_voltage
-- @param min the minimum allowed voltage in Volts.
-- @param max the maximum allowed voltage in Volts.
-- @return A dynamixel error code.
--- Set the torque limit (persist).
-- This is also the default value for `torque_limit`.
-- @function set.max_torque
-- @param torque the maximum producible torque, as percentage of maximum possible (in the 0% - 100% range)
-- @return A dynamixel error code.
--- Set the Return Level (persist).
-- Control what commands must generate a status response
-- from the actuator.
-- @function set.status_return_level
-- @param return_level Possible values are 'ONLY\_PING', 'ONLY\_READ' and 'ALL' (default)
-- @return A dynamixel error code.
--- Set LED alarm (persist).
-- A list of error conditions that cause the LED to blink.
-- @function set.alarm_led
-- @param errors A list of error codes. The possible
-- error codes are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- @return A dynamixel error code.
--- Set alarm shutdown (persist).
-- A list of error conditions that cause the `torque_limit` attribute to
-- be set to 0, halting the motor.
-- @function set.alarm_shutodown
-- @param errors A list of error codes. The possible
-- error codes are 'ERROR\_INPUT\_VOLTAGE', 'ERROR\_ANGLE\_LIMIT', 'ERROR\_OVERHEATING',
-- @return A dynamixel error code.
--- Set the Torque Enable status (volatile).
-- Control the power supply to the motor.
-- @function set.torque_enable
-- @param status Boolean
-- @return A dynamixel error code.
--- Set the Compliance Margin (volatile).
-- See Dynamiel reference.
-- @function set.compliance_margin
-- @param cw clockwise margin, in deg.
-- @param ccw counterclockwise margin, in deg.
-- @return A dynamixel error code.
--- Set the Compliance Slope (volatile).
-- See Dynamiel reference.
-- @function set.compliance_slope
-- @param step the step value.
-- @return A dynamixel error code.
--- Set the Punch value (volatile).
-- See Dynamiel reference.
-- @function set.punch
-- @param punch as % of max torque (in the 0..100 range)
-- @return A dynamixel error code.
--- Set the goal angle (volatile).
-- The target position for the actuator to go, in degrees. Only works in joint mode.
-- @function set.goal_position
-- @param angle the target angle in degrees
-- @return A dynamixel error code.
--- Set the rotation speed (volatile).
-- @function set.moving_speed
-- @param speed If motor in joint mode, speed in deg/sec in the 0 .. 684 range
-- (0 means max unregulated speed).
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range).
-- @return A dynamixel error code.
--- Set the torque limit (volatile).
-- Controls the 'ERROR\_OVERLOAD' error triggering.
-- @function set.torque_limit
-- @param torque The torque limit as percentage of maximum possible.
-- If in wheel mode, as a % of max torque (in the -100 .. 100 range).
-- @return A dynamixel error code.
--- Set the lock status (volatile).
-- @function set.lock
-- @param lock once set to true, can be unlocked only powering down the motor.
-- @return A dynamixel error code.
| 34.788945 | 129 | 0.710711 |
0a14abcd4a2ce2fadd0ad57910a0fb8b81d047ef | 150 | h | C | src/MolecularMechanics/SetMMParameters.h | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/MolecularMechanics/SetMMParameters.h | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/MolecularMechanics/SetMMParameters.h | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null |
#ifndef __GABEDIT_SETMMPARAMETERS_H__
#define __GABEDIT_SETMMPARAMETERS_H__
void setMMParamatersDlg();
#endif /* __GABEDIT_SETMMPARAMETERS_H__ */
| 16.666667 | 42 | 0.84 |
c2e567162364b6ee9b8f4d3f08b931cd930143b9 | 2,472 | swift | Swift | Sources/Meadow/Data Types/FootprintChunk.swift | zilmarinen/Meadow | a524a06f5fc06c1fd20113bb35e4457ecbba477c | [
"MIT"
] | 1 | 2021-09-19T15:09:36.000Z | 2021-09-19T15:09:36.000Z | Sources/Meadow/Data Types/FootprintChunk.swift | zilmarinen/Meadow | a524a06f5fc06c1fd20113bb35e4457ecbba477c | [
"MIT"
] | null | null | null | Sources/Meadow/Data Types/FootprintChunk.swift | zilmarinen/Meadow | a524a06f5fc06c1fd20113bb35e4457ecbba477c | [
"MIT"
] | null | null | null | //
// FootprintChunk.swift
//
// Created by Zack Brown on 27/03/2021.
//
import SceneKit
public class FootprintChunk: SCNNode, Codable, Hideable, Responder, Shadable, Soilable {
private enum CodingKeys: String, CodingKey {
case coordinate = "co"
case direction = "d"
}
public var ancestor: SoilableParent? { parent as? SoilableParent }
public var isDirty: Bool = false
public var category: SceneGraphCategory { .surfaceChunk }
public var footprint: Footprint { Footprint(coordinate: coordinate, rotation: direction, nodes: prop.footprint.nodes) }
public var prop: Model { fatalError("prop has not been implemented") }
private(set) public var coordinate: Coordinate {
didSet {
if oldValue != coordinate {
becomeDirty()
}
}
}
public let direction: Cardinal
public var program: SCNProgram? { nil }
public var uniforms: [Uniform]? { nil }
public var textures: [Texture]? { nil }
var offset: Coordinate = .zero {
didSet {
if oldValue != offset {
coordinate = (coordinate - oldValue) + offset
becomeDirty()
}
}
}
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
coordinate = try container.decode(Coordinate.self, forKey: .coordinate)
direction = try container.decode(Cardinal.self, forKey: .direction)
super.init()
name = "Chunk \(coordinate.description)"
categoryBitMask = category.rawValue
becomeDirty()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@discardableResult public func clean() -> Bool {
guard isDirty else { return false }
position = SCNVector3(coordinate.world)
geometry?.program = program
if let uniforms = uniforms {
geometry?.set(uniforms: uniforms)
}
if let textures = textures {
geometry?.set(textures: textures)
}
isDirty = false
return true
}
}
| 24.72 | 123 | 0.540049 |
75eb4abb44ecac6c28c5d0e4ad42314416be329c | 8,014 | php | PHP | application/views/home.php | ChenttlyEnggar/ci3 | 6d7c47a086400cd837099870043549142a17561c | [
"MIT"
] | null | null | null | application/views/home.php | ChenttlyEnggar/ci3 | 6d7c47a086400cd837099870043549142a17561c | [
"MIT"
] | null | null | null | application/views/home.php | ChenttlyEnggar/ci3 | 6d7c47a086400cd837099870043549142a17561c | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<title>Yogyakarta</title>
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" href="aseets/css/bootstrap.css">
<link rel="stylesheet" href="assets/css/style.css">
<link rel="stylesheet" href="assets/css/font-awesome.min.css" type="text/css">
<link rel="stylesheet" href="assets/css/font-awesome.css" type="text/css">
</head>
<body>
<nav class="navbar navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="single-page-nav sticky-wrapper" id="tmNavbar">
<ul class="nav navbar-nav">
<li><a class="page-scroll" href="#carousel-281873">Home</a></li>
<li><a class="page-scroll" href="#sejarah">About</a></li>
<li><a class="page-scroll" href="#profil">Profil</a></li>
<li><a class="page-scroll" href="about">Blog</a></li>
</ul>
</div>
</div>
</nav>
</div>
<div class="row">
<div class="col-md-12">
<div class="carousel slide" id="carousel-281873">
<ol class="carousel-indicators">
</li>
<li data-slide-to="2" data-target="#carousel-281873" class="active">
</li>
</ol>
<div class="item active">
<img alt="Carousel Bootstrap Third" src="assets/img/gambar1.png">
<div class="carousel-caption">
<h4>
Candi Borobudur
</h4>
</div>
</div>
</div> <a class="left carousel-control" href="#carousel-281873" data-slide="prev"><span class="glyphicon glyphicon-chevron-left"></span></a> <a class="right carousel-control" href="#carousel-281873" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
</div>
<div class="row">
<section id="sejarah">
<div class="col-md-8">
<h1>SEJARAH</h1>
<font size="4px">
<p>
Berdirinya Kota Yogyakarta berawal dari adanya Perjanjian Gianti pada Tanggal 13 Februari 1755 yang ditandatangani Kompeni Belanda di bawah tanda tangan Gubernur Nicholas Hartingh atas nama Gubernur Jendral Jacob Mossel.
Isi Perjanjian Gianti : Negara Mataram dibagi dua : Setengah masih menjadi Hak Kerajaan Surakarta, setengah lagi menjadi Hak Pangeran Mangkubumi. Dalam perjanjian itu pula Pengeran Mangkubumi diakui menjadi Raja tas setengah daerah Pedalaman Kerajaan Jawa dengan Gelar Sultan Hamengku Buwono Senopati Ing Alega Abdul Rachman Sayidin Panatagama Khalifatullah.
Adapun daerah-daerah yang menjadi kekuasaannya adalah Mataram (Yogyakarta), Pojong, Sukowati, Bagelen, Kedu, Bumigede dan ditambah daerah mancanegara yaitu; Madiun, Magetan, Cirebon, Separuh Pacitan, Kartosuro, Kalangbret, Tulungagung, Mojokerto, Bojonegoro, Ngawen, Sela, Kuwu, Wonosari, Grobogan.
Setelah selesai Perjanjian Pembagian Daerah itu, Pengeran Mangkubumi yang bergelar Sultan Hamengku Buwono I segera menetapkan bahwa Daerah Mataram yang ada di dalam kekuasaannya itu diberi nama Ngayogyakarta Hadiningrat dan beribukota di Ngayogyakarta (Yogyakarta). Ketetapan ini diumumkan pada tanggal 13 Maret 1755.
</p>
</font>
<img src="">
</div>
</section>
</div>
<div class="row">
<section id="profil">
<div class="row">
<div class="col-md-4">
<div class="thumbnail">
<img alt="Bootstrap Thumbnail First" src="assets/img/borobudur.jpg">
<div class="caption">
<h3>
Candi Borobudur
</h3>
<p>
Borobudur adalah sebuah candi Buddha yang terletak di Borobudur, Magelang, Jawa Tengah, Indonesia. Candi ini berlokasi di kurang lebih 100 km di sebelah barat daya Semarang, 86 km di sebelah barat Surakarta, dan 40 km di sebelah barat laut Yogyakarta. Candi berbentuk stupa ini didirikan oleh para penganut agama Buddha Mahayana sekitar abad ke-8 masehi pada masa pemerintahan wangsa Syailendra. Borobudur adalah candi atau kuil Buddha terbesar di dunia, sekaligus salah satu monumen Buddha terbesar di dunia.
</p>
<p>
<a class="btn btn-primary" href="#">Action</a> <a class="btn" href="#">Action</a>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="thumbnail">
<img alt="Bootstrap Thumbnail Second" src="assets/img/gambar22.jpg">
<div class="caption">
<h3>
Malioboro
</h3>
<p>
Jalan Malioboro (bahasa Jawa: Hanacaraka, ꦢꦭꦤ꧀ꦩꦭꦶꦲꦧꦫ , Dalan Malioboro) adalah nama salah satu kawasan jalan dari tiga jalan di Kota Yogyakarta yang membentang dari Tugu Yogyakarta hingga ke perempatan Kantor Pos Yogyakarta. Secara keseluruhan terdiri dari Jalan Margo Utomo, Jalan Malioboro, dan Jalan Margo Mulyo. Jalan ini merupakan poros Garis Imajiner Kraton Yogyakarta.
Pada tanggal 20 Desember 2013, pukul 10.30 oleh Sri Sultan Hamengkubuwono X nama dua ruas jalan Malioboro dikembalikan ke nama aslinya, Jalan Pangeran Mangkubumi menjadi jalan Margo Utomo, dan Jalan Jenderal Achmad Yani menjadi jalan Margo Mulyo.[1]
Terdapat beberapa objek bersejarah di kawasan tiga jalan ini antara lain Tugu Yogyakarta, Stasiun Tugu, Gedung Agung, Pasar Beringharjo, Benteng Vredeburg, dan Monumen Serangan Oemoem 1 Maret.
Jalan Malioboro sangat terkenal dengan para pedagang kaki lima yang menjajakan kerajinan khas Jogja dan warung-warung lesehan di malam hari yang menjual makanan gudeg Jogja serta terkenal sebagai tempat berkumpulnya para seniman yang sering mengekpresikan kemampuan mereka seperti bermain musik, melukis, hapening art, pantomim, dan lain-lain di sepanjang jalan ini.
Saat ini, Jalan Malioboro tampak lebih lebar karena tempat parkir yang ada di pinggir jalan sudah dipindahkan ke kawasan parkir Abu Bakar Ali. Sehingga, untuk para pejalan kaki jadi lebih leluasa karena trotoar di Jalan Malioboro bisa digunakan sepenuhnya.
</p>
<p>
<a class="btn btn-primary" href="#">Action</a> <a class="btn" href="#">Action</a>
</p>
</div>
</div>
</div>
<div class="col-md-4">
<div class="thumbnail">
<img alt="Bootstrap Thumbnail Third" src="assets/img/gambar33.jpg">
<div class="caption">
<h3>
Candi Prambanan
</h3>
<p>
Candi Prambanan atau Candi Roro Jonggrang adalah kompleks candi Hindu terbesar di Indonesia yang dibangun pada abad ke-9 masehi. Candi ini dipersembahkan untuk Trimurti, tiga dewa utama Hindu yaitu Brahma sebagai dewa pencipta, Wishnu sebagai dewa pemelihara, dan Siwa sebagai dewa pemusnah. Berdasarkan prasasti Siwagrha nama asli kompleks candi ini adalah Siwagrha (bahasa Sanskerta yang bermakna 'Rumah Siwa'), dan memang di garbagriha (ruang utama) candi ini bersemayam arca Siwa Mahadewa setinggi tiga meter yang menujukkan bahwa di candi ini dewa Siwa lebih diutamakan.
Kompleks candi ini terletak di kecamatan Prambanan, Sleman dan kecamatan Prambanan, Klaten,[1] kurang lebih 17 kilometer timur laut Yogyakarta, 50 kilometer barat daya Surakarta dan 120 kilometer selatan Semarang, persis di perbatasan antara provinsi Jawa Tengah dan Daerah Istimewa Yogyakarta.[2] Letaknya sangat unik, Candi Prambanan terletak di wilayah administrasi desa Bokoharjo, Prambanan, Sleman, sedangkan pintu masuk kompleks Candi Prambanan terletak di wilayah adminstrasi desa Tlogo, Prambanan, Klaten.
</p>
<p>
<a class="btn btn-primary" href="#">Action</a> <a class="btn" href="#">Action</a>
</p>
</div>
</div>
</div>
</div>
</section>
</div>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/scripts.js"></script>
<script src="assets/js/custom.js"></script>
<script src="assets/js/jquery.easing.min.js"></script>
<script src="assets/js/scrolling-nav.js"></script>
</body>
</html> | 52.723684 | 583 | 0.69728 |
a4bb3b70e3ed3e1ab154a10cca71f82e858adab9 | 360 | swift | Swift | Shared/Global/App/AppView+State.swift | crelies/Game-of-Thrones-VIPER-SwiftUI | 4fd5b52492f9ccaf07dd6b187a00190c23b7e626 | [
"MIT"
] | 1 | 2019-11-26T20:28:28.000Z | 2019-11-26T20:28:28.000Z | Shared/Global/App/AppView+State.swift | crelies/Game-of-Thrones-SwiftUI | 4fd5b52492f9ccaf07dd6b187a00190c23b7e626 | [
"MIT"
] | null | null | null | Shared/Global/App/AppView+State.swift | crelies/Game-of-Thrones-SwiftUI | 4fd5b52492f9ccaf07dd6b187a00190c23b7e626 | [
"MIT"
] | 1 | 2019-11-18T00:39:27.000Z | 2019-11-18T00:39:27.000Z | //
// AppView+State.swift
// Game-of-Thrones-SwiftUI
//
// Created Christian Elies on 31.08.21.
// Copyright © 2021 Christian Elies. All rights reserved.
//
// Template generated by Christian Elies @crelies
// https://www.christianelies.de
//
extension AppView {
struct State: Equatable {
let selectedNavigationItem: NavigationItem?
}
}
| 21.176471 | 58 | 0.691667 |
86a489fca0d734c85a458c6134b24df4ad3a4ad0 | 912 | rs | Rust | common/client-libs/validator-client/src/nymd/cosmwasm_client/mod.rs | nymtech/nym | 20c96b940fdf15659ab3e5b61765a78e15071332 | [
"Apache-2.0",
"MIT"
] | 543 | 2019-06-12T15:53:42.000Z | 2022-03-31T08:28:41.000Z | common/client-libs/validator-client/src/nymd/cosmwasm_client/mod.rs | arno01/nym | f63aba9058882b26c540fefb1ac7f081c3077256 | [
"Apache-2.0",
"MIT"
] | 518 | 2019-06-14T09:19:55.000Z | 2022-03-29T12:32:35.000Z | common/client-libs/validator-client/src/nymd/cosmwasm_client/mod.rs | arno01/nym | f63aba9058882b26c540fefb1ac7f081c3077256 | [
"Apache-2.0",
"MIT"
] | 82 | 2019-06-12T15:53:53.000Z | 2022-03-24T19:22:40.000Z | // Copyright 2021 - Nym Technologies SA <contact@nymtech.net>
// SPDX-License-Identifier: Apache-2.0
use crate::nymd::error::NymdError;
use crate::nymd::wallet::DirectSecp256k1HdWallet;
use cosmrs::rpc::{Error as TendermintRpcError, HttpClient, HttpClientUrl};
use std::convert::TryInto;
pub mod client;
mod helpers;
pub mod logs;
pub mod signing_client;
pub mod types;
pub fn connect<U>(endpoint: U) -> Result<HttpClient, NymdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
Ok(HttpClient::new(endpoint)?)
}
// maybe the wallet could be made into a generic, but for now, let's just have this one implementation
pub fn connect_with_signer<U>(
endpoint: U,
signer: DirectSecp256k1HdWallet,
) -> Result<signing_client::Client, NymdError>
where
U: TryInto<HttpClientUrl, Error = TendermintRpcError>,
{
signing_client::Client::connect_with_signer(endpoint, signer)
}
| 28.5 | 102 | 0.75 |
77a6c3fecb923de551d47cad19dd10a9e6328c8d | 244 | kt | Kotlin | app/src/main/java/org/techtown/wishmatching/RealtimeDB/ImageChatMessage.kt | KPUCE2021SP/TotheMoon | 46e8b8cb6e47a672647bfa79d341b153c04476c5 | [
"MIT"
] | 5 | 2021-09-08T15:46:10.000Z | 2021-09-08T15:46:39.000Z | app/src/main/java/org/techtown/wishmatching/RealtimeDB/ImageChatMessage.kt | Gyubam/TotheMoon-1 | 46e8b8cb6e47a672647bfa79d341b153c04476c5 | [
"MIT"
] | 4 | 2021-07-28T15:59:52.000Z | 2021-09-09T11:10:02.000Z | app/src/main/java/org/techtown/wishmatching/RealtimeDB/ImageChatMessage.kt | Gyubam/TotheMoon-1 | 46e8b8cb6e47a672647bfa79d341b153c04476c5 | [
"MIT"
] | 6 | 2021-07-27T17:43:21.000Z | 2022-03-02T03:25:44.000Z | package org.techtown.wishmatching.RealtimeDB
class ImageChatMessage(val id: String, val imageUrl: String, val fromId:String, val toId:String, val timestamp: Long,val nickname:String,val flag:Int){
constructor(): this("","","","",-1,"",0)
} | 48.8 | 151 | 0.72541 |
c9ba3af74a11fdd68bd0f84e3b0a454250af97fa | 401 | sql | SQL | src/main/resources/db/migration/V2021_07_06_1345__migrate_spec_legal_rep_reference_number_seq.sql | hmcts/civil-service | 3a4c3984595c74a279d9b0c9310551b274880fd2 | [
"MIT"
] | 3 | 2021-06-01T13:09:09.000Z | 2021-12-09T10:20:37.000Z | src/main/resources/db/migration/V2021_07_06_1345__migrate_spec_legal_rep_reference_number_seq.sql | hmcts/civil-service | 3a4c3984595c74a279d9b0c9310551b274880fd2 | [
"MIT"
] | 324 | 2021-06-11T06:36:26.000Z | 2022-03-31T13:50:21.000Z | src/main/resources/db/migration/V2021_07_06_1345__migrate_spec_legal_rep_reference_number_seq.sql | hmcts/civil-service | 3a4c3984595c74a279d9b0c9310551b274880fd2 | [
"MIT"
] | 1 | 2022-03-17T20:51:56.000Z | 2022-03-17T20:51:56.000Z | CREATE SEQUENCE claim_SPEC_legal_rep_reference_number_seq MAXVALUE 999999 NO CYCLE;
/**
* Returns a new reference number from a 000MC001...999MC999 range.
*/
CREATE FUNCTION next_SPEC_legal_rep_reference_number() RETURNS TEXT AS $$
SELECT
regexp_replace(
to_char(
nextval('claim_SPEC_legal_rep_reference_number_seq'),
'FM000000'),
'(\d{3})(\d{3})', '\1MC\2')
$$ LANGUAGE SQL;
| 28.642857 | 83 | 0.730673 |
71ba05c2b39437af1204fed041d592d30908a25e | 424 | ts | TypeScript | api/services/certificate/src/interfaces/HtmlPrinterProviderInterface.ts | betagouv/preuve-covoiturage | 38a167323781e1f2ef586489bfe6e0308c1541ea | [
"Apache-2.0"
] | 25 | 2018-11-07T15:22:46.000Z | 2021-12-13T13:45:32.000Z | api/services/certificate/src/interfaces/HtmlPrinterProviderInterface.ts | betagouv/preuve-covoiturage | 38a167323781e1f2ef586489bfe6e0308c1541ea | [
"Apache-2.0"
] | 1,055 | 2018-11-15T16:36:47.000Z | 2022-03-30T13:53:11.000Z | api/services/certificate/src/interfaces/HtmlPrinterProviderInterface.ts | betagouv/preuve-covoiturage | 38a167323781e1f2ef586489bfe6e0308c1541ea | [
"Apache-2.0"
] | 5 | 2019-07-09T08:29:43.000Z | 2021-02-22T13:03:10.000Z | export interface HtmlPrinterProviderInterface {
png(uuid: string): Promise<Buffer>;
pdf(uuid: string): Promise<Buffer>;
}
export abstract class HtmlPrinterProviderInterfaceResolver implements HtmlPrinterProviderInterface {
async png(uuid: string): Promise<Buffer> {
throw new Error('Method not implemented.');
}
async pdf(uuid: string): Promise<Buffer> {
throw new Error('Method not implemented.');
}
}
| 30.285714 | 100 | 0.745283 |
fecd44c4a01f3b56454083eb40c1c1295f347722 | 345 | html | HTML | canvasTest/index.html | Brancepeng/HTMLCSS | 775c74b7584100e54423af40501f398d81ede7af | [
"MIT"
] | null | null | null | canvasTest/index.html | Brancepeng/HTMLCSS | 775c74b7584100e54423af40501f398d81ede7af | [
"MIT"
] | null | null | null | canvasTest/index.html | Brancepeng/HTMLCSS | 775c74b7584100e54423af40501f398d81ede7af | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>canvas绘图测试</title>
<link rel="stylesheet" href="normalize.css">
<link rel="stylesheet" href="style.css" media="screen" type="text/css" />
</head>
<body>
<canvas id="drawing">This is a drawing.</canvas>
<script src="canvasTest.js"></script>
</body>
</html>
| 23 | 77 | 0.643478 |
9c60cde09e9226ecc22d2ecdd00bc0f81c5ea16c | 1,296 | js | JavaScript | app/router.js | dolcalmi/coquito-express | 193d55da85498d5acf49371954947836f88635c3 | [
"MIT"
] | 3 | 2017-05-08T21:58:02.000Z | 2020-08-12T17:06:56.000Z | app/router.js | dolcalmi/coquito-express | 193d55da85498d5acf49371954947836f88635c3 | [
"MIT"
] | null | null | null | app/router.js | dolcalmi/coquito-express | 193d55da85498d5acf49371954947836f88635c3 | [
"MIT"
] | 1 | 2019-05-07T17:19:41.000Z | 2019-05-07T17:19:41.000Z | import path from 'path';
import { express, Router } from 'express';
import ExpressRouteBuilder from 'express-route-builder';
import AccountController from 'app/controllers/account';
import jwtAuthorization from 'app/middlewares/jwt-authorization';
export default function(appContext) {
const router = Router();
const baseDir = path.join(__dirname, 'controllers/');
const builder = new ExpressRouteBuilder(express, router, baseDir);
builder.addRoute('/', 'index');
builder.addRoute('/login', { post: AccountController.login });
builder.addRoute('/signup', { post: AccountController.signup });
builder.addRoute('/activate', { post: AccountController.activate });
builder.addRoute('/change-password', { post: AccountController.changePassword }, jwtAuthorization(appContext));
builder.addRoute('/forgot-password', { post: AccountController.forgotPassword });
builder.addRoute('/reset-password', { post: AccountController.resetPassword });
builder.addRoute('/users', 'users', jwtAuthorization(appContext));
// Or you can explicitly define functions for each route and method.
// builder.addRoute('/other/data', {
// get: (req, res, next) => { ... },
// post: (req, res, next) => { ... },
// ...
// })
return router;
}
| 41.806452 | 115 | 0.688272 |
16a9a8455644f8de61b24ddbfddc267ee8dde0fd | 2,789 | h | C | printscan/faxsrv/exchange/xport/resource.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/faxsrv/exchange/xport/resource.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/faxsrv/exchange/xport/resource.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////
// //
// MAPI Transport Provider resource ID file //
// It compiles as part of FxsRes.dll //
// All the IDs should be in range //
// //
// [11500 - 11999] //
// //
//////////////////////////////////////////////////////
#include "..\..\admin\faxres\resource.h"
#define IDD_FAX_PROP_CONFIG 11500
#define IDI_FAX_EXT 11501
#define IDS_CANT_ACCESS_PRINTER 11503
#define IDS_RESOURCES_UNAVAIL 11504
#define IDS_CANT_PRINT 11505
#define IDS_CANT_ACCESS_MSG_DATA 11506
#define IDS_CANT_ACCESS_PROFILE 11507
#define IDS_BAD_ATTACHMENTS 11508
#define IDS_FONT_REGULAR 11509
#define IDS_FONT_ITALIC 11510
#define IDS_FONT_BOLD 11511
#define IDS_FAX_MESSAGE 11513
#define IDS_CANT_PRINT_BODY 11515
#define IDS_FAILED_MESSAGE 11516
#define IDS_OUT_OF_MEM 11517
#define IDS_INTERNAL_ERROR 11518
#define IDS_SUBJECT_FORMAT 11519
#define IDS_PERSONAL_CP_FORBIDDEN 11520
#define IDS_BAD_CANNONICAL_ADDRESS 11521
#define IDS_NO_MSG_ATTACHMENTS 11522
#define IDS_NO_MSG_BODY 11523
#define IDS_EMPTY_MESSAGE 11524
#define IDC_SET_FONT 11528
#define IDC_FONT_NAME 11529
#define IDC_FONT_STYLE 11530
#define IDC_FONT_SIZE 11531
#define IDCSTATIC_FONT 11532
#define IDCSTATIC_FONTSTYLE 11533
#define IDCSTATIC_FONTSIZE 11534
#define IDC_COVERPAGE_LIST_LABEL 11535
#define IDCSTATIC_FONT_GROUP 11536
#define IDC_STATIC_ICON 11537
#define IDC_STATIC_TITLE 11538
#define IDC_STATIC_PRINTERS 11539
#define IDS_NO_SUBMIT_RITHTS 11541
#define IDS_RECIPIENTS_LIMIT 11542
#define IDS_MESSAGE_DOC_NAME 11543
//////////////////////////////////////////////////////
// //
// MAPI Transport Provider resource ID file //
// It compiles as part of FxsRes.dll //
// All the IDs should be in range //
// //
// [11500 - 11999] //
// //
//////////////////////////////////////////////////////
| 46.483333 | 55 | 0.461814 |
d2de3641a53479211f5d75d91b2a592d89ec6c11 | 2,640 | php | PHP | models/Alumnos.php | comau22/HRProject | 0ad3acfc4a9878556500d58f735b82351a924e6f | [
"BSD-3-Clause"
] | null | null | null | models/Alumnos.php | comau22/HRProject | 0ad3acfc4a9878556500d58f735b82351a924e6f | [
"BSD-3-Clause"
] | null | null | null | models/Alumnos.php | comau22/HRProject | 0ad3acfc4a9878556500d58f735b82351a924e6f | [
"BSD-3-Clause"
] | null | null | null | <?php
namespace app\models;
use Yii;
/**
* This is the model class for table "alumnos".
*
* @property int $idAlumno
* @property string $nombre
* @property string $aPaterno
* @property string $aMaterno
* @property int $dia_nac
* @property int $mes_nac
* @property int $ano_nac
* @property string $sexo
* @property string $rfc
* @property string $status
* @property float $promedio
* @property int $id_grupo
*
* @property Grupos $grupo
* @property AsignaturaAlumno[] $asignaturaAlumnos
* @property Calificacion[] $calificacions
*/
class Alumnos extends \yii\db\ActiveRecord
{
/**
* {@inheritdoc}
*/
public static function tableName()
{
return 'alumnos';
}
/**
* {@inheritdoc}
*/
public function rules()
{
return [
[['nombre', 'aPaterno', 'aMaterno', 'dia_nac', 'mes_nac', 'ano_nac', 'sexo', 'rfc', 'status', 'promedio', 'id_grupo'], 'required'],
[['dia_nac', 'mes_nac', 'ano_nac', 'id_grupo'], 'integer'],
[['promedio'], 'number'],
[['nombre', 'aPaterno', 'aMaterno'], 'string', 'max' => 15],
[['sexo', 'status'], 'string', 'max' => 20],
[['rfc'], 'string', 'max' => 13],
[['id_grupo'], 'exist', 'skipOnError' => true, 'targetClass' => Grupos::className(), 'targetAttribute' => ['id_grupo' => 'id_grupo']],
];
}
/**
* {@inheritdoc}
*/
public function attributeLabels()
{
return [
'idAlumno' => 'Id Alumno',
'nombre' => 'Nombre',
'aPaterno' => 'A Paterno',
'aMaterno' => 'A Materno',
'dia_nac' => 'Dia Nac',
'mes_nac' => 'Mes Nac',
'ano_nac' => 'Ano Nac',
'sexo' => 'Sexo',
'rfc' => 'Rfc',
'status' => 'Status',
'promedio' => 'Promedio',
'id_grupo' => 'Id Grupo',
];
}
/**
* Gets query for [[Grupo]].
*
* @return \yii\db\ActiveQuery
*/
public function getGrupo()
{
return $this->hasOne(Grupos::className(), ['id_grupo' => 'id_grupo']);
}
/**
* Gets query for [[AsignaturaAlumnos]].
*
* @return \yii\db\ActiveQuery
*/
public function getAsignaturaAlumnos()
{
return $this->hasMany(AsignaturaAlumno::className(), ['id_alumno' => 'idAlumno']);
}
/**
* Gets query for [[Calificacions]].
*
* @return \yii\db\ActiveQuery
*/
public function getCalificacions()
{
return $this->hasMany(Calificacion::className(), ['id_alumno' => 'idAlumno']);
}
}
| 25.384615 | 146 | 0.521591 |
5c45cb58d023827665d22385e044c199a753a96d | 18,570 | c | C | src/linux/drivers/net/ks8842.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 21 | 2021-01-22T06:47:38.000Z | 2022-03-20T14:24:29.000Z | src/linux/drivers/net/ks8842.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 1 | 2021-08-07T07:14:45.000Z | 2021-08-07T08:24:23.000Z | src/linux/drivers/net/ks8842.c | wangyan98/linux-lib | f98bbaec0d696b948935939b2d613cd15cd6105f | [
"MIT"
] | 12 | 2021-01-22T14:59:28.000Z | 2022-02-22T04:03:31.000Z | /*
* ks8842_main.c timberdale KS8842 ethernet driver
* Copyright (c) 2009 Intel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* Supports:
* The Micrel KS8842 behind the timberdale FPGA
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/ethtool.h>
#define DRV_NAME "ks8842"
/* Timberdale specific Registers */
#define REG_TIMB_RST 0x1c
/* KS8842 registers */
#define REG_SELECT_BANK 0x0e
/* bank 0 registers */
#define REG_QRFCR 0x04
/* bank 2 registers */
#define REG_MARL 0x00
#define REG_MARM 0x02
#define REG_MARH 0x04
/* bank 3 registers */
#define REG_GRR 0x06
/* bank 16 registers */
#define REG_TXCR 0x00
#define REG_TXSR 0x02
#define REG_RXCR 0x04
#define REG_TXMIR 0x08
#define REG_RXMIR 0x0A
/* bank 17 registers */
#define REG_TXQCR 0x00
#define REG_RXQCR 0x02
#define REG_TXFDPR 0x04
#define REG_RXFDPR 0x06
#define REG_QMU_DATA_LO 0x08
#define REG_QMU_DATA_HI 0x0A
/* bank 18 registers */
#define REG_IER 0x00
#define IRQ_LINK_CHANGE 0x8000
#define IRQ_TX 0x4000
#define IRQ_RX 0x2000
#define IRQ_RX_OVERRUN 0x0800
#define IRQ_TX_STOPPED 0x0200
#define IRQ_RX_STOPPED 0x0100
#define IRQ_RX_ERROR 0x0080
#define ENABLED_IRQS (IRQ_LINK_CHANGE | IRQ_TX | IRQ_RX | IRQ_RX_STOPPED | \
IRQ_TX_STOPPED | IRQ_RX_OVERRUN | IRQ_RX_ERROR)
#define REG_ISR 0x02
#define REG_RXSR 0x04
#define RXSR_VALID 0x8000
#define RXSR_BROADCAST 0x80
#define RXSR_MULTICAST 0x40
#define RXSR_UNICAST 0x20
#define RXSR_FRAMETYPE 0x08
#define RXSR_TOO_LONG 0x04
#define RXSR_RUNT 0x02
#define RXSR_CRC_ERROR 0x01
#define RXSR_ERROR (RXSR_TOO_LONG | RXSR_RUNT | RXSR_CRC_ERROR)
/* bank 32 registers */
#define REG_SW_ID_AND_ENABLE 0x00
#define REG_SGCR1 0x02
#define REG_SGCR2 0x04
#define REG_SGCR3 0x06
/* bank 39 registers */
#define REG_MACAR1 0x00
#define REG_MACAR2 0x02
#define REG_MACAR3 0x04
/* bank 45 registers */
#define REG_P1MBCR 0x00
#define REG_P1MBSR 0x02
/* bank 46 registers */
#define REG_P2MBCR 0x00
#define REG_P2MBSR 0x02
/* bank 48 registers */
#define REG_P1CR2 0x02
/* bank 49 registers */
#define REG_P1CR4 0x02
#define REG_P1SR 0x04
struct ks8842_adapter {
void __iomem *hw_addr;
int irq;
struct tasklet_struct tasklet;
spinlock_t lock; /* spinlock to be interrupt safe */
struct platform_device *pdev;
};
static inline void ks8842_select_bank(struct ks8842_adapter *adapter, u16 bank)
{
iowrite16(bank, adapter->hw_addr + REG_SELECT_BANK);
}
static inline void ks8842_write8(struct ks8842_adapter *adapter, u16 bank,
u8 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite8(value, adapter->hw_addr + offset);
}
static inline void ks8842_write16(struct ks8842_adapter *adapter, u16 bank,
u16 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite16(value, adapter->hw_addr + offset);
}
static inline void ks8842_enable_bits(struct ks8842_adapter *adapter, u16 bank,
u16 bits, int offset)
{
u16 reg;
ks8842_select_bank(adapter, bank);
reg = ioread16(adapter->hw_addr + offset);
reg |= bits;
iowrite16(reg, adapter->hw_addr + offset);
}
static inline void ks8842_clear_bits(struct ks8842_adapter *adapter, u16 bank,
u16 bits, int offset)
{
u16 reg;
ks8842_select_bank(adapter, bank);
reg = ioread16(adapter->hw_addr + offset);
reg &= ~bits;
iowrite16(reg, adapter->hw_addr + offset);
}
static inline void ks8842_write32(struct ks8842_adapter *adapter, u16 bank,
u32 value, int offset)
{
ks8842_select_bank(adapter, bank);
iowrite32(value, adapter->hw_addr + offset);
}
static inline u8 ks8842_read8(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread8(adapter->hw_addr + offset);
}
static inline u16 ks8842_read16(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread16(adapter->hw_addr + offset);
}
static inline u32 ks8842_read32(struct ks8842_adapter *adapter, u16 bank,
int offset)
{
ks8842_select_bank(adapter, bank);
return ioread32(adapter->hw_addr + offset);
}
static void ks8842_reset(struct ks8842_adapter *adapter)
{
/* The KS8842 goes haywire when doing softare reset
* a work around in the timberdale IP is implemented to
* do a hardware reset instead
ks8842_write16(adapter, 3, 1, REG_GRR);
msleep(10);
iowrite16(0, adapter->hw_addr + REG_GRR);
*/
iowrite16(32, adapter->hw_addr + REG_SELECT_BANK);
iowrite32(0x1, adapter->hw_addr + REG_TIMB_RST);
msleep(20);
}
static void ks8842_update_link_status(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
/* check the status of the link */
if (ks8842_read16(adapter, 45, REG_P1MBSR) & 0x4) {
netif_carrier_on(netdev);
netif_wake_queue(netdev);
} else {
netif_stop_queue(netdev);
netif_carrier_off(netdev);
}
}
static void ks8842_enable_tx(struct ks8842_adapter *adapter)
{
ks8842_enable_bits(adapter, 16, 0x01, REG_TXCR);
}
static void ks8842_disable_tx(struct ks8842_adapter *adapter)
{
ks8842_clear_bits(adapter, 16, 0x01, REG_TXCR);
}
static void ks8842_enable_rx(struct ks8842_adapter *adapter)
{
ks8842_enable_bits(adapter, 16, 0x01, REG_RXCR);
}
static void ks8842_disable_rx(struct ks8842_adapter *adapter)
{
ks8842_clear_bits(adapter, 16, 0x01, REG_RXCR);
}
static void ks8842_reset_hw(struct ks8842_adapter *adapter)
{
/* reset the HW */
ks8842_reset(adapter);
/* Enable QMU Transmit flow control / transmit padding / Transmit CRC */
ks8842_write16(adapter, 16, 0x000E, REG_TXCR);
/* enable the receiver, uni + multi + broadcast + flow ctrl
+ crc strip */
ks8842_write16(adapter, 16, 0x8 | 0x20 | 0x40 | 0x80 | 0x400,
REG_RXCR);
/* TX frame pointer autoincrement */
ks8842_write16(adapter, 17, 0x4000, REG_TXFDPR);
/* RX frame pointer autoincrement */
ks8842_write16(adapter, 17, 0x4000, REG_RXFDPR);
/* RX 2 kb high watermark */
ks8842_write16(adapter, 0, 0x1000, REG_QRFCR);
/* aggresive back off in half duplex */
ks8842_enable_bits(adapter, 32, 1 << 8, REG_SGCR1);
/* enable no excessive collison drop */
ks8842_enable_bits(adapter, 32, 1 << 3, REG_SGCR2);
/* Enable port 1 force flow control / back pressure / transmit / recv */
ks8842_write16(adapter, 48, 0x1E07, REG_P1CR2);
/* restart port auto-negotiation */
ks8842_enable_bits(adapter, 49, 1 << 13, REG_P1CR4);
/* only advertise 10Mbps */
ks8842_clear_bits(adapter, 49, 3 << 2, REG_P1CR4);
/* Enable the transmitter */
ks8842_enable_tx(adapter);
/* Enable the receiver */
ks8842_enable_rx(adapter);
/* clear all interrupts */
ks8842_write16(adapter, 18, 0xffff, REG_ISR);
/* enable interrupts */
ks8842_write16(adapter, 18, ENABLED_IRQS, REG_IER);
/* enable the switch */
ks8842_write16(adapter, 32, 0x1, REG_SW_ID_AND_ENABLE);
}
static void ks8842_read_mac_addr(struct ks8842_adapter *adapter, u8 *dest)
{
int i;
u16 mac;
for (i = 0; i < ETH_ALEN; i++)
dest[ETH_ALEN - i - 1] = ks8842_read8(adapter, 2, REG_MARL + i);
/* make sure the switch port uses the same MAC as the QMU */
mac = ks8842_read16(adapter, 2, REG_MARL);
ks8842_write16(adapter, 39, mac, REG_MACAR1);
mac = ks8842_read16(adapter, 2, REG_MARM);
ks8842_write16(adapter, 39, mac, REG_MACAR2);
mac = ks8842_read16(adapter, 2, REG_MARH);
ks8842_write16(adapter, 39, mac, REG_MACAR3);
}
static inline u16 ks8842_tx_fifo_space(struct ks8842_adapter *adapter)
{
return ks8842_read16(adapter, 16, REG_TXMIR) & 0x1fff;
}
static int ks8842_tx_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
int len = skb->len;
u32 *ptr = (u32 *)skb->data;
u32 ctrl;
dev_dbg(&adapter->pdev->dev,
"%s: len %u head %p data %p tail %p end %p\n",
__func__, skb->len, skb->head, skb->data,
skb_tail_pointer(skb), skb_end_pointer(skb));
/* check FIFO buffer space, we need space for CRC and command bits */
if (ks8842_tx_fifo_space(adapter) < len + 8)
return NETDEV_TX_BUSY;
/* the control word, enable IRQ, port 1 and the length */
ctrl = 0x8000 | 0x100 | (len << 16);
ks8842_write32(adapter, 17, ctrl, REG_QMU_DATA_LO);
netdev->stats.tx_bytes += len;
/* copy buffer */
while (len > 0) {
iowrite32(*ptr, adapter->hw_addr + REG_QMU_DATA_LO);
len -= sizeof(u32);
ptr++;
}
/* enqueue packet */
ks8842_write16(adapter, 17, 1, REG_TXQCR);
dev_kfree_skb(skb);
return NETDEV_TX_OK;
}
static void ks8842_rx_frame(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
u32 status = ks8842_read32(adapter, 17, REG_QMU_DATA_LO);
int len = (status >> 16) & 0x7ff;
status &= 0xffff;
dev_dbg(&adapter->pdev->dev, "%s - rx_data: status: %x\n",
__func__, status);
/* check the status */
if ((status & RXSR_VALID) && !(status & RXSR_ERROR)) {
struct sk_buff *skb = netdev_alloc_skb_ip_align(netdev, len);
dev_dbg(&adapter->pdev->dev, "%s, got package, len: %d\n",
__func__, len);
if (skb) {
u32 *data;
netdev->stats.rx_packets++;
netdev->stats.rx_bytes += len;
if (status & RXSR_MULTICAST)
netdev->stats.multicast++;
data = (u32 *)skb_put(skb, len);
ks8842_select_bank(adapter, 17);
while (len > 0) {
*data++ = ioread32(adapter->hw_addr +
REG_QMU_DATA_LO);
len -= sizeof(u32);
}
skb->protocol = eth_type_trans(skb, netdev);
netif_rx(skb);
} else
netdev->stats.rx_dropped++;
} else {
dev_dbg(&adapter->pdev->dev, "RX error, status: %x\n", status);
netdev->stats.rx_errors++;
if (status & RXSR_TOO_LONG)
netdev->stats.rx_length_errors++;
if (status & RXSR_CRC_ERROR)
netdev->stats.rx_crc_errors++;
if (status & RXSR_RUNT)
netdev->stats.rx_frame_errors++;
}
/* set high watermark to 3K */
ks8842_clear_bits(adapter, 0, 1 << 12, REG_QRFCR);
/* release the frame */
ks8842_write16(adapter, 17, 0x01, REG_RXQCR);
/* set high watermark to 2K */
ks8842_enable_bits(adapter, 0, 1 << 12, REG_QRFCR);
}
void ks8842_handle_rx(struct net_device *netdev, struct ks8842_adapter *adapter)
{
u16 rx_data = ks8842_read16(adapter, 16, REG_RXMIR) & 0x1fff;
dev_dbg(&adapter->pdev->dev, "%s Entry - rx_data: %d\n",
__func__, rx_data);
while (rx_data) {
ks8842_rx_frame(netdev, adapter);
rx_data = ks8842_read16(adapter, 16, REG_RXMIR) & 0x1fff;
}
}
void ks8842_handle_tx(struct net_device *netdev, struct ks8842_adapter *adapter)
{
u16 sr = ks8842_read16(adapter, 16, REG_TXSR);
dev_dbg(&adapter->pdev->dev, "%s - entry, sr: %x\n", __func__, sr);
netdev->stats.tx_packets++;
if (netif_queue_stopped(netdev))
netif_wake_queue(netdev);
}
void ks8842_handle_rx_overrun(struct net_device *netdev,
struct ks8842_adapter *adapter)
{
dev_dbg(&adapter->pdev->dev, "%s: entry\n", __func__);
netdev->stats.rx_errors++;
netdev->stats.rx_fifo_errors++;
}
void ks8842_tasklet(unsigned long arg)
{
struct net_device *netdev = (struct net_device *)arg;
struct ks8842_adapter *adapter = netdev_priv(netdev);
u16 isr;
unsigned long flags;
u16 entry_bank;
/* read current bank to be able to set it back */
spin_lock_irqsave(&adapter->lock, flags);
entry_bank = ioread16(adapter->hw_addr + REG_SELECT_BANK);
spin_unlock_irqrestore(&adapter->lock, flags);
isr = ks8842_read16(adapter, 18, REG_ISR);
dev_dbg(&adapter->pdev->dev, "%s - ISR: 0x%x\n", __func__, isr);
/* Ack */
ks8842_write16(adapter, 18, isr, REG_ISR);
if (!netif_running(netdev))
return;
if (isr & IRQ_LINK_CHANGE)
ks8842_update_link_status(netdev, adapter);
if (isr & (IRQ_RX | IRQ_RX_ERROR))
ks8842_handle_rx(netdev, adapter);
if (isr & IRQ_TX)
ks8842_handle_tx(netdev, adapter);
if (isr & IRQ_RX_OVERRUN)
ks8842_handle_rx_overrun(netdev, adapter);
if (isr & IRQ_TX_STOPPED) {
ks8842_disable_tx(adapter);
ks8842_enable_tx(adapter);
}
if (isr & IRQ_RX_STOPPED) {
ks8842_disable_rx(adapter);
ks8842_enable_rx(adapter);
}
/* re-enable interrupts, put back the bank selection register */
spin_lock_irqsave(&adapter->lock, flags);
ks8842_write16(adapter, 18, ENABLED_IRQS, REG_IER);
iowrite16(entry_bank, adapter->hw_addr + REG_SELECT_BANK);
spin_unlock_irqrestore(&adapter->lock, flags);
}
static irqreturn_t ks8842_irq(int irq, void *devid)
{
struct ks8842_adapter *adapter = devid;
u16 isr;
u16 entry_bank = ioread16(adapter->hw_addr + REG_SELECT_BANK);
irqreturn_t ret = IRQ_NONE;
isr = ks8842_read16(adapter, 18, REG_ISR);
dev_dbg(&adapter->pdev->dev, "%s - ISR: 0x%x\n", __func__, isr);
if (isr) {
/* disable IRQ */
ks8842_write16(adapter, 18, 0x00, REG_IER);
/* schedule tasklet */
tasklet_schedule(&adapter->tasklet);
ret = IRQ_HANDLED;
}
iowrite16(entry_bank, adapter->hw_addr + REG_SELECT_BANK);
return ret;
}
/* Netdevice operations */
static int ks8842_open(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
int err;
dev_dbg(&adapter->pdev->dev, "%s - entry\n", __func__);
/* reset the HW */
ks8842_reset_hw(adapter);
ks8842_update_link_status(netdev, adapter);
err = request_irq(adapter->irq, ks8842_irq, IRQF_SHARED, DRV_NAME,
adapter);
if (err) {
printk(KERN_ERR "Failed to request IRQ: %d: %d\n",
adapter->irq, err);
return err;
}
return 0;
}
static int ks8842_close(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
dev_dbg(&adapter->pdev->dev, "%s - entry\n", __func__);
/* free the irq */
free_irq(adapter->irq, adapter);
/* disable the switch */
ks8842_write16(adapter, 32, 0x0, REG_SW_ID_AND_ENABLE);
return 0;
}
static netdev_tx_t ks8842_xmit_frame(struct sk_buff *skb,
struct net_device *netdev)
{
int ret;
struct ks8842_adapter *adapter = netdev_priv(netdev);
dev_dbg(&adapter->pdev->dev, "%s: entry\n", __func__);
ret = ks8842_tx_frame(skb, netdev);
if (ks8842_tx_fifo_space(adapter) < netdev->mtu + 8)
netif_stop_queue(netdev);
return ret;
}
static int ks8842_set_mac(struct net_device *netdev, void *p)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
unsigned long flags;
struct sockaddr *addr = p;
char *mac = (u8 *)addr->sa_data;
int i;
dev_dbg(&adapter->pdev->dev, "%s: entry\n", __func__);
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, mac, netdev->addr_len);
spin_lock_irqsave(&adapter->lock, flags);
for (i = 0; i < ETH_ALEN; i++) {
ks8842_write8(adapter, 2, mac[ETH_ALEN - i - 1], REG_MARL + i);
ks8842_write8(adapter, 39, mac[ETH_ALEN - i - 1],
REG_MACAR1 + i);
}
spin_unlock_irqrestore(&adapter->lock, flags);
return 0;
}
static void ks8842_tx_timeout(struct net_device *netdev)
{
struct ks8842_adapter *adapter = netdev_priv(netdev);
unsigned long flags;
dev_dbg(&adapter->pdev->dev, "%s: entry\n", __func__);
spin_lock_irqsave(&adapter->lock, flags);
/* disable interrupts */
ks8842_write16(adapter, 18, 0, REG_IER);
ks8842_write16(adapter, 18, 0xFFFF, REG_ISR);
spin_unlock_irqrestore(&adapter->lock, flags);
ks8842_reset_hw(adapter);
ks8842_update_link_status(netdev, adapter);
}
static const struct net_device_ops ks8842_netdev_ops = {
.ndo_open = ks8842_open,
.ndo_stop = ks8842_close,
.ndo_start_xmit = ks8842_xmit_frame,
.ndo_set_mac_address = ks8842_set_mac,
.ndo_tx_timeout = ks8842_tx_timeout,
.ndo_validate_addr = eth_validate_addr
};
static const struct ethtool_ops ks8842_ethtool_ops = {
.get_link = ethtool_op_get_link,
};
static int __devinit ks8842_probe(struct platform_device *pdev)
{
int err = -ENOMEM;
struct resource *iomem;
struct net_device *netdev;
struct ks8842_adapter *adapter;
u16 id;
iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!request_mem_region(iomem->start, resource_size(iomem), DRV_NAME))
goto err_mem_region;
netdev = alloc_etherdev(sizeof(struct ks8842_adapter));
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
adapter = netdev_priv(netdev);
adapter->hw_addr = ioremap(iomem->start, resource_size(iomem));
if (!adapter->hw_addr)
goto err_ioremap;
adapter->irq = platform_get_irq(pdev, 0);
if (adapter->irq < 0) {
err = adapter->irq;
goto err_get_irq;
}
adapter->pdev = pdev;
tasklet_init(&adapter->tasklet, ks8842_tasklet, (unsigned long)netdev);
spin_lock_init(&adapter->lock);
netdev->netdev_ops = &ks8842_netdev_ops;
netdev->ethtool_ops = &ks8842_ethtool_ops;
ks8842_read_mac_addr(adapter, netdev->dev_addr);
id = ks8842_read16(adapter, 32, REG_SW_ID_AND_ENABLE);
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_register;
platform_set_drvdata(pdev, netdev);
printk(KERN_INFO DRV_NAME
" Found chip, family: 0x%x, id: 0x%x, rev: 0x%x\n",
(id >> 8) & 0xff, (id >> 4) & 0xf, (id >> 1) & 0x7);
return 0;
err_register:
err_get_irq:
iounmap(adapter->hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
release_mem_region(iomem->start, resource_size(iomem));
err_mem_region:
return err;
}
static int __devexit ks8842_remove(struct platform_device *pdev)
{
struct net_device *netdev = platform_get_drvdata(pdev);
struct ks8842_adapter *adapter = netdev_priv(netdev);
struct resource *iomem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
unregister_netdev(netdev);
tasklet_kill(&adapter->tasklet);
iounmap(adapter->hw_addr);
free_netdev(netdev);
release_mem_region(iomem->start, resource_size(iomem));
platform_set_drvdata(pdev, NULL);
return 0;
}
static struct platform_driver ks8842_platform_driver = {
.driver = {
.name = DRV_NAME,
.owner = THIS_MODULE,
},
.probe = ks8842_probe,
.remove = ks8842_remove,
};
static int __init ks8842_init(void)
{
return platform_driver_register(&ks8842_platform_driver);
}
static void __exit ks8842_exit(void)
{
platform_driver_unregister(&ks8842_platform_driver);
}
module_init(ks8842_init);
module_exit(ks8842_exit);
MODULE_DESCRIPTION("Timberdale KS8842 ethernet driver");
MODULE_AUTHOR("Mocean Laboratories <info@mocean-labs.com>");
MODULE_LICENSE("GPL v2");
MODULE_ALIAS("platform:ks8842");
| 25.403557 | 80 | 0.732041 |
85b888ecb16e39ce460945ec4c3098013ca682da | 4,568 | js | JavaScript | doc/html/search/all_69.js | akinaru/radiotap-java-decoder | 3d1b433ad722a632a4e4486c290c4510054b5be5 | [
"MIT"
] | 1 | 2016-05-22T15:25:15.000Z | 2016-05-22T15:25:15.000Z | doc/html/search/all_69.js | network-code/radiotap-decoder-java | 3d1b433ad722a632a4e4486c290c4510054b5be5 | [
"MIT"
] | null | null | null | doc/html/search/all_69.js | network-code/radiotap-decoder-java | 3d1b433ad722a632a4e4486c290c4510054b5be5 | [
"MIT"
] | 2 | 2016-03-15T02:34:28.000Z | 2016-08-30T03:39:55.000Z | var searchData=
[
['iradiotapchannel',['IRadiotapChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html',1,'fr::bmartel::protocol::radiotap::inter']]],
['iradiotapdata',['IRadiotapData',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_data.html',1,'fr::bmartel::protocol::radiotap::inter']]],
['iradiotapflags',['IRadiotapFlags',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_flags.html',1,'fr::bmartel::protocol::radiotap::inter']]],
['iradiotapframe',['IRadioTapFrame',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radio_tap_frame.html',1,'fr::bmartel::protocol::radiotap::inter']]],
['iscckchannel',['isCckChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#a637f25532cb6b7c37aa34f0bafa6d42a',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isCckChannel()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#ab8565e22b62b5c92aedce8cddb4a1235',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isCckChannel()']]],
['isdynamiccckofdmchannel',['isDynamicCckOfdmChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#a2d9158a1c19e6f6f5d520de13828ca26',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isDynamicCckOfdmChannel()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#a735d39087d57ce6f681f8ae6cb5354e1',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isDynamicCckOfdmChannel()']]],
['isgfskchannel',['isGfskChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#aaea894442b4fc4bdf1fd5e7953e0c96a',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isGfskChannel()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#a0470a1f0e1cffc6a2f1a9326090b0ca5',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isGfskChannel()']]],
['isofdmchannel',['isOfdmChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#a3a4f3bbfe38404f46b438b1906979881',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isOfdmChannel()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#ac4978636eb7b8c3c842b51e6d968f8a6',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isOfdmChannel()']]],
['isonlypassivescanallowed',['isOnlyPassiveScanAllowed',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#aa82458b0ab46acb0331e829c9b2592a2',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isOnlyPassiveScanAllowed()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#a1b9f30262b0995d549465a6e1643dff8',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isOnlyPassiveScanAllowed()']]],
['isplcpcrcerrors',['isPlcpCrcErrors',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_data.html#a6cf8201e0d34c5b4ad60a9dd63fcd192',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapData.isPlcpCrcErrors()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_data.html#ab47d81defd7e03e67ae776553ca88bbd',1,'fr.bmartel.protocol.radiotap.RadioTapData.isPlcpCrcErrors()']]],
['isspectrumchannel2ghz',['isSpectrumChannel2GHZ',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#ac007b55f5de89b6c0e81d40e50bd7c43',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isSpectrumChannel2GHZ()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#ad293c28ba1ade15bb753a5737b07d262',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isSpectrumChannel2GHZ()']]],
['isspectrumchannel5ghz',['isSpectrumChannel5GHZ',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#a963e7b66a7ef1e34e12adbfa202f8965',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isSpectrumChannel5GHZ()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#a631137519f9f7cc73ae1a1df41ca52e9',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isSpectrumChannel5GHZ()']]],
['isturbochannel',['isTurboChannel',['../interfacefr_1_1bmartel_1_1protocol_1_1radiotap_1_1inter_1_1_i_radiotap_channel.html#ad053158c2be972f09d0f573d0d8d5c44',1,'fr.bmartel.protocol.radiotap.inter.IRadiotapChannel.isTurboChannel()'],['../classfr_1_1bmartel_1_1protocol_1_1radiotap_1_1_radio_tap_channel.html#ac6286cd9fa92f49c929b4508520144e4',1,'fr.bmartel.protocol.radiotap.RadioTapChannel.isTurboChannel()']]]
];
| 268.705882 | 455 | 0.858363 |
369e3937b36326b61f5a049a8d499a60de0afad2 | 124 | swift | Swift | Tests/LinuxMain.swift | Beyova/SafeDecoder | 7fa3abbe551132f5ac65949a03c3e58b00344e11 | [
"MIT"
] | 3 | 2020-06-26T09:20:01.000Z | 2021-02-10T17:14:43.000Z | Tests/LinuxMain.swift | Beyova/SafeDecoder | 7fa3abbe551132f5ac65949a03c3e58b00344e11 | [
"MIT"
] | 1 | 2020-08-07T01:28:46.000Z | 2020-09-18T14:53:46.000Z | Tests/LinuxMain.swift | Beyova/SafeDecoder | 7fa3abbe551132f5ac65949a03c3e58b00344e11 | [
"MIT"
] | 1 | 2020-09-18T08:11:15.000Z | 2020-09-18T08:11:15.000Z | import XCTest
import SafeDecoderTests
var tests = [XCTestCaseEntry]()
tests += SafeDecoderTests.allTests()
XCTMain(tests)
| 15.5 | 36 | 0.790323 |
fd7c8d9c800fb1f8ba7ad4b9167bf6fb1f5bd47a | 1,246 | h | C | Feather/Feather.h | mpapp/Feather | 48d2e7da93a0ddb5af091e1094b967a40e2d9c1d | [
"Apache-2.0"
] | 12 | 2015-06-05T05:24:49.000Z | 2022-02-28T13:47:36.000Z | Feather/Feather.h | mpapp/Feather | 48d2e7da93a0ddb5af091e1094b967a40e2d9c1d | [
"Apache-2.0"
] | 3 | 2015-06-05T16:40:22.000Z | 2019-08-07T10:30:28.000Z | Feather/Feather.h | mpapp/Feather | 48d2e7da93a0ddb5af091e1094b967a40e2d9c1d | [
"Apache-2.0"
] | null | null | null | //
// Feather.h
// Feather
//
// Created by Matias Piipari on 29/03/2013.
// Copyright (c) 2013 Matias Piipari. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "Mixin.h"
#import "MPManagedObject.h"
#import "MPManagedObjectsController.h"
#import "MPManagedObject+Mixin.h"
#import "MPEmbeddedObject.h"
#import "MPTreeItem.h"
#import "MPTreeItemUtility.h"
#import "MPContributor.h"
#import "MPContributorsController.h"
#import "MPDatabase.h"
#import "MPDatabasePackageController.h"
#import "MPShoeboxPackageController.h"
#import "MPPlaceHolding.h"
#import "MPTreeItem.h"
#import "MPTitledProtocol.h"
#import "MPDatabasePackageBackedDocument.h"
#import "MPVirtualSection.h"
#import "MPObjectWrappingSection.h"
#import "NSNotificationCenter+MPManagedObjectExtensions.h"
#import "NSDictionary+MPManagedObjectExtensions.h"
#import "NSArray+MPManagedObjectExtensions.h"
#import "MPException.h"
#import "MPAssert.h"
#import "MPCountryList.h"
#import "MPFileObserver.h"
#import "MPBundlableMixin.h"
#import "MPCategorizableMixin.h"
#import "MPIndexableMixin.h"
#import "MPRESTFulResource.h"
#import "MPRootSection.h"
#import "MPSnapshot.h"
#import "MPSnapshotsController.h"
#import "CBLDocument+MPScriptingSupport.h"
| 21.118644 | 59 | 0.778491 |
c4391fd76c6a4bc51747666a45187c8f76ce672e | 4,569 | c | C | features/nanostack/sal-stack-nanostack/source/6LoWPAN/IPHC_Decode/lowpan_context.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 10 | 2019-01-11T08:18:31.000Z | 2022-03-24T01:37:14.000Z | features/nanostack/sal-stack-nanostack/source/6LoWPAN/IPHC_Decode/lowpan_context.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 18 | 2021-01-29T08:36:51.000Z | 2021-02-03T11:53:10.000Z | features/nanostack/sal-stack-nanostack/source/6LoWPAN/IPHC_Decode/lowpan_context.c | pattyolanterns/mbed-os | f05af9a870580a0a81688e4d8f94cf72ca17a4d6 | [
"Apache-2.0"
] | 8 | 2020-01-21T08:44:01.000Z | 2020-03-12T04:50:28.000Z | /*
* Copyright (c) 2015-2017, Arm Limited and affiliates.
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* \file lowpan_context.c
* \brief API for Add,Remove and update timeouts for lowpan context's
*
*/
#include "nsconfig.h"
#include "string.h"
#include "ns_types.h"
#include "ns_trace.h"
#include "nsdynmemLIB.h"
#include "ns_list.h"
#include "6LoWPAN/IPHC_Decode/lowpan_context.h"
#include "common_functions.h"
#define TRACE_GROUP "lCon"
lowpan_context_t *lowpan_contex_get_by_id(const lowpan_context_list_t *list, uint8_t id)
{
id &= LOWPAN_CONTEXT_CID_MASK;
/* Check to see we already have info for this context */
ns_list_foreach(lowpan_context_t, entry, list) {
if (entry->cid == id) {
return entry;
}
}
return NULL;
}
lowpan_context_t *lowpan_context_get_by_address(const lowpan_context_list_t *list, const uint8_t *ipv6Address)
{
/* Check to see we already have info for this context
* List is already listed that longest prefix are first at list
*/
ns_list_foreach(lowpan_context_t, entry, list) {
if (bitsequal(entry->prefix, ipv6Address, entry->length)) {
//Take always longest match prefix
return entry;
}
}
return NULL;
}
int_fast8_t lowpan_context_update(lowpan_context_list_t *list, uint8_t cid_flags, uint16_t lifetime, const uint8_t *prefix, uint_fast8_t len, bool stable)
{
uint8_t cid = cid_flags & LOWPAN_CONTEXT_CID_MASK;
lowpan_context_t *ctx = NULL;
/* Check to see we already have info for this context */
ctx = lowpan_contex_get_by_id(list, cid);
if (ctx) {
//Remove from the list - it will be reinserted below, sorted by its
//new context length. (Don't need "safe" foreach, as we break
//immediately after the removal).
ns_list_remove(list, ctx);
}
if (lifetime == 0) {
/* This is a removal request: delete any existing entry, then exit */
if (ctx) {
ns_dyn_mem_free(ctx);
}
return 0;
}
if (!ctx) {
ctx = ns_dyn_mem_alloc(sizeof(lowpan_context_t));
}
if (!ctx) {
tr_error("No heap for New 6LoWPAN Context");
return -2;
}
bool inserted = false;
ns_list_foreach(lowpan_context_t, entry, list) {
if (len >= entry->length) {
ns_list_add_before(list, entry, ctx);
inserted = true;
break;
}
}
if (!inserted) {
ns_list_add_to_end(list, ctx);
}
ctx->length = len;
ctx->cid = cid;
ctx->expiring = false;
ctx->stable = stable;
ctx->compression = cid_flags & LOWPAN_CONTEXT_C;
ctx->lifetime = (uint32_t) lifetime * 600u; /* minutes -> 100ms ticks */
// Do our own zero-padding, just in case sender has done something weird
memset(ctx->prefix, 0, sizeof ctx->prefix);
bitcopy(ctx->prefix, prefix, len);
return 0;
}
void lowpan_context_list_free(lowpan_context_list_t *list)
{
ns_list_foreach_safe(lowpan_context_t, cur, list) {
ns_list_remove(list, cur);
ns_dyn_mem_free(cur);
}
}
/* ticks is in 1/10s */
void lowpan_context_timer(lowpan_context_list_t *list, uint_fast16_t ticks)
{
ns_list_foreach_safe(lowpan_context_t, ctx, list) {
if (ctx->lifetime > ticks) {
ctx->lifetime -= ticks;
continue;
}
if (!ctx->expiring) {
/* Main lifetime has run out. Clear compression flag, and retain a
* bit longer (RFC 6775 5.4.3).
*/
ctx->compression = false;
ctx->expiring = true;
ctx->lifetime = 2 * 18000u; /* 2 * default Router Lifetime = 2 * 1800s = 1 hour */
tr_debug("Context timed out - compression disabled");
} else {
/* 1-hour expiration timer set above has run out */
ns_list_remove(list, ctx);
ns_dyn_mem_free(ctx);
tr_debug("Delete Expired context");
}
}
}
| 30.059211 | 154 | 0.637339 |
0a2548f22bc800329c8f497cc069b662208e0a34 | 252 | h | C | FitAnalytics-WebWidget/FitAnalyticsWebWidget.h | DigitalInnovation/FitAnalytics-WebWidget-iOS | 01d5b95366ea0990755798f4997b2467afb4093e | [
"MIT"
] | null | null | null | FitAnalytics-WebWidget/FitAnalyticsWebWidget.h | DigitalInnovation/FitAnalytics-WebWidget-iOS | 01d5b95366ea0990755798f4997b2467afb4093e | [
"MIT"
] | 3 | 2021-03-03T10:43:42.000Z | 2021-12-30T15:36:53.000Z | FitAnalytics-WebWidget/FitAnalyticsWebWidget.h | DigitalInnovation/FitAnalytics-WebWidget-iOS | 01d5b95366ea0990755798f4997b2467afb4093e | [
"MIT"
] | 2 | 2021-05-31T13:17:33.000Z | 2022-03-16T14:01:05.000Z |
#ifndef FITAWebwidget_Bridging_Header_h
#define FITAWebwidget_Bridging_Header_h
#import "FITAWebWidget.h"
#import "FITAWebWidgetHandler.h"
#import "FITAPurchaseReport.h"
#import "FITAPurchaseReporter.h"
#endif /* FITAWebwidget_Bridging_Header_h */
| 21 | 44 | 0.829365 |
ef9716b5cd45ac686a83f5b111962502247b014e | 134 | sql | SQL | microservicio/infraestructura/src/main/resources/sql/estado_agendamiento_historico/listar.sql | dagarciah/ceiba-adn-backend | aacd695656c6002ba4473673c31cc59b1d4fd5bd | [
"Apache-2.0"
] | null | null | null | microservicio/infraestructura/src/main/resources/sql/estado_agendamiento_historico/listar.sql | dagarciah/ceiba-adn-backend | aacd695656c6002ba4473673c31cc59b1d4fd5bd | [
"Apache-2.0"
] | null | null | null | microservicio/infraestructura/src/main/resources/sql/estado_agendamiento_historico/listar.sql | dagarciah/ceiba-adn-backend | aacd695656c6002ba4473673c31cc59b1d4fd5bd | [
"Apache-2.0"
] | null | null | null | select id, creacion as ultimo_cambio, nombre as estado
from estado_agendamiento_historico
where agendamiento_id = :agendamientoId | 44.666667 | 54 | 0.835821 |
c00729e0dc08e2b1e58467dafa0cf3dca4faa66a | 262 | sql | SQL | examples/WeatherApp/UIInit/Scripts/add-ts-stations.sql | muzammilkm/test-essentials | 0898b7cd99c67149947a24ef50cde40a6810732a | [
"Apache-2.0"
] | 1 | 2021-04-29T02:44:30.000Z | 2021-04-29T02:44:30.000Z | examples/WeatherApp/UIInit/Scripts/add-ts-stations.sql | muzammilkm/test-essentials | 0898b7cd99c67149947a24ef50cde40a6810732a | [
"Apache-2.0"
] | 7 | 2019-10-06T19:16:24.000Z | 2022-02-12T22:18:14.000Z | examples/WeatherApp/APITEST/Scripts/add-ts-stations.sql | muzammilkm/test-essentials | 0898b7cd99c67149947a24ef50cde40a6810732a | [
"Apache-2.0"
] | 2 | 2020-03-25T15:02:20.000Z | 2020-11-18T17:45:09.000Z | Insert Into Station VALUES('Hyderbad', 'Telangana')
Insert Into Station VALUES('Warangal', 'Telangana')
Insert Into Station VALUES('Karim Nagar', 'Telangana')
Insert Into Station VALUES('Nizambad', 'Telangana')
Insert Into Station VALUES('Khammam', 'Telangana')
| 43.666667 | 54 | 0.767176 |
d2c7a0833bedefa6b85ddc2e79f75d2c3d19e082 | 1,681 | php | PHP | resources/views/admin/users/create.blade.php | MarioGattolla/Project | e788ab7c389d346440a153ae52fa72f60321ddf5 | [
"MIT"
] | null | null | null | resources/views/admin/users/create.blade.php | MarioGattolla/Project | e788ab7c389d346440a153ae52fa72f60321ddf5 | [
"MIT"
] | null | null | null | resources/views/admin/users/create.blade.php | MarioGattolla/Project | e788ab7c389d346440a153ae52fa72f60321ddf5 | [
"MIT"
] | null | null | null | <x-app-layout>
<x-slot name="header">
<x-header>
{{ __('Create: ') }}
</x-header>
</x-slot>
<div class="py-12" name="body">
<x-body-div class="">
<x-div-box>
<x-div-box class="p-2 border-2 border-indigo-100 rounded">
<form method="POST" action="{{route('users.index')}}" class="bg-white p-5 ">
@csrf
<x-users.form.label class="" for="name" >Name</x-users.form.label>
<x-users.form.imput id="name" name="name"/>
<x-users.form.label for="surname" >Surname</x-users.form.label>
<x-users.form.imput id="surname" name="surname"/>
<x-users.form.label for="email">Email</x-users.form.label>
<x-users.form.imput id="email" name="email"/>
<x-users.form.label for="password">Password</x-users.form.label>
<x-users.form.imput id="password" name="password" />
<x-users.form.label for="roles">Choose a role : </x-users.form.label>
<select name="role" id="role">
@foreach(\App\Enums\Role::values() as $role_id => $role_name)
<option value="{{$role_name}}" {{($role_id == \App\Enums\Role::user->name ? 'selected' : '')}}>{{$role_name}}</option>
@endforeach
</select>
<x-users.form.submit type="submit" value="Submit" name="submit"/>
</form>
</x-div-box>
</x-div-box>
</x-body-div>
</div>
</x-app-layout>
| 40.02381 | 145 | 0.469363 |
0ba8bac551a05bebe5ab8cdbe7162fe74234100b | 1,019 | py | Python | 1306_Jump_Game_III.py | imguozr/LC-Solutions | 5e5e7098d2310c972314c9c9895aafd048047fe6 | [
"WTFPL"
] | null | null | null | 1306_Jump_Game_III.py | imguozr/LC-Solutions | 5e5e7098d2310c972314c9c9895aafd048047fe6 | [
"WTFPL"
] | null | null | null | 1306_Jump_Game_III.py | imguozr/LC-Solutions | 5e5e7098d2310c972314c9c9895aafd048047fe6 | [
"WTFPL"
] | null | null | null | from typing import List
class Solution:
"""
BFS
"""
def canReach_1(self, arr: List[int], start: int) -> bool:
"""
Recursively.
"""
seen = set()
def helper(pos):
if not 0 <= pos < len(arr) or pos in seen:
return False
if not arr[pos]:
return True
seen.add(pos)
return helper(pos + arr[pos]) or helper(pos - arr[pos])
return helper(start)
def canReach_2(self, arr: List[int], start: int) -> bool:
"""
Iteratively
"""
from collections import deque
queue, seen = deque([start]), {start}
while queue:
curr = queue.popleft()
if not arr[curr]:
return True
for nxt in [curr + arr[curr], curr - arr[curr]]:
if 0 <= nxt < len(arr) and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
return False
| 24.261905 | 67 | 0.459274 |
22fe6d1d781cd1241d897ad51eddcd5d88a9f4fb | 718 | asm | Assembly | oeis/137/A137243.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/137/A137243.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/137/A137243.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A137243: Number of coprime pairs (a,b) with -n <= a,b <= n.
; 8,16,32,48,80,96,144,176,224,256,336,368,464,512,576,640,768,816,960,1024,1120,1200,1376,1440,1600,1696,1840,1936,2160,2224,2464,2592,2752,2880,3072,3168,3456,3600,3792,3920,4240,4336,4672,4832,5024,5200,5568,5696,6032,6192,6448,6640,7056,7200,7520,7712,8000,8224,8688,8816,9296,9536,9824,10080,10464,10624,11152,11408,11760,11952,12512,12704,13280,13568,13888,14176,14656,14848,15472,15728,16160,16480,17136,17328,17840,18176,18624,18944,19648,19840,20416,20768,21248,21616,22192,22448,23216,23552
lpb $0
mov $2,$0
sub $0,1
seq $2,10 ; Euler totient function phi(n): count numbers <= n and prime to n.
add $1,$2
lpe
add $1,1
mul $1,8
mov $0,$1
| 55.230769 | 500 | 0.736769 |
76db48c63ca6c8fcf224f2d52c61667e65612fb6 | 484 | h | C | src/geometry_msgs/msg/pose_array.h | cndabai/micro_ros | 56676e56ceed07af4dedf1f92b8a4f4768691921 | [
"Apache-2.0"
] | 4 | 2021-07-29T03:01:04.000Z | 2021-12-21T09:12:39.000Z | src/geometry_msgs/msg/pose_array.h | cndabai/micro_ros | 56676e56ceed07af4dedf1f92b8a4f4768691921 | [
"Apache-2.0"
] | null | null | null | src/geometry_msgs/msg/pose_array.h | cndabai/micro_ros | 56676e56ceed07af4dedf1f92b8a4f4768691921 | [
"Apache-2.0"
] | 6 | 2021-06-14T15:55:19.000Z | 2021-11-19T01:18:10.000Z | // generated from rosidl_generator_c/resource/idl.h.em
// with input from geometry_msgs:msg/PoseArray.idl
// generated code does not contain a copyright notice
#ifndef GEOMETRY_MSGS__MSG__POSE_ARRAY_H_
#define GEOMETRY_MSGS__MSG__POSE_ARRAY_H_
#include "geometry_msgs/msg/detail/pose_array__struct.h"
#include "geometry_msgs/msg/detail/pose_array__functions.h"
#include "geometry_msgs/msg/detail/pose_array__type_support.h"
#endif // GEOMETRY_MSGS__MSG__POSE_ARRAY_H_
| 37.230769 | 63 | 0.822314 |
c1729ee67237cffe30e0c0859e1d2298ccf71436 | 3,818 | rs | Rust | query/src/sql/planner/binder/ddl/view.rs | b41sh/databend | 16e1cc5c5d26d14daef753df877a3597469d5812 | [
"Apache-2.0"
] | null | null | null | query/src/sql/planner/binder/ddl/view.rs | b41sh/databend | 16e1cc5c5d26d14daef753df877a3597469d5812 | [
"Apache-2.0"
] | 37 | 2021-10-12T03:11:10.000Z | 2022-01-24T02:46:39.000Z | query/src/sql/planner/binder/ddl/view.rs | b41sh/databend | 16e1cc5c5d26d14daef753df877a3597469d5812 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Datafuse Labs.
//
// 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.
use common_ast::ast::AlterViewStmt;
use common_ast::ast::CreateViewStmt;
use common_ast::ast::DropViewStmt;
use common_exception::Result;
use common_planners::AlterViewPlan;
use common_planners::CreateViewPlan;
use common_planners::DropViewPlan;
use crate::sql::binder::Binder;
use crate::sql::plans::Plan;
impl<'a> Binder {
pub(in crate::sql::planner::binder) async fn bind_create_view(
&mut self,
stmt: &CreateViewStmt<'a>,
) -> Result<Plan> {
let CreateViewStmt {
if_not_exists,
catalog,
database,
view,
query,
} = stmt;
let tenant = self.ctx.get_tenant();
let catalog = catalog
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_catalog());
let database = database
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_database());
let viewname = view.name.to_lowercase();
let subquery = format!("{}", query);
let plan = CreateViewPlan {
if_not_exists: *if_not_exists,
tenant,
catalog,
database,
viewname,
subquery,
};
Ok(Plan::CreateView(Box::new(plan)))
}
pub(in crate::sql::planner::binder) async fn bind_alter_view(
&mut self,
stmt: &AlterViewStmt<'a>,
) -> Result<Plan> {
let AlterViewStmt {
catalog,
database,
view,
query,
} = stmt;
let tenant = self.ctx.get_tenant();
let catalog = catalog
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_catalog());
let database = database
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_database());
let viewname = view.name.to_lowercase();
let subquery = format!("{}", query);
let plan = AlterViewPlan {
tenant,
catalog,
database,
viewname,
subquery,
};
Ok(Plan::AlterView(Box::new(plan)))
}
pub(in crate::sql::planner::binder) async fn bind_drop_view(
&mut self,
stmt: &DropViewStmt<'a>,
) -> Result<Plan> {
let DropViewStmt {
if_exists,
catalog,
database,
view,
} = stmt;
let tenant = self.ctx.get_tenant();
let catalog = catalog
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_catalog());
let database = database
.as_ref()
.map(|ident| ident.name.to_lowercase())
.unwrap_or_else(|| self.ctx.get_current_database());
let viewname = view.name.to_lowercase();
let plan = DropViewPlan {
if_exists: *if_exists,
tenant,
catalog,
database,
viewname,
};
Ok(Plan::DropView(Box::new(plan)))
}
}
| 30.062992 | 75 | 0.564694 |
fc4650b7f74bb8949be6cc38876d6f35398c5929 | 858 | css | CSS | static/assets/css/custom.css | Fudster/python-auth-website | 7960717a217f80557a1593888c3c117e2045232b | [
"MIT"
] | null | null | null | static/assets/css/custom.css | Fudster/python-auth-website | 7960717a217f80557a1593888c3c117e2045232b | [
"MIT"
] | null | null | null | static/assets/css/custom.css | Fudster/python-auth-website | 7960717a217f80557a1593888c3c117e2045232b | [
"MIT"
] | null | null | null | body {
padding-top: 90px;
}
.panel-login {
border-color: #ccc;
-webkit-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2);
-moz-box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2);
box-shadow: 0px 2px 3px 0px rgba(0,0,0,0.2);
}
.panel-login>.panel-heading {
color: #00415d;
background-color: #fff;
border-color: #fff;
text-align:center;
}
.panel-login>.panel-heading a{
text-decoration: none;
color: #666;
font-weight: bold;
font-size: 15px;
-webkit-transition: all 0.1s linear;
-moz-transition: all 0.1s linear;
transition: all 0.1s linear;
}
.panel-login>.panel-heading a.active{
color: #029f5b;
font-size: 18px;
}
.panel-login>.panel-heading hr{
margin-top: 10px;
margin-bottom: 0px;
clear: both;
border: 0;
height: 1px;
background-image: -webkit-linear-gradient(left,rgba(0, 0, 0, 0),rgba(0, 0, 0, 0.15),rgba(0, 0, 0, 0));
background-image: | 23.833333 | 103 | 0.675991 |
627cfda14b7196b6e1809be2c328e28ad17c7dec | 2,469 | kt | Kotlin | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/BaseLoginDialog.kt | outring/intellij-community | a0ce0176ecae0b7cfedf017aa917f860e3f7262f | [
"Apache-2.0"
] | null | null | null | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/BaseLoginDialog.kt | outring/intellij-community | a0ce0176ecae0b7cfedf017aa917f860e3f7262f | [
"Apache-2.0"
] | null | null | null | plugins/github/src/org/jetbrains/plugins/github/authentication/ui/BaseLoginDialog.kt | outring/intellij-community | a0ce0176ecae0b7cfedf017aa917f860e3f7262f | [
"Apache-2.0"
] | null | null | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.authentication.ui
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.openapi.util.Disposer
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.completionOnEdt
import org.jetbrains.plugins.github.util.errorOnEdt
import org.jetbrains.plugins.github.util.successOnEdt
import java.awt.Component
import javax.swing.JComponent
internal abstract class BaseLoginDialog(
project: Project?,
parent: Component?,
executorFactory: GithubApiRequestExecutor.Factory,
isAccountUnique: UniqueLoginPredicate
) : DialogWrapper(project, parent, false, IdeModalityType.PROJECT) {
protected val loginPanel = GithubLoginPanel(executorFactory, isAccountUnique)
private var _login = ""
private var _token = ""
val login: String get() = _login
val token: String get() = _token
val server: GithubServerPath get() = loginPanel.getServer()
fun setServer(path: String, editable: Boolean) = loginPanel.setServer(path, editable)
override fun getPreferredFocusedComponent(): JComponent? = loginPanel.getPreferredFocus()
override fun doValidateAll(): List<ValidationInfo> = loginPanel.doValidateAll()
override fun doOKAction() {
val modalityState = ModalityState.stateForComponent(loginPanel)
val emptyProgressIndicator = EmptyProgressIndicator(modalityState)
Disposer.register(disposable, Disposable { emptyProgressIndicator.cancel() })
startGettingToken()
loginPanel.acquireLoginAndToken(emptyProgressIndicator)
.completionOnEdt(modalityState) { finishGettingToken() }
.successOnEdt(modalityState) { (login, token) ->
_login = login
_token = token
close(OK_EXIT_CODE, true)
}
.errorOnEdt(modalityState) {
if (!GithubAsyncUtil.isCancellation(it)) startTrackingValidation()
}
}
protected open fun startGettingToken() = Unit
protected open fun finishGettingToken() = Unit
} | 39.190476 | 140 | 0.786553 |
39f4fdd360048e0db3fbcfd1ab2c0d3f97610c3d | 777 | java | Java | 1.JavaSyntax/task/task09/task0921/Solution.java | vladyslavkarpovych/JavaRushTasks | 614667a0f475e6f413b70682d15b3119139c49d6 | [
"MIT"
] | null | null | null | 1.JavaSyntax/task/task09/task0921/Solution.java | vladyslavkarpovych/JavaRushTasks | 614667a0f475e6f413b70682d15b3119139c49d6 | [
"MIT"
] | null | null | null | 1.JavaSyntax/task/task09/task0921/Solution.java | vladyslavkarpovych/JavaRushTasks | 614667a0f475e6f413b70682d15b3119139c49d6 | [
"MIT"
] | null | null | null | package com.javarush.task.task09.task0921;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.io.IOException;
/*
Метод в try..catch
*/
public class Solution {
public static void main(String[] args) {
readData();
}
public static void readData() {
List<Integer>list = new ArrayList<>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try{
while(true)
{
list.add(Integer.parseInt(reader.readLine()));
}
}
catch (NumberFormatException e)
{
for(int x : list){
System.out.println(x);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
| 20.447368 | 81 | 0.615187 |
8e9bbb3eb96e956a1e404d1df21355a42f365b65 | 99 | rb | Ruby | vendor/bundle/ruby/2.6.0/gems/autoprefixer-rails-9.6.5/lib/autoprefixer-rails/version.rb | Noah-Bytelion/web_app_clone | c5b898c49efa68d6cf94b3d1f9336e6a70a3a7ed | [
"Ruby",
"Beerware",
"MIT"
] | 1 | 2019-10-20T06:43:16.000Z | 2019-10-20T06:43:16.000Z | vendor/bundle/ruby/2.4.0/gems/autoprefixer-rails-9.6.5/lib/autoprefixer-rails/version.rb | morimichi1123/sample_app | 4c85ffa2b1ecc973283f9101061dd5b4569d473d | [
"RSA-MD"
] | 8 | 2019-11-08T02:11:37.000Z | 2022-02-26T05:45:32.000Z | vendor/bundle/ruby/2.4.0/gems/autoprefixer-rails-9.6.5/lib/autoprefixer-rails/version.rb | morimichi1123/sample_app | 4c85ffa2b1ecc973283f9101061dd5b4569d473d | [
"RSA-MD"
] | 1 | 2020-11-04T07:56:30.000Z | 2020-11-04T07:56:30.000Z | module AutoprefixerRails
VERSION = "9.6.5".freeze unless defined? AutoprefixerRails::VERSION
end
| 24.75 | 69 | 0.79798 |
48c354f1f8b35a74c0cd90e9b4f2c1b37f00d093 | 6,813 | h | C | Tools/MedusaExport/max9/include/maxnet_manager.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 32 | 2016-05-22T23:09:19.000Z | 2022-03-13T03:32:27.000Z | Tools/MedusaExport/max9/include/maxnet_manager.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 2 | 2016-05-30T19:45:58.000Z | 2018-01-24T22:29:51.000Z | Tools/MedusaExport/max9/include/maxnet_manager.h | CarysT/medusa | 8e79f7738534d8cf60577ec42ed86621533ac269 | [
"MIT"
] | 17 | 2016-05-27T11:01:42.000Z | 2022-03-13T03:32:30.000Z | //-----------------------------------------------------------------------------
// ---------------------------
// File ....: maxnet_manager.h
// ---------------------------
// Author...: Gus J Grubba
// Date ....: February 2000
// O.S. ....: Windows 2000
//
// History .: Feb, 15 2000 - Created
//
// 3D Studio Max Network Rendering Classes
//
//-----------------------------------------------------------------------------
#ifndef _MAXNET_MANAGER_H_
#define _MAXNET_MANAGER_H_
#include "maxheap.h"
//-------------------------------------------------------------------
//-- Global Server State
//
#define JOB_STATE_COMPLETE 0
#define JOB_STATE_WAITING 1
#define JOB_STATE_BUSY 2
#define JOB_STATE_ERROR 3
#define JOB_STATE_SUSPENDED 4
struct JobList: public MaxHeapOperators {
Job job;
HJOB hJob;
WORD state;
};
//-----------------------------------------------------------------------------
//-- MaxNetCallBack
//
// Note: Return as soon as possible from these calls. They block the API thread
// and nothing will happen until you return. If you have to do some processing,
// post a message to your own code and return immediately. Also note that these
// calls may come from a separate thread than your main process thread.
//
class MAXNETEXPORT MaxNetCallBack: public MaxHeapOperators {
public:
//-- Return "true" to cancel, "false" to continue
virtual bool Progress (int total, int current){return false;}
virtual void ProgressMsg (const TCHAR *message){;}
//-- Notifies the Manager Went Down
virtual void ManagerDown ( ){;}
//-- Notifies something has changed (new job, new server, new frame, etc.)
virtual void Update ( ){;}
//-- Notifies someone wants control of the queue; Send grant control msg to manager;
virtual void QueryControl ( TCHAR* station ){;}
//-- Notifies someone has taken control of the queue (Another QueueManager for instance)
virtual void QueueControl ( ){;}
};
//-----------------------------------------------------------------------------
//-- Manager Session Class
//
class MAXNETEXPORT MaxNetManager : public MaxNet {
public:
//-- Optional Call Back
virtual void SetCallBack ( MaxNetCallBack* cb )=0;
//-- Session
virtual bool FindManager ( short port, char* manager, char* netmask = "255.255.255.0" )=0;
virtual void Connect ( short port, char* manager = NULL, bool enable_callback = false )=0;
virtual void Disconnect ( )=0;
virtual void GetManagerInfo ( ManagerInfo* info )=0;
virtual bool KillManager ( )=0;
virtual void EnableUpdate ( bool enable = true )=0;
virtual bool QueryManagerControl ( bool wait )=0;
virtual bool TakeManagerControl ( )=0;
virtual void GrantManagerControl ( bool grant )=0;
virtual bool LockControl ( bool lock )=0;
virtual int GetClientCount ( )=0;
virtual int ListClients ( int start, int end, ClientInfo* clientList )=0;
//-- Jobs
virtual int GetJobCount ( )=0;
virtual int ListJobs ( int start, int end, JobList* jobList )=0;
virtual void GetJob ( HJOB hJob, JobList* jobList )=0;
virtual void GetJob ( HJOB hJob, Job* job )=0;
virtual void GetJobText ( HJOB hJob, CJobText& jobText, int count )=0;
virtual void SetJob ( HJOB hJob, Job* job, CJobText& jobText, bool reset )=0;
virtual int GetJobPriority ( HJOB hJob )=0;
virtual bool SetJobPriority ( HJOB hJob, int priority )=0;
virtual void SetJobOrder ( HJOB* hJob, DWORD count )=0;
virtual void DeleteJob ( HJOB hJob )=0;
virtual void SuspendJob ( HJOB hJob )=0;
virtual void ActivateJob ( HJOB hJob )=0;
virtual int GetJobServersCount ( HJOB hJob )=0;
virtual int GetJobServers ( int start, int end, HJOB hJob, JobServer* servers )=0;
virtual void GetJobServerStatus ( HJOB hJob, HSERVER hServer, TCHAR* status_text )=0;
virtual void SuspendJobServer ( HJOB hJob, HSERVER hServer )=0;
virtual void AssignJobServer ( HJOB hJob, HSERVER hServer )=0;
virtual int GetJobFramesCount ( HJOB hJob )=0;
virtual int GetJobFrames ( int start, int end, HJOB hJob, JOBFRAMES* frames )=0;
virtual int GetJobLog ( int start, int count, HJOB hJob, TCHAR** buffer )=0;
virtual bool CheckOutputVisibility ( TCHAR* output, TCHAR* err )=0;
virtual void AssignJob ( Job* job, TCHAR* archive, HSERVER* servers, CJobText& jobtext, DWORD blocksize = 0 )=0;
//-- Servers (Global)
virtual int GetServerCount ( )=0;
virtual int ListServers ( int start, int end, ServerList* serverList )=0;
virtual void GetServer ( HSERVER hServer, ServerList* serverList )=0;
virtual bool DeleteServer ( HSERVER hServer )=0;
virtual bool ResetServerIndex ( HSERVER hServer )=0;
virtual void GetWeekSchedule ( HSERVER hServer, WeekSchedule* schedule )=0;
virtual void SetWeekSchedule ( HSERVER hServer, WeekSchedule* schedule )=0;
virtual void GetServerNetStat ( HSERVER hServer, NetworkStatus* net_stat )=0;
virtual int GetServerGroupCount ( )=0;
virtual int GetServerGroupXCount ( int group )=0;
virtual int GetServerGroup ( int group, int count, HSERVER* grplist, TCHAR* name )=0;
virtual void NewServerGroup ( int count, HSERVER* grplist, TCHAR* name )=0;
virtual void DeleteServerGroup ( int group )=0;
};
//-----------------------------------------------------------------------------
//-- Interface Class
class MaxNetworkInterface: public MaxHeapOperators {
public:
virtual bool GetCurrentRenderer ( TCHAR* name, DWORD* id1, DWORD* id2)=0;
};
//This class will have more methods with each version.
//Version number indicates which methods are supported by a given implementation
class MaxNetworkInterface2 : public MaxNetworkInterface {
protected:
int version;
public:
MaxNetworkInterface2() { version = 6010; } //version 6.0.1.0
int GetMAXVersion() {return version;}
void SetMAXVersion(int version) {this->version = version;}
//-- version 6.0.1.0 - begin
virtual BOOL GetRendMultiThread() {return FALSE;}
virtual BOOL GetRendSimplifyAreaLights() {return FALSE;}
virtual BOOL GetUseAdvLight() {return FALSE;}
virtual BOOL GetCalcAdvLight() {return FALSE;}
//-- version 6.0.1.0 - end
//-- version 7.0.0.0 - begin
//-- ADD VERSION 7 METHODS HERE
//-- version 7.0.0.0 - end
};
//Uses interface version 1
MAXNETEXPORT void AssignJobEx(
MaxNetManager* mgr,
MaxNetworkInterface* maxIface,
Job* job,
TCHAR* archive,
HSERVER* servers,
CJobText& jobtext,
DWORD blocksize = 0 );
//Uses interface version 2
MAXNETEXPORT void AssignJobEx(
MaxNetManager* mgr,
MaxNetworkInterface2* maxIface,
Job* job,
TCHAR* archive,
HSERVER* servers,
CJobText& jobtext,
DWORD blocksize = 0 );
#endif
//-- EOF: maxnet_manager.h ----------------------------------------------------
| 36.433155 | 117 | 0.642448 |
2a75d91d9e330bfae907fa904a68e87c7993f722 | 1,612 | java | Java | ajah-spring-jdbc/src/main/java/com/ajah/spring/jdbc/err/QuerySyntaxException.java | efsavage/ajah | 8d6c0233061a185194c742c58b6b4158210dc23d | [
"Apache-2.0"
] | 2 | 2015-02-16T00:52:04.000Z | 2015-04-08T06:08:12.000Z | ajah-spring-jdbc/src/main/java/com/ajah/spring/jdbc/err/QuerySyntaxException.java | efsavage/ajah | 8d6c0233061a185194c742c58b6b4158210dc23d | [
"Apache-2.0"
] | null | null | null | ajah-spring-jdbc/src/main/java/com/ajah/spring/jdbc/err/QuerySyntaxException.java | efsavage/ajah | 8d6c0233061a185194c742c58b6b4158210dc23d | [
"Apache-2.0"
] | 2 | 2015-11-10T11:33:43.000Z | 2019-04-23T02:37:42.000Z | /*
* Copyright 2012 Eric F. Savage, code@efsavage.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.
*/
package com.ajah.spring.jdbc.err;
/**
* Happens when the syntax of a query is invalid and cannot be executed.
*
* @author <a href="http://efsavage.com">Eric F. Savage</a>, <a
* href="mailto:code@efsavage.com">code@efsavage.com</a>.
*
*/
public class QuerySyntaxException extends DataOperationException {
/**
* Error with a message.
*
* @param message
* The message describing the error.
*/
public QuerySyntaxException(final String message) {
super(message);
}
/**
* Wraps another exception, with a message.
*
* @param message
* The message to include with the error.
* @param cause
* The original exception.
*/
public QuerySyntaxException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Wraps another exception.
*
* @param cause
* The original exception.
*/
public QuerySyntaxException(final Throwable cause) {
super(cause);
}
}
| 26.866667 | 77 | 0.671836 |
add65866117aee567e7570be8cf6af40eca3accf | 161 | rs | Rust | ecms_inputvalidator/src/lib.rs | extensible-cms/ecms-rs | ed97272518816e96c0485c61405d5131a07c237c | [
"BSD-3-Clause"
] | null | null | null | ecms_inputvalidator/src/lib.rs | extensible-cms/ecms-rs | ed97272518816e96c0485c61405d5131a07c237c | [
"BSD-3-Clause"
] | 7 | 2021-12-07T16:21:15.000Z | 2022-02-15T08:50:41.000Z | ecms_inputvalidator/src/lib.rs | extensible-cms/ecms-rs | ed97272518816e96c0485c61405d5131a07c237c | [
"BSD-3-Clause"
] | null | null | null | #[macro_use]
extern crate derive_builder;
pub mod number;
pub mod text;
pub mod types;
#[cfg(test)]
mod test {
#[test]
fn test_valid_with_no_rules() {}
}
| 11.5 | 34 | 0.689441 |
e8dc347e2e8914b12566e7ce88c38a00dd0fd08d | 540 | py | Python | data_input/__init__.py | uabalabadubdub/ppcd-pec4 | b9b1dfae84fd987c4e9b4ea09c0197ef746b30d7 | [
"CC0-1.0"
] | null | null | null | data_input/__init__.py | uabalabadubdub/ppcd-pec4 | b9b1dfae84fd987c4e9b4ea09c0197ef746b30d7 | [
"CC0-1.0"
] | null | null | null | data_input/__init__.py | uabalabadubdub/ppcd-pec4 | b9b1dfae84fd987c4e9b4ea09c0197ef746b30d7 | [
"CC0-1.0"
] | null | null | null | from pathlib import Path
current_path = Path(".")
datafolder = current_path / "data"
imagefolder = current_path / "images"
if not datafolder.exists():
print(f"Creating {datafolder}/...")
datafolder.mkdir()
if not imagefolder.exists():
print(f"Creating {imagefolder}/...")
imagefolder.mkdir()
print("Scaning root folder...")
for child in current_path.iterdir():
if child.name == 'data.zip':
print(f"Moving {child.name} to data/...")
child.replace(datafolder / child.name)
print("Setup DONE!")
print()
| 24.545455 | 49 | 0.668519 |
742f2afb2a1d938c11c6acd1564aa2a03638962c | 442 | h | C | src/menus.h | usrshare/amptest | 4a88f37b91f1127025c7a8364c123a895de68579 | [
"MIT"
] | null | null | null | src/menus.h | usrshare/amptest | 4a88f37b91f1127025c7a8364c123a895de68579 | [
"MIT"
] | null | null | null | src/menus.h | usrshare/amptest | 4a88f37b91f1127025c7a8364c123a895de68579 | [
"MIT"
] | null | null | null | #ifndef RESOURCES_H
#define RESOURCES_H
#define IDI_APPICON 101
#define IDM_MAINMENU 201
#define IDM_P_OPEN 202
#define IDM_I_OPENFILE 1011
#define IDM_I_OPENLOC 1012
#define IDM_I_OPENURL 1013
#define IDM_I_FILEINFO 1021
#define IDM_I_ABOUT 1098
#define IDM_I_EXIT 1099
#define IDM_O_PREFS 1031
#define IDM_O_INPUTPREF 1032
#define IDM_O_OUTPUTPREF 1033
#define IDD_INPUTBOX 901
#define IDD_PROMPT 9011
#define IDD_INPUT 9012
#endif
| 16.37037 | 29 | 0.828054 |
eaf0e4bb1bca5603a0addcfbe28fbd5892788709 | 37 | sql | SQL | migration/sql-files/034-space-owner.sql | pranavgore09/fabric8-wit | d7de30ec49a14b7864f3ea6bab95568c30076a73 | [
"Apache-2.0"
] | 27 | 2016-07-13T20:09:38.000Z | 2017-05-24T06:46:35.000Z | migration/sql-files/034-space-owner.sql | pranavgore09/fabric8-wit | d7de30ec49a14b7864f3ea6bab95568c30076a73 | [
"Apache-2.0"
] | 1,364 | 2016-06-23T16:13:07.000Z | 2017-06-28T08:36:06.000Z | migration/sql-files/034-space-owner.sql | pranavgore09/fabric8-wit | d7de30ec49a14b7864f3ea6bab95568c30076a73 | [
"Apache-2.0"
] | 55 | 2017-07-03T06:57:20.000Z | 2022-03-05T10:46:32.000Z | ALTER TABLE spaces ADD owner_id uuid; | 37 | 37 | 0.837838 |
5c7df99463133d97db8253a21511ce1732459a59 | 1,147 | h | C | LEEThemeDemo/LEEThemeDemo/CommunityDemo/Utility/Tools/YYLabelExtend/YYLabel+Extend.h | ZPP506/LEETheme | 02416f7a20d6fa8274647e2cd575e06f39aefd63 | [
"MIT"
] | 823 | 2016-04-22T08:56:45.000Z | 2022-03-22T01:44:59.000Z | LEEThemeDemo/LEEThemeDemo/CommunityDemo/Utility/Tools/YYLabelExtend/YYLabel+Extend.h | ZPP506/LEETheme | 02416f7a20d6fa8274647e2cd575e06f39aefd63 | [
"MIT"
] | 28 | 2016-06-15T02:20:06.000Z | 2022-02-14T02:43:58.000Z | LEEThemeDemo/LEEThemeDemo/CommunityDemo/Utility/Tools/YYLabelExtend/YYLabel+Extend.h | ZPP506/LEETheme | 02416f7a20d6fa8274647e2cd575e06f39aefd63 | [
"MIT"
] | 144 | 2016-06-21T09:52:17.000Z | 2022-03-16T08:30:49.000Z | //
// YYLabel+Extend.h
// MierMilitaryNews
//
// Created by 李响 on 2016/12/7.
// Copyright © 2016年 miercn. All rights reserved.
//
#import "YYKit.h"
#define faceGreenNameArray @[@"[微笑]",@"[抠鼻]",@"[大笑]",@"[调皮]",@"[阴险]",@"[鼓掌]",@"[抓狂]",@"[大哭]",@"[傲慢]",@"[鄙视]",@"[奋斗]",@"[发怒]"]
#define faceWhiteNameArray @[@"[吐]",@"[得意]",@"[晕]",@"[咒骂]",@"[闭嘴]",@"[睡觉]",@"[疑问]",@"[流汗]",@"[委屈]",@"[龇牙]",@"[恭喜]",@"[撇嘴]"]
#define faceGreenImageArray @[@"cmbq_green_1",@"cmbq_green_2",@"cmbq_green_3",@"cmbq_green_4",@"cmbq_green_5",@"cmbq_green_6",@"cmbq_green_7",@"cmbq_green_8",@"cmbq_green_9",@"cmbq_green_10",@"cmbq_green_11",@"cmbq_green_12"]
#define faceWhiteImageArray @[@"cmbq_white_1",@"cmbq_white_2",@"cmbq_white_3",@"cmbq_white_4",@"cmbq_white_5",@"cmbq_white_6",@"cmbq_white_7",@"cmbq_white_8",@"cmbq_white_9",@"cmbq_white_10",@"cmbq_white_11",@"cmbq_white_12"]
@interface YYLabel (Extend)
/**
表情字典
@return 字典
*/
+ (NSDictionary *)faceMapper;
/**
设置文本布局 (YYLabel)
@param label YYLabel
@param maxRows 最大行数
@param maxSize 最大范围
*/
+ (void)configTextLayoutWithLabel:(YYLabel *)label MaxRows:(NSInteger)maxRows MaxSize:(CGSize)maxSize;
@end
| 31.861111 | 225 | 0.646905 |
92ca7ead5832e7368364616319baf135dd02f9ad | 16,804 | h | C | structs/RedBlack.h | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | structs/RedBlack.h | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | structs/RedBlack.h | hpbader42/KrisLibrary | 04efbe9e4ddd5dd8aacad7462143ae604c963791 | [
"BSD-3-Clause"
] | null | null | null | #ifndef REDBLACK_H
#define REDBLACK_H
#include <log4cxx/logger.h>
#include <KrisLibrary/Logger.h>
#include <iostream>
#include <assert.h>
#include <KrisLibrary/utils/cmp_func.h>
namespace RedBlack {
enum Color { Black, Red };
//defines the match type for the lookup function
enum Lookup { None, Equal,GTEQ,LTEQ,Less,Greater,Next,Prev};
template <class T>
struct WalkCallback {
enum Visit { PreOrder, PostOrder, EndOrder, Leaf };
virtual ~WalkCallback() {}
virtual void Visit(const T& key, Visit visit, int level) {}
};
template <class T>
class Node
{
public:
typedef Node<T> MyT;
Node();
Node(const T&);
~Node();
void detatch();
bool isValid() const;
int count_black();
void dumptree(std::ostream& out,int n);
MyT* successor() const; //Return a pointer to the smallest key greater than x
MyT* predecessor() const; //Return a pointer to the largest key less than x
void walk(WalkCallback<T>& callback,int level);
inline void setColor(Color c) { if(this==NULL) assert(c==Black); else color=c; }
inline Color getColor() const { if(this==NULL) return Black; return color; }
inline bool hasColor(Color c) const { return c==getColor(); }
MyT *left; /* Left down */
MyT *right; /* Right down */
MyT *up; /* Up */
T key;
private:
Color color;
};
template <class T,class Cmp=std::cmp_func<T> >
class Tree
{
public:
typedef Tree<T> MyT;
typedef Node<T> NodeT;
struct iterator
{
inline iterator() : curp(NULL) {}
inline iterator(NodeT* n) { curp=n; }
inline iterator(const iterator& i) : curp(i.curp) {}
inline operator const T* () const { assert(curp); return &curp->key; }
inline const T* operator->() const { assert(curp); return &curp->key; }
inline void operator++() { if(curp) curp=curp->successor(); }
inline void operator--() { if(curp) curp=curp->predecessor(); }
inline void operator++(int) { if(curp) curp=curp->successor(); }
inline void operator--(int) { if(curp) curp=curp->predecessor(); }
inline bool operator == (const iterator& i) const { return i.curp==curp; }
inline bool operator != (const iterator& i) const { return i.curp!=curp; }
inline operator bool() const { return curp!=NULL; }
inline bool operator !() const { return curp==NULL; }
inline bool end() const { return curp==NULL; }
NodeT* curp;
};
Tree();
~Tree();
bool checkValid() const;
inline bool empty() const { return root==NULL; }
void clear();
bool erase(const T&);
inline void erase(const iterator& x) { _erase(x.curp); }
inline iterator find(const T& key) const { return iterator(_find(key)); }
inline iterator insert(const T& key) { return iterator(_insert(key)); }
iterator lookup(Lookup type, const T&);
void walk(WalkCallback<T>& callback);
iterator begin() const;
inline iterator end() const { return iterator(); }
iterator front() const;
iterator back() const;
Cmp cmpFunc;
private:
NodeT* _insert(const T&);
NodeT* _find(const T&) const;
NodeT* _lookup(Lookup, const T&) const;
void _erase(NodeT* x);
void _erase_fix(NodeT* x,NodeT* p);
void _left_rotate(NodeT* x);
void _right_rotate(NodeT* x);
NodeT *root;
};
template <class T>
Node<T>::Node()
:left(NULL),right(NULL),up(NULL),color(Black)
{}
template <class T>
Node<T>::Node(const T& _key)
:left(NULL),right(NULL),up(NULL),key(_key),color(Black)
{}
template <class T>
Node<T>::~Node()
{
if(left) delete left;
if(right) delete right;
}
template <class T>
void Node<T>::detatch()
{
left=right=up=NULL;
}
template <class T>
Node<T>* Node<T>::successor() const
{
MyT *y;
const MyT *x;
if (right!=NULL)
{
/* If right is not NULL then go right one and
** then keep going left until we find a node with
** no left pointer.
*/
for (y=right; y->left!=NULL; y=y->left);
}
else
{
/* Go up the tree until we get to a node that is on the
** left of its parent (or the root) and then return the
** parent.
*/
y=up;
x=this;
while(y!=NULL && x==y->right)
{
x=y;
y=y->up;
}
}
return(y);
}
template <class T>
Node<T>* Node<T>::predecessor() const
{
MyT *y;
const MyT *x;
if (left!=NULL)
{
/* If left is not NULL then go left one and
** then keep going right until we find a node with
** no right pointer.
*/
for (y=left; y->right!=NULL; y=y->right);
}
else
{
/* Go up the tree until we get to a node that is on the
** right of its parent (or the root) and then return the
** parent.
*/
y=up;
x=this;
while(y!=NULL && x==y->left)
{
x=y;
y=y->up;
}
}
return(y);
}
template <class T>
void Node<T>::walk(WalkCallback<T>& callback,int level)
{
if (left==NULL && right==NULL)
{
callback(key, WalkCallback<T>::Leaf, level);
}
else
{
callback(key, WalkCallback<T>::Preorder, level);
if(left != NULL) left->walk(callback, level+1);
callback(key, WalkCallback<T>::Postorder, level);
if(right != NULL) right->walk(callback, level+1);
callback(key, WalkCallback<T>::Endorder, level);
}
}
template <class T>
bool Node<T>::isValid() const
{
if (hasColor(Red))
{
if (!left->hasColor(Black) && !right->hasColor(Black))
{
//LOG4CXX_ERROR(KrisLibrary::logger(), "Children of red node not both black, x="<< (unsigned long)this);
return false;
}
}
if (left)
{
if (left->up != this)
{
//LOG4CXX_ERROR(KrisLibrary::logger(), "x->left->up != x, x="<< (unsigned long)this);
return false;
}
if (!left->isValid())
return false;
}
if (right)
{
if (right->up != this)
{
//LOG4CXX_ERROR(KrisLibrary::logger(), "x->right->up != x, x="<< (unsigned long)this);
return false;
}
if (!right->isValid())
return false;
}
return true;
}
template <class T>
int Node<T>::count_black()
{
if (this==NULL)
return(1);
int nleft=left->count_black(), nright=right->count_black();
if (nleft==-1 || nright==-1)
return(-1);
if (nleft != nright)
{
//LOG4CXX_ERROR(KrisLibrary::logger(), "Black count not equal on left & right, x="<< (unsigned long)this);
return(-1);
}
if (hasColor(Black)) nleft++;
return(nleft);
}
template <class T>
void Node<T>::dumptree(std::ostream& out,int n)
{
if (this!=NULL) {
n++;
out<<"Tree: "<<n<<" "<<(unsigned int)this<<
": color="<<(hasColor(Black)? "Black" : "Red") <<", key="<<key<<
", left="<<(unsigned int)left<<", right="<<(unsigned int)right<<std::endl;
left->dumptree(out,n);
right->dumptree(out,n);
}
}
/*
** OK here we go, the balanced tree stuff. The algorithm is the
** fairly standard red/black taken from "Introduction to Algorithms"
** by Cormen, Leiserson & Rivest.
**
** Basically a red/black balanced tree has the following properties:-
** 1) Every node is either red or black
** 2) A leaf (NULL pointer) is considered black
** 3) If a node is red then its children are black
** 4) Every path from a node to a leaf contains the same no
** of black nodes
**
** 3) & 4) above guarantee that the longest path (alternating
** red and black nodes) is only twice as long as the shortest
** path (all black nodes). Thus the tree remains fairly balanced.
*/
template <class T,class Cmp>
Tree<T,Cmp>::Tree()
:root(NULL)
{}
template <class T,class Cmp>
Tree<T,Cmp>::~Tree()
{
clear();
}
template <class T,class Cmp>
void Tree<T,Cmp>::clear()
{
if (root) delete root;
root=NULL;
}
template <class T,class Cmp>
bool Tree<T,Cmp>::erase(const T& key)
{
NodeT *x=_find(key);
if (x) {
_erase(x);
return true;
}
return false;
}
template <class T,class Cmp>
void Tree<T,Cmp>::walk(WalkCallback<T>& callback)
{
_walk(root, callback);
}
template <class T,class Cmp>
typename Tree<T,Cmp>::iterator Tree<T,Cmp>::begin() const
{
NodeT* start=root;
//seek the minimum
if(start) while(start->left!=NULL) start=start->left;
return iterator(start);
}
template <class T,class Cmp>
typename Tree<T,Cmp>::iterator Tree<T,Cmp>::lookup(Lookup mode, const T& key)
{
if (!root) return iterator(NULL);
return iterator(_lookup(mode, key));
}
template <class T,class Cmp>
typename Tree<T,Cmp>::iterator Tree<T,Cmp>::front() const
{
NodeT* start=root;
//seek the minimum
if(start) while(start->left!=NULL) start=start->left;
return iterator(start);
}
template <class T,class Cmp>
typename Tree<T,Cmp>::iterator Tree<T,Cmp>::back() const
{
NodeT* start=root;
//seek the maximum
if(start) while(start->right!=NULL) start=start->right;
return iterator(start);
}
/* --------------------------------------------------------------------- */
/* Search for and if not found and insert is true, will add a new
** node in. Returns a pointer to the new node, or the node found
*/
template <class T,class Cmp>
Node<T>* Tree<T,Cmp>::_insert(const T& key)
{
NodeT *x,*y,*z;
int cmp;
y=NULL; /* points to the parent of x */
x=root;
/* walk x down the tree */
while(x!=NULL) {
y=x;
cmp=cmpFunc(key, x->key);
if (cmp<0)
x=x->left;
else if (cmp>0)
x=x->right;
else //found the key
return x;
}
z=new NodeT(key);
if (z==NULL) {
/* Whoops, no memory */
return(NULL);
}
z->up=y;
if (y==NULL)
{
root=z;
}
else
{
cmp=cmpFunc(z->key, y->key);
if (cmp<0)
y->left=z;
else
y->right=z;
}
z->left=NULL;
z->right=NULL;
/* color this new node red */
z->setColor(Red);
/* Having added a red node, we must now walk back up the tree balancing
** it, by a series of rotations and changing of colors
*/
x=z;
/* While we are not at the top and our parent node is red
** N.B. Since the root node is garanteed black, then we
** are also going to stop if we are the child of the root
*/
while(x != root && x->up->hasColor(Red))
{
/* if our parent is on the left side of our grandparent */
if (x->up == x->up->up->left)
{
/* get the right side of our grandparent (uncle?) */
y=x->up->up->right;
if (y->hasColor(Red))
{
/* make our parent black */
x->up->setColor(Black);
/* make our uncle black */
y->setColor(Black);
/* make our grandparent red */
x->up->up->setColor(Red);
/* now consider our grandparent */
x=x->up->up;
}
else
{
/* if we are on the right side of our parent */
if (x == x->up->right)
{
/* Move up to our parent */
x=x->up;
_left_rotate(x);
}
/* make our parent black */
x->up->setColor(Black);
/* make our grandparent red */
x->up->up->setColor(Red);
/* right rotate our grandparent */
_right_rotate(x->up->up);
}
}
else
{
/* everything here is the same as above, but
** exchanging left for right
*/
y=x->up->up->left;
if (y->hasColor(Red))
{
x->up->setColor(Black);
y->setColor(Black);
x->up->up->setColor(Red);
x=x->up->up;
}
else
{
if (x == x->up->left)
{
x=x->up;
_right_rotate(x);
}
x->up->setColor(Black);
x->up->up->setColor(Red);
_left_rotate(x->up->up);
}
}
}
/* Set the root node black */
root->setColor(Black);
return z;
}
template <class T,class Cmp>
Node<T>* Tree<T,Cmp>::_find(const T& key) const
{
NodeT* x=root;
int cmp;
/* walk x down the tree */
while(x!=NULL) {
cmp=cmpFunc(key, x->key);
if (cmp<0)
x=x->left;
else if (cmp>0)
x=x->right;
else
return x;
}
return NULL;
}
template <class T,class Cmp>
Node<T>* Tree<T,Cmp>::_lookup(Lookup mode, const T& key) const
{
NodeT *x,*y;
int cmp=0;
int found=0;
y=NULL; /* points to the parent of x */
x=root;
/* walk x down the tree */
while(x!=NULL && found==0)
{
y=x;
cmp=cmpFunc(key, x->key);
if (cmp<0)
x=x->left;
else if (cmp>0)
x=x->right;
else
found=1;
}
if (found && (mode==Equal || mode==GTEQ || mode==LTEQ))
return(x);
if (!found && (mode==Equal || mode==Next || mode==Prev))
return(NULL);
if (mode==GTEQ || (!found && mode==Greater))
{
if (cmp>0)
return(y->successor());
else
return(y);
}
if (mode==LTEQ || (!found && mode==Less))
{
if (cmp<0)
return(y->predecessor());
else
return(y);
}
if (mode==Next || (found && mode==Greater))
return(x->successor());
if (mode==Prev || (found && mode==Less))
return(x->predecessor());
/* Shouldn't get here unless mode=None */
return(NULL);
}
/*
** Rotate our tree thus:-
**
** X left_rotate(X)---> Y
** / \ / \
** A Y <--- right_rotate(Y) X C
** / \ / \
** B C A B
**
** N.B. This does not change the ordering.
**
** We assume that neither X or Y is NULL
*/
template <class T,class Cmp>
void Tree<T,Cmp>::_left_rotate(NodeT *x)
{
NodeT *y;
assert(x!=NULL);
assert(x->right!=NULL);
y=x->right; /* set Y */
/* Turn Y's left subtree into X's right subtree (move B)*/
x->right = y->left;
/* If B is not null, set it's parent to be X */
if (y->left != NULL)
y->left->up = x;
/* Set Y's parent to be what X's parent was */
y->up = x->up;
/* if X was the root */
if (x->up == NULL)
{
root=y;
}
else
{
/* Set X's parent's left or right pointer to be Y */
if (x == x->up->left)
{
x->up->left=y;
}
else
{
x->up->right=y;
}
}
/* Put X on Y's left */
y->left=x;
/* Set X's parent to be Y */
x->up = y;
}
template <class T,class Cmp>
void Tree<T,Cmp>::_right_rotate(NodeT *y)
{
NodeT *x;
assert(y!=NULL);
assert(y->left!=NULL);
x=y->left; /* set X */
/* Turn X's right subtree into Y's left subtree (move B) */
y->left = x->right;
/* If B is not null, set it's parent to be Y */
if (x->right != NULL)
x->right->up = y;
/* Set X's parent to be what Y's parent was */
x->up = y->up;
/* if Y was the root */
if (y->up == NULL)
{
root=x;
}
else
{
/* Set Y's parent's left or right pointer to be X */
if (y == y->up->left)
{
y->up->left=x;
}
else
{
y->up->right=x;
}
}
/* Put Y on X's right */
x->right=y;
/* Set Y's parent to be X */
y->up = x;
}
template <class T,class Cmp>
void Tree<T,Cmp>::_erase(NodeT *z)
{
NodeT *x, *y, *p;
if (z->left == NULL || z->right == NULL)
y=z;
else
y=z->successor();
p = y->up;
if (y->left != NULL)
x=y->left;
else
x=y->right;
if(x) x->up=p;
if (p == NULL)
{
root=x;
}
else
{
if (y==p->left)
p->left = x;
else
p->right = x;
}
y->detatch();
if (y->hasColor(Black))
_erase_fix(x,p);
/* DELETED: don't want to be changing iterators around on erase!
if(z!=y) {
z->key = y->key;
}
delete y;
*/
if(z!=y) {
//sit y into z's place
if(z->up) {
if(z->up->left == z) z->up->left=y;
else { assert(z->up->right == z); z->up->right=y; }
}
y->up=z->up;
if(z->left) z->left->up = y;
y->left=z->left;
if(z->right) z->right->up = y;
y->right=z->right;
y->setColor(z->getColor());
z->detatch();
}
delete z;
}
/* Restore the red-black properties after a delete */
template <class T,class Cmp>
void Tree<T,Cmp>::_erase_fix(NodeT *x,NodeT* p)
{
NodeT *w;
while (x!=root && x->hasColor(Black))
{
if (x==p->left)
{
w=p->right;
if (w->hasColor(Red))
{
w->setColor(Black);
p->setColor(Red);
_left_rotate(p);
w=p->right;
}
if (w->left->hasColor(Black) && w->right->hasColor(Black))
{
w->setColor(Red);
x=p;
p=x->up;
}
else
{
if (w->right->hasColor(Black))
{
w->left->setColor(Black);
w->setColor(Red);
_right_rotate(w);
w=p->right;
}
w->setColor(p->getColor());
p->setColor(Black);
w->right->setColor(Black);
_left_rotate(p);
x=root;
}
}
else
{
w=p->left;
if (w->hasColor(Red))
{
w->setColor(Black);
p->setColor(Red);
_right_rotate(p);
w=p->left;
}
if (w->right->hasColor(Black) && w->left->hasColor(Black))
{
w->setColor(Red);
x=p;
p=x->up;
}
else
{
if (w->left->hasColor(Black))
{
w->right->setColor(Black);
w->setColor(Red);
_left_rotate(w);
w=p->left;
}
w->setColor(p->getColor());
p->setColor(Black);
w->left->setColor(Black);
_right_rotate(p);
x=root;
}
}
}
x->setColor(Black);
}
template <class T,class Cmp>
bool Tree<T,Cmp>::checkValid() const
{
if (root->up!=NULL)
{
LOG4CXX_ERROR(KrisLibrary::logger(), "Root up pointer not NULL" <<"\n");
root->dumptree(std::cerr,0);
return false;
}
if (!root->isValid())
{
root->dumptree(std::cerr,0);
return false;
}
if (root->count_black()==-1)
{
LOG4CXX_ERROR(KrisLibrary::logger(),"Error in black count"<<"\n");
root->dumptree(std::cerr,0);
return false;
}
return true;
}
} //namespace RedBlack
#endif
| 19.630841 | 110 | 0.583909 |
133730203e24c201a3954a374d6bccf617ee7303 | 3,665 | h | C | dependencies-include/nxogre/include/NxOgreOgreSceneRenderer.h | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | 2 | 2016-06-23T21:20:19.000Z | 2020-03-25T15:01:07.000Z | dependencies-include/nxogre/include/NxOgreOgreSceneRenderer.h | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | null | null | null | dependencies-include/nxogre/include/NxOgreOgreSceneRenderer.h | bach74/Lisa | 6f79b909f734883cd05a0ccf8679199ae2e301cf | [
"MIT",
"Unlicense"
] | null | null | null | /** \file NxOgreOgreSceneRenderer.h
* \brief Header for the OgreSceneRenderer class.
* \version 1.0-21
*
* \licence NxOgre a wrapper for the PhysX physics library.
* Copyright (C) 2005-8 Robin Southern of NxOgre.org http://www.nxogre.org
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __NXOGRE_OGRE_SCENE_RENDERER_H__
#define __NXOGRE_OGRE_SCENE_RENDERER_H__
#include "NxOgrePrerequisites.h"
#include "NxOgreContainer.h"
#include "NxOgrePose.h"
#include "NxOgreNodeRenderable.h" // For: NodeRenderableParams
#include "NxOgreMeshRenderable.h" // For: MeshRenderableParams
#include "NxOgreSceneRenderer.h"
namespace NxOgre {
//////////////////////////////////////////////////////////////////////////////
/** \brief SceneRenderer for the Ogre3D Rendering Engine.
\note rendererUserData requires the name of the SceneManager
to use, in the format of "name", otherwise
the SceneRenderer will use the First SceneManager known.
*/
class NxPublicClass OgreSceneRenderer : public SceneRenderer {
friend class Scene;
public:
/** \brief SceneRenderer Constructor
\note rendererUserData string params combinations
name - Use this scenemanager with this name.
#first - Use the first scenemanager created.
#last - Use the last scenemanager created.
*/
OgreSceneRenderer(Scene* s, NxString rendererUserData);
virtual ~OgreSceneRenderer();
/** \brief Create a specific NodeRenderable to the SceneRender.
\note With the "Intent" param different sub-types of the NodeRenderable
can be made and used. For example with Wheels you may wish
to dynamically add the springs and steering to the graphics model.
With the intent param being "NxOgre-Wheel" you can know that and
use a "OgreWheelNodeRenderable", instead of "OgreNodeRenderable".
Of course this is a suggestion, the implementation if you choose
to use it, is purely up to you.
*/
virtual NodeRenderable* createNodeRenderable(NodeRenderableParams);
/** \brief Create a specific MeshRenderable to the MeshRenderable
*/
virtual MeshRenderable* createMeshRenderable(MeshRenderableParams, Resources::Mesh*);
// Nothing special with these, so we just use the defaults.
//void renderAll();
//void renderNxTransform(Actors*, Characters*); /** and so on */
//void renderSources();
Ogre::SceneManager* getSceneMgr() {
return mSceneMgr;
}
virtual void setCustom(const NxString& identifier, void* ptr);
virtual void setCustom(const NxString& identifier, const NxString& value);
void* getCustom(const NxString& identifier);
protected:
Ogre::SceneManager* mSceneMgr;
private:
};
//////////////////////////////////////////////////////////////////////////////
};
#endif
| 34.904762 | 88 | 0.66985 |
a1f64139b1ae1db4b98679afc8df523c676b15d2 | 12,832 | h | C | emulator/src/devices/cpu/h6280/h6280.h | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | 1 | 2022-01-15T21:38:38.000Z | 2022-01-15T21:38:38.000Z | emulator/src/devices/cpu/h6280/h6280.h | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | emulator/src/devices/cpu/h6280/h6280.h | rjw57/tiw-computer | 5ef1c79893165b8622d1114d81cd0cded58910f0 | [
"MIT"
] | null | null | null | // license:BSD-3-Clause
// copyright-holders:Bryan McPhail
/*****************************************************************************
h6280.h Portable Hu6280 emulator interface
Copyright Bryan McPhail, mish@tendril.co.uk
This source code is based (with permission!) on the 6502 emulator by
Juergen Buchmueller. It is released as part of the Mame emulator project.
Let me know if you intend to use this code in any other project.
******************************************************************************/
#ifndef MAME_CPU_H6280_H6280_H
#define MAME_CPU_H6280_H6280_H
#pragma once
#define H6280_LAZY_FLAGS 0
//**************************************************************************
// TYPE DEFINITIONS
//**************************************************************************
// ======================> h6280_device
// Used by core CPU interface
class h6280_device : public cpu_device
{
public:
// construction/destruction
h6280_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
// public interfaces
void set_irq_line(int irqline, int state);
DECLARE_READ8_MEMBER( irq_status_r );
DECLARE_WRITE8_MEMBER( irq_status_w );
DECLARE_READ8_MEMBER( timer_r );
DECLARE_WRITE8_MEMBER( timer_w );
/* functions for use by the PSG and joypad port only! */
uint8_t io_get_buffer();
void io_set_buffer(uint8_t);
protected:
// register enumeration
enum
{
H6280_PC = 1,
H6280_S,
H6280_P,
H6280_A,
H6280_X,
H6280_Y,
H6280_IRQ_MASK,
H6280_TIMER_STATE,
H6280_NMI_STATE,
H6280_IRQ1_STATE,
H6280_IRQ2_STATE,
H6280_IRQT_STATE,
H6280_M1,
H6280_M2,
H6280_M3,
H6280_M4,
H6280_M5,
H6280_M6,
H6280_M7,
H6280_M8
};
// device-level overrides
virtual void device_start() override;
virtual void device_reset() override;
virtual void device_stop() override;
// device_execute_interface overrides
virtual uint32_t execute_min_cycles() const override;
virtual uint32_t execute_max_cycles() const override;
virtual uint32_t execute_input_lines() const override;
virtual void execute_run() override;
virtual void execute_set_input(int inputnum, int state) override;
// device_memory_interface overrides
virtual space_config_vector memory_space_config() const override;
virtual bool memory_translate(int spacenum, int intention, offs_t &address) override;
// device_disasm_interface overrides
virtual std::unique_ptr<util::disasm_interface> create_disassembler() override;
// device_state_interface overrides
virtual void state_string_export(const device_state_entry &entry, std::string &str) const override;
// opcode accessors
uint8_t program_read8(offs_t addr);
void program_write8(offs_t addr, uint8_t data);
uint8_t program_read8z(offs_t addr);
void program_write8z(offs_t addr, uint8_t data);
uint16_t program_read16(offs_t addr);
uint16_t program_read16z(offs_t addr);
void push(uint8_t value);
void pull(uint8_t &value);
uint8_t read_opcode();
uint8_t read_opcode_arg();
#undef PROTOTYPES
#define PROTOTYPES(prefix) \
void prefix##_00(); void prefix##_01(); void prefix##_02(); void prefix##_03(); \
void prefix##_04(); void prefix##_05(); void prefix##_06(); void prefix##_07(); \
void prefix##_08(); void prefix##_09(); void prefix##_0a(); void prefix##_0b(); \
void prefix##_0c(); void prefix##_0d(); void prefix##_0e(); void prefix##_0f(); \
void prefix##_10(); void prefix##_11(); void prefix##_12(); void prefix##_13(); \
void prefix##_14(); void prefix##_15(); void prefix##_16(); void prefix##_17(); \
void prefix##_18(); void prefix##_19(); void prefix##_1a(); void prefix##_1b(); \
void prefix##_1c(); void prefix##_1d(); void prefix##_1e(); void prefix##_1f(); \
void prefix##_20(); void prefix##_21(); void prefix##_22(); void prefix##_23(); \
void prefix##_24(); void prefix##_25(); void prefix##_26(); void prefix##_27(); \
void prefix##_28(); void prefix##_29(); void prefix##_2a(); void prefix##_2b(); \
void prefix##_2c(); void prefix##_2d(); void prefix##_2e(); void prefix##_2f(); \
void prefix##_30(); void prefix##_31(); void prefix##_32(); void prefix##_33(); \
void prefix##_34(); void prefix##_35(); void prefix##_36(); void prefix##_37(); \
void prefix##_38(); void prefix##_39(); void prefix##_3a(); void prefix##_3b(); \
void prefix##_3c(); void prefix##_3d(); void prefix##_3e(); void prefix##_3f(); \
void prefix##_40(); void prefix##_41(); void prefix##_42(); void prefix##_43(); \
void prefix##_44(); void prefix##_45(); void prefix##_46(); void prefix##_47(); \
void prefix##_48(); void prefix##_49(); void prefix##_4a(); void prefix##_4b(); \
void prefix##_4c(); void prefix##_4d(); void prefix##_4e(); void prefix##_4f(); \
void prefix##_50(); void prefix##_51(); void prefix##_52(); void prefix##_53(); \
void prefix##_54(); void prefix##_55(); void prefix##_56(); void prefix##_57(); \
void prefix##_58(); void prefix##_59(); void prefix##_5a(); void prefix##_5b(); \
void prefix##_5c(); void prefix##_5d(); void prefix##_5e(); void prefix##_5f(); \
void prefix##_60(); void prefix##_61(); void prefix##_62(); void prefix##_63(); \
void prefix##_64(); void prefix##_65(); void prefix##_66(); void prefix##_67(); \
void prefix##_68(); void prefix##_69(); void prefix##_6a(); void prefix##_6b(); \
void prefix##_6c(); void prefix##_6d(); void prefix##_6e(); void prefix##_6f(); \
void prefix##_70(); void prefix##_71(); void prefix##_72(); void prefix##_73(); \
void prefix##_74(); void prefix##_75(); void prefix##_76(); void prefix##_77(); \
void prefix##_78(); void prefix##_79(); void prefix##_7a(); void prefix##_7b(); \
void prefix##_7c(); void prefix##_7d(); void prefix##_7e(); void prefix##_7f(); \
void prefix##_80(); void prefix##_81(); void prefix##_82(); void prefix##_83(); \
void prefix##_84(); void prefix##_85(); void prefix##_86(); void prefix##_87(); \
void prefix##_88(); void prefix##_89(); void prefix##_8a(); void prefix##_8b(); \
void prefix##_8c(); void prefix##_8d(); void prefix##_8e(); void prefix##_8f(); \
void prefix##_90(); void prefix##_91(); void prefix##_92(); void prefix##_93(); \
void prefix##_94(); void prefix##_95(); void prefix##_96(); void prefix##_97(); \
void prefix##_98(); void prefix##_99(); void prefix##_9a(); void prefix##_9b(); \
void prefix##_9c(); void prefix##_9d(); void prefix##_9e(); void prefix##_9f(); \
void prefix##_a0(); void prefix##_a1(); void prefix##_a2(); void prefix##_a3(); \
void prefix##_a4(); void prefix##_a5(); void prefix##_a6(); void prefix##_a7(); \
void prefix##_a8(); void prefix##_a9(); void prefix##_aa(); void prefix##_ab(); \
void prefix##_ac(); void prefix##_ad(); void prefix##_ae(); void prefix##_af(); \
void prefix##_b0(); void prefix##_b1(); void prefix##_b2(); void prefix##_b3(); \
void prefix##_b4(); void prefix##_b5(); void prefix##_b6(); void prefix##_b7(); \
void prefix##_b8(); void prefix##_b9(); void prefix##_ba(); void prefix##_bb(); \
void prefix##_bc(); void prefix##_bd(); void prefix##_be(); void prefix##_bf(); \
void prefix##_c0(); void prefix##_c1(); void prefix##_c2(); void prefix##_c3(); \
void prefix##_c4(); void prefix##_c5(); void prefix##_c6(); void prefix##_c7(); \
void prefix##_c8(); void prefix##_c9(); void prefix##_ca(); void prefix##_cb(); \
void prefix##_cc(); void prefix##_cd(); void prefix##_ce(); void prefix##_cf(); \
void prefix##_d0(); void prefix##_d1(); void prefix##_d2(); void prefix##_d3(); \
void prefix##_d4(); void prefix##_d5(); void prefix##_d6(); void prefix##_d7(); \
void prefix##_d8(); void prefix##_d9(); void prefix##_da(); void prefix##_db(); \
void prefix##_dc(); void prefix##_dd(); void prefix##_de(); void prefix##_df(); \
void prefix##_e0(); void prefix##_e1(); void prefix##_e2(); void prefix##_e3(); \
void prefix##_e4(); void prefix##_e5(); void prefix##_e6(); void prefix##_e7(); \
void prefix##_e8(); void prefix##_e9(); void prefix##_ea(); void prefix##_eb(); \
void prefix##_ec(); void prefix##_ed(); void prefix##_ee(); void prefix##_ef(); \
void prefix##_f0(); void prefix##_f1(); void prefix##_f2(); void prefix##_f3(); \
void prefix##_f4(); void prefix##_f5(); void prefix##_f6(); void prefix##_f7(); \
void prefix##_f8(); void prefix##_f9(); void prefix##_fa(); void prefix##_fb(); \
void prefix##_fc(); void prefix##_fd(); void prefix##_fe(); void prefix##_ff();
PROTOTYPES(op)
uint32_t translated(uint16_t addr);
void h6280_cycles(int cyc);
void set_nz(uint8_t n);
void clear_t();
void do_interrupt(uint16_t vector);
void check_and_take_irq_lines();
void check_irq_lines();
void check_vdc_vce_penalty(uint16_t addr);
void bra(bool cond);
void ea_zpg();
void ea_tflg();
void ea_zpx();
void ea_zpy();
void ea_abs();
void ea_abx();
void ea_aby();
void ea_zpi();
void ea_idx();
void ea_idy();
void ea_ind();
void ea_iax();
uint8_t rd_imm();
uint8_t rd_zpg();
uint8_t rd_zpx();
uint8_t rd_zpy();
uint8_t rd_abs();
uint8_t rd_abx();
uint8_t rd_aby();
uint8_t rd_zpi();
uint8_t rd_idx();
uint8_t rd_idy();
uint8_t rd_tfl();
void wr_zpg(uint8_t tmp);
void wr_zpx(uint8_t tmp);
void wr_zpy(uint8_t tmp);
void wr_abs(uint8_t tmp);
void wr_abx(uint8_t tmp);
void wr_aby(uint8_t tmp);
void wr_zpi(uint8_t tmp);
void wr_idx(uint8_t tmp);
void wr_idy(uint8_t tmp);
void wb_ea(uint8_t tmp);
void wb_eaz(uint8_t tmp);
void compose_p(uint8_t set, uint8_t clr);
void tadc(uint8_t tmp);
void adc(uint8_t tmp);
void tand(uint8_t tmp);
void and_a(uint8_t tmp);
uint8_t asl(uint8_t tmp);
void bbr(int bit, uint8_t tmp);
void bbs(int bit, uint8_t tmp);
void bcc();
void bcs();
void beq();
void bit(uint8_t tmp);
void bmi();
void bne();
void bpl();
void brk();
void bsr();
void bvc();
void bvs();
void cla();
void clc();
void cld();
void cli();
void clv();
void clx();
void cly();
void cmp(uint8_t tmp);
void cpx(uint8_t tmp);
void cpy(uint8_t tmp);
uint8_t dec(uint8_t tmp);
void dex();
void dey();
void teor(uint8_t tmp);
void eor(uint8_t tmp);
uint8_t inc(uint8_t tmp);
void inx();
void iny();
void jmp();
void jsr();
void lda(uint8_t tmp);
void ldx(uint8_t tmp);
void ldy(uint8_t tmp);
uint8_t lsr(uint8_t tmp);
void nop();
void tora(uint8_t tmp);
void ora(uint8_t tmp);
void pha();
void php();
void phx();
void phy();
void pla();
void plp();
void plx();
void ply();
uint8_t rmb(int bit, uint8_t tmp);
uint8_t rol(uint8_t tmp);
uint8_t ror(uint8_t tmp);
void rti();
void rts();
void sax();
void say();
void tsbc(uint8_t tmp);
void sbc(uint8_t tmp);
void sec();
void sed();
void sei();
void set();
uint8_t smb(int bit, uint8_t tmp);
void st0(uint8_t tmp);
void st1(uint8_t tmp);
void st2(uint8_t tmp);
uint8_t sta();
uint8_t stx();
uint8_t sty();
uint8_t stz();
void sxy();
void tai();
void tam(uint8_t tmp);
void tax();
void tay();
void tdd();
void tia();
void tii();
void tin();
void tma(uint8_t tmp);
uint8_t trb(uint8_t tmp);
uint8_t tsb(uint8_t tmp);
void tsx();
void tst(uint8_t imm, uint8_t tmp);
void txa();
void txs();
void tya();
void csh();
void csl();
enum
{
H6280_RESET_VEC = 0xfffe,
H6280_NMI_VEC = 0xfffc,
H6280_TIMER_VEC = 0xfffa,
H6280_IRQ1_VEC = 0xfff8,
H6280_IRQ2_VEC = 0xfff6 /* Aka BRK vector */
};
// address spaces
const address_space_config m_program_config;
const address_space_config m_io_config;
// CPU registers
PAIR m_ppc; /* previous program counter */
PAIR m_pc; /* program counter */
PAIR m_sp; /* stack pointer (always 100 - 1FF) */
PAIR m_zp; /* zero page address */
PAIR m_ea; /* effective address */
uint8_t m_a; /* Accumulator */
uint8_t m_x; /* X index register */
uint8_t m_y; /* Y index register */
uint8_t m_p; /* Processor status */
uint8_t m_mmr[8]; /* Hu6280 memory mapper registers */
uint8_t m_irq_mask; /* interrupt enable/disable */
uint8_t m_timer_status; /* timer status */
uint8_t m_timer_ack; /* timer acknowledge */
uint8_t m_clocks_per_cycle; /* 4 = low speed mode, 1 = high speed mode */
int32_t m_timer_value; /* timer interrupt */
int32_t m_timer_load; /* reload value */
uint8_t m_nmi_state;
uint8_t m_irq_state[3];
uint8_t m_irq_pending;
#if H6280_LAZY_FLAGS
int32_t m_nz; /* last value (lazy N and Z flag) */
#endif
uint8_t m_io_buffer; /* last value written to the PSG, timer, and interrupt pages */
// other internal states
int m_icount;
// address spaces
address_space *m_program;
address_space *m_io;
direct_read_data<0> *m_direct;
typedef void (h6280_device::*ophandler)();
ophandler m_opcode[256];
static const ophandler s_opcodetable[256];
};
DECLARE_DEVICE_TYPE(H6280, h6280_device)
#endif // MAME_CPU_H6280_H6280_H
| 34.494624 | 100 | 0.655938 |
bdae281ab6c4cc0b1f1376f241baa06cc6a92587 | 1,413 | rs | Rust | src/udp/packet.rs | akitsu-sanae/microps-rs | e217d2110e402a8a49909f08ea26725e2a9350cf | [
"MIT"
] | 4 | 2020-01-13T01:43:45.000Z | 2022-03-06T09:16:34.000Z | src/udp/packet.rs | akitsu-sanae/microps-rs | e217d2110e402a8a49909f08ea26725e2a9350cf | [
"MIT"
] | null | null | null | src/udp/packet.rs | akitsu-sanae/microps-rs | e217d2110e402a8a49909f08ea26725e2a9350cf | [
"MIT"
] | 1 | 2022-02-03T14:24:42.000Z | 2022-02-03T14:24:42.000Z | use crate::{buffer::Buffer, packet, util};
use std::error::Error;
pub struct Packet {
pub src_port: u16,
pub dst_port: u16,
pub sum: u16,
pub payload: Buffer,
}
const HEADER_LEN: usize = 8;
impl Packet {
pub fn dump(&self) {
eprintln!("src port: {}", self.src_port);
eprintln!("dst port: {}", self.dst_port);
eprintln!("sum: {}", self.sum);
eprintln!("{}", self.payload);
}
pub fn write_checksum(buf: &mut Buffer, sum: u16) {
buf.write_u16(4, sum);
}
}
impl packet::Packet<Packet> for Packet {
fn from_buffer(mut buf: Buffer) -> Result<Self, Box<dyn Error>> {
let src_port = buf.pop_u16("src port")?;
let dst_port = buf.pop_u16("dst port")?;
let len = buf.pop_u16("len")?;
let sum = buf.pop_u16("sum")?;
if len as usize != HEADER_LEN + buf.0.len() {
return Err(util::RuntimeError::new(format!("invalid len: {}", len)));
}
Ok(Packet {
src_port: src_port,
dst_port: dst_port,
sum: sum,
payload: buf,
})
}
fn to_buffer(self) -> Buffer {
let mut buf = Buffer::empty();
buf.push_u16(self.src_port);
buf.push_u16(self.dst_port);
buf.push_u16((HEADER_LEN + self.payload.0.len()) as u16);
buf.push_u16(self.sum);
buf.append(self.payload);
buf
}
}
| 26.660377 | 81 | 0.547771 |
12e8445adeb03251b19db355cb157886d44e7078 | 436 | html | HTML | po/apps/core/templates/admin/product_form.html | ministryofjustice/po | ff73ace136fc5f24e6b2ccc7b722ae0125d6f2b2 | [
"ADSL"
] | null | null | null | po/apps/core/templates/admin/product_form.html | ministryofjustice/po | ff73ace136fc5f24e6b2ccc7b722ae0125d6f2b2 | [
"ADSL"
] | 2 | 2016-01-21T15:31:41.000Z | 2016-01-21T15:34:40.000Z | po/apps/core/templates/admin/product_form.html | ministryofjustice/po | ff73ace136fc5f24e6b2ccc7b722ae0125d6f2b2 | [
"ADSL"
] | 2 | 2017-11-07T22:48:59.000Z | 2021-04-11T06:58:18.000Z | {% extends "admin/change_form.html" %}
{% block after_related_objects %}
{% load ctx %}
<div class="tabular">
<fieldset class="module">
<h2>Builds</h2>
<table>
<tr><th>Build</th><th>Created</th></tr>
{% for build in original.builds.all %}
<tr><td><a href="{% link_build build %}">{{ build.name }}</a></td><td>{{ build.created }}</td></tr>
{% endfor %}
</table>
</fieldset>
</div>
{% endblock %}
| 25.647059 | 105 | 0.559633 |
6d215d1f59f77ffe1818b024491ba29f9eb3c526 | 1,457 | swift | Swift | CarenetSDK/Classes/controllers/CNWarningViewController.swift | renatocarvalhan1/SDK | 25aa09d69daf998b8ffe9832871d1875fb9f3023 | [
"MIT"
] | null | null | null | CarenetSDK/Classes/controllers/CNWarningViewController.swift | renatocarvalhan1/SDK | 25aa09d69daf998b8ffe9832871d1875fb9f3023 | [
"MIT"
] | null | null | null | CarenetSDK/Classes/controllers/CNWarningViewController.swift | renatocarvalhan1/SDK | 25aa09d69daf998b8ffe9832871d1875fb9f3023 | [
"MIT"
] | null | null | null | //
// CNWarningViewController.swift
// CarenetSDK
//
// Created by Renato Carvalhan on 09/10/17.
//
import UIKit
import VisualEffectView
class CNWarningViewController: CNBaseViewController {
@IBOutlet var centerView: UIView!
@IBOutlet var blurView: VisualEffectView!{
didSet {
blurView.colorTint = UIColor.black
blurView.colorTintAlpha = 0.2
blurView.blurRadius = 5
blurView.scale = 1
}
}
var effect: UIVisualEffect!
override func viewDidLoad() {
super.viewDidLoad()
effect = blurView.effect
blurView.effect = nil
animateIn()
}
func animateIn(){
centerView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
centerView.alpha = 0
UIView.animate(withDuration: 0.4) {
self.blurView.effect = self.effect
self.centerView.alpha = 1
self.centerView.transform = CGAffineTransform.identity
}
}
func animateOut() {
UIView.animate(withDuration: 0.3, animations: {
self.blurView.effect = nil
self.centerView.transform = CGAffineTransform(scaleX: 1.3, y: 1.3)
self.centerView.alpha = 0
}) { (finished) in
self.dismiss(animated: false, completion: nil)
}
}
@IBAction func close(_ sender: Any) {
animateOut()
}
}
| 24.283333 | 78 | 0.575841 |
76ad6f9ca8d8afdc8ae8c40bab14b26d2400137e | 2,364 | swift | Swift | Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift | htaiwan/LeetCode-Solutions-in-Swift | df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2 | [
"MIT"
] | null | null | null | Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift | htaiwan/LeetCode-Solutions-in-Swift | df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2 | [
"MIT"
] | null | null | null | Solutions/SolutionsTests/Easy/Easy_088_Merge_Sorted_Array_Test.swift | htaiwan/LeetCode-Solutions-in-Swift | df8e24b17fbd2e791e56eb0c2d38f07b5c2880b2 | [
"MIT"
] | 1 | 2019-06-10T18:26:47.000Z | 2019-06-10T18:26:47.000Z | //
// Easy_088_Merge_Sorted_Array_Test.swift
// Solutions
//
// Created by Di Wu on 10/15/15.
// Copyright © 2015 diwu. All rights reserved.
//
import XCTest
class Easy_088_Merge_Sorted_Array_Test: XCTestCase {
private static let ProblemName: String = "Easy_088_Merge_Sorted_Array"
private static let TimeOutName = ProblemName + Default_Timeout_Suffix
private static let TimeOut = Default_Timeout_Value
func test_001() {
var input0: [Int] = [0]
let input1: [Int] = [1]
let m: Int = 0
let n: Int = 1
let expected: [Int] = [1]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
func test_002() {
var input0: [Int] = [1]
let input1: [Int] = [0]
let m: Int = 1
let n: Int = 0
let expected: [Int] = [1]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
func test_003() {
var input0: [Int] = [1, 3, 5, 7, 9, 0, 0, 0, 0, 0]
let input1: [Int] = [2, 4, 6, 8, 10]
let m: Int = 5
let n: Int = 5
let expected: [Int] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
asyncHelper(input0: &input0, input1: input1, m: m, n: n, expected: expected)
}
private func asyncHelper(input0: inout [Int], input1: [Int], m: Int, n: Int, expected: [Int]) {
weak var expectation: XCTestExpectation? = self.expectation(description: Easy_088_Merge_Sorted_Array_Test.TimeOutName)
var localInput0 = input0
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async(execute: { () -> Void in
Easy_088_Merge_Sorted_Array.merge(nums1: &localInput0, m: m, nums2: input1, n: n)
assertHelper(localInput0 == expected, problemName: Easy_088_Merge_Sorted_Array_Test.ProblemName, input: localInput0, resultValue: localInput0, expectedValue: expected)
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout: Easy_088_Merge_Sorted_Array_Test.TimeOut) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName: Easy_088_Merge_Sorted_Array_Test.ProblemName, input: localInput0, resultValue: Easy_088_Merge_Sorted_Array_Test.TimeOutName, expectedValue: expected)
}
}
}
}
| 42.214286 | 198 | 0.623942 |
e3eecd56cb84e8da5e90c81f8f82db2f666f8191 | 509 | go | Go | generateTypedTranslations_test.go | NSMutableString/typedLocalizable | 0a4fde3a21aa03fded6a634a61a16f20d65206b6 | [
"MIT"
] | null | null | null | generateTypedTranslations_test.go | NSMutableString/typedLocalizable | 0a4fde3a21aa03fded6a634a61a16f20d65206b6 | [
"MIT"
] | null | null | null | generateTypedTranslations_test.go | NSMutableString/typedLocalizable | 0a4fde3a21aa03fded6a634a61a16f20d65206b6 | [
"MIT"
] | null | null | null | package main
import "testing"
func TestExtractKeyFromLineGivenValidLineData(t *testing.T) {
line := "\"lorem\" = \"ipsum\";"
expectedKey := "lorem"
key, _ := extractKeyFromLine(line)
if key != expectedKey {
t.Errorf("Did not get expected result")
}
}
func TestExtractKeyFromLineGivenInvalidLineData(t *testing.T) {
line := "lorem ipsum"
expectedError := "Line did not match regex"
_, err := extractKeyFromLine(line)
if err.Error() != expectedError {
t.Errorf("Did not get expected error")
}
} | 24.238095 | 63 | 0.705305 |
2c7f8cb6fd98237a45bd69d3f50fb308aea1da91 | 394 | kt | Kotlin | app/src/main/java/com/szymongrochowiak/androidkotlinstarterpack/di/ApplicationModule.kt | SzymonGrochowiak/Android-Kotlin-Starter-Pack | 5a337fb35c0d51961983f7d5de9bb6e112494231 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/szymongrochowiak/androidkotlinstarterpack/di/ApplicationModule.kt | SzymonGrochowiak/Android-Kotlin-Starter-Pack | 5a337fb35c0d51961983f7d5de9bb6e112494231 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/szymongrochowiak/androidkotlinstarterpack/di/ApplicationModule.kt | SzymonGrochowiak/Android-Kotlin-Starter-Pack | 5a337fb35c0d51961983f7d5de9bb6e112494231 | [
"Apache-2.0"
] | null | null | null | package com.szymongrochowiak.androidkotlinstarterpack.di
import android.app.Application
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* @author Szymon Grochowiak
*/
@Module
class ApplicationModule(private val application: Application) {
@Provides
@Singleton
fun providesStarterPackApplication(): Application {
return application
}
}
| 19.7 | 63 | 0.769036 |
b984a2e41dd2c7ddb1ff6262c073a7f5f9a90668 | 130,615 | c | C | cilk5rts/cilk2c/transform.c | wustl-pctg/cracer | 033f0bc0cee9d77e00c8424b07350d5524f4cef8 | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | cilk5rts/cilk2c/transform.c | wustl-pctg/cracer | 033f0bc0cee9d77e00c8424b07350d5524f4cef8 | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | cilk5rts/cilk2c/transform.c | wustl-pctg/cracer | 033f0bc0cee9d77e00c8424b07350d5524f4cef8 | [
"MIT",
"Intel",
"BSD-3-Clause"
] | null | null | null | /* -*- c-indentation-style: "k&r"; c-basic-offset: 5 -*- */
/*************************************************************************
*
* C-to-C Translator
*
* Rob Miller
*
*************************************************************************/
/*
* Copyright (c) 1994-2003 Massachusetts Institute of Technology
* Copyright (c) 2000 Matteo Frigo
* Copyright (c) 2002 Bradley C. Kuszmaul
* Copyright (c) 2003 Jim Sukha
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
#include "ast.h"
FILE_IDENTITY(ident,
"$HeadURL: https://bradley.csail.mit.edu/svn/repos/cilk/5.4.3/cilk2c/transform.c $ $LastChangedBy: bradley $ $Rev: 2739 $ $Date: 2006-02-09 00:16:43 -0500 (Thu, 09 Feb 2006) $");
#include <ctype.h>
#include "astEquals.h"
#include "stringParse.h"
/* CilkPrefix: prefix for all preprocessor-generated symbols */
GLOBAL const char *CilkPrefix = "_cilk_";
PRIVATE char CilkNameBuf[100];
PRIVATE const char *ApplyPrefix(const char *root)
{
sprintf(CilkNameBuf, "%s%s", CilkPrefix, root);
return UniqueString(CilkNameBuf);
}
PRIVATE const char *MakeSyncName(int n)
{
sprintf(CilkNameBuf, "%s%s%d", CilkPrefix, "sync", n);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeFrameTypeName(const char *proc)
{
sprintf(CilkNameBuf, "%s%s_frame", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeSlowProcName(const char *proc)
{
sprintf(CilkNameBuf, "%s%s_slow", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeFastProcName(const char *proc)
{
/* sprintf(CilkNameBuf, "%s%s_fast", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
*/
return proc;
}
const char *MakeExportProcName(const char *proc)
{
sprintf(CilkNameBuf, "mt_%s", proc);
return (UniqueString(CilkNameBuf));
}
const char *MakeImportProcName(const char *proc)
{
sprintf(CilkNameBuf, "%s%s_import", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeScopeName(int n)
{
sprintf(CilkNameBuf, "scope%d", n);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeLinkName(const char *proc)
{
sprintf(CilkNameBuf, "%s%s_sig", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeTempName(void)
{
static int temp_count = 0;
sprintf(CilkNameBuf, "%s%s%d", CilkPrefix, "temp", temp_count++);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeSlowInletName(const char *proc, const char *inlet)
{
sprintf(CilkNameBuf, "%s%s_%s_inlet", CilkPrefix, proc, inlet);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeInnerSlowInletName(const char *proc, const char *inlet)
{
sprintf(CilkNameBuf, "%s%s_%s_inlet_slow", CilkPrefix, proc, inlet);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeInnerFastInletName(const char *proc, const char *inlet)
{
sprintf(CilkNameBuf, "%s%s_%s_inlet_fast", CilkPrefix, proc, inlet);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeImplicitInletName(const char *proc, int entry)
{
sprintf(CilkNameBuf, "%s%s_%d_inlet", CilkPrefix, proc, entry);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeInletArgsTypeName(const char *inlet)
{
sprintf(CilkNameBuf, "%s_args", inlet);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeProcArgsTypeName(const char *proc)
{
sprintf(CilkNameBuf, "%s%s_args", CilkPrefix, proc);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *MakeRemovedInletRemark(const char *name)
{
sprintf(CilkNameBuf,
"/*------- %s inlet as inner function was removed ------*/",
name);
return (UniqueString(CilkNameBuf));
}
PRIVATE const char *FrameName, *HeaderName, *DummyReturnName;
PRIVATE const char *WorkerStateTypeName, *WorkerStateName;
const char *ContextTypeName, *ContextName;
PRIVATE const char *ExportCilkStartName;
PRIVATE const char *EntryName, *ReceiverName, *SizeName, *FunctionName;
PRIVATE const char *SynchronizeName, *SynchedName;
PRIVATE const char *GenericFrameTypeName;
PRIVATE const char *InitFrameName, *PushFrameName;
PRIVATE const char *XPopFrameNoResultName;
PRIVATE const char *SetNoResultName;
PRIVATE const char *InletArgsName, *InletResultName;
PRIVATE const char *ProcArgsName, *ProcArgsName_v, *ProcResultName;
PRIVATE const char *AbortSlowName, *AbortStandaloneName;
PRIVATE const char *StartThreadFastName, *StartThreadSlowName,
*BeforeSpawnFastName, *BeforeSpawnSlowName, *AfterSpawnFastName,
*AfterSpawnSlowName, *AfterSyncSlowName, *BeforeSyncSlowName,
*AtSyncFastName, *BeforeReturnFastName, *BeforeReturnSlowName,
*BeforeReturnInletName, *AtThreadBoundarySlowName;
PRIVATE const char *OffsetofName;
/* nondeterminator support */
PRIVATE const char *AccessReadProfileName, *AccessWriteProfileName;
PRIVATE const char *AccessReadProfileName4, *AccessWriteProfileName4;
PRIVATE const char *AccessReadProfileName8, *AccessWriteProfileName8;
PRIVATE const char *AccessReadProfileAddrName, *AccessWriteProfileAddrName;
PRIVATE const char *AccessReadProfileAddrName4, *AccessWriteProfileAddrName4;
PRIVATE const char *AccessReadProfileAddrName8, *AccessWriteProfileAddrName8;
PRIVATE const char *SpawnVarProfileName;
PRIVATE void InitCilkTransform(void)
{
/* frame names */
FrameName = ApplyPrefix("frame");
/* parts-of-frame names */
HeaderName = UniqueString("header");
DummyReturnName = UniqueString("dummy_return");
/* parts of header */
EntryName = UniqueString("entry");
ReceiverName = UniqueString("receiver");
SizeName = UniqueString("size");
FunctionName = UniqueString("fn");
/* parts of RTS */
GenericFrameTypeName = UniqueString("CilkStackFrame");
WorkerStateTypeName = UniqueString("CilkWorkerState");
ContextTypeName = UniqueString("CilkContext");
/* name of worker state */
WorkerStateName = ApplyPrefix("ws");
/* name of Conetxt */
ContextName = UniqueString("context");
/* name of Cilk_start function - for export functions */
ExportCilkStartName = UniqueString("Cilk_start");
/* RTS macros */
InitFrameName = UniqueString("CILK2C_INIT_FRAME");
PushFrameName = UniqueString("CILK2C_PUSH_FRAME");
XPopFrameNoResultName = UniqueString("CILK2C_XPOP_FRAME_NORESULT");
SetNoResultName = UniqueString("CILK2C_SET_NORESULT");
SynchronizeName = UniqueString("CILK2C_SYNC");
SynchedName = UniqueString("CILK2C_SYNCHED");
AbortSlowName = UniqueString("CILK2C_ABORT_SLOW");
AbortStandaloneName = UniqueString("CILK2C_ABORT_STANDALONE");
StartThreadFastName = UniqueString("CILK2C_START_THREAD_FAST");
StartThreadSlowName = UniqueString("CILK2C_START_THREAD_SLOW");
BeforeSpawnFastName = UniqueString("CILK2C_BEFORE_SPAWN_FAST");
BeforeSpawnSlowName = UniqueString("CILK2C_BEFORE_SPAWN_SLOW");
AfterSpawnFastName = UniqueString("CILK2C_AFTER_SPAWN_FAST");
AfterSpawnSlowName = UniqueString("CILK2C_AFTER_SPAWN_SLOW");
AtSyncFastName = UniqueString("CILK2C_AT_SYNC_FAST");
AtThreadBoundarySlowName = UniqueString("CILK2C_AT_THREAD_BOUNDARY_SLOW");
BeforeSyncSlowName = UniqueString("CILK2C_BEFORE_SYNC_SLOW");
AfterSyncSlowName = UniqueString("CILK2C_AFTER_SYNC_SLOW");
BeforeReturnFastName = UniqueString("CILK2C_BEFORE_RETURN_FAST");
BeforeReturnSlowName = UniqueString("CILK2C_BEFORE_RETURN_SLOW");
BeforeReturnInletName = UniqueString("CILK2C_BEFORE_RETURN_INLET");
OffsetofName = UniqueString("CILK_OFFSETOF");
InletArgsName = ApplyPrefix("inletargs");
InletResultName = ApplyPrefix("inletresult");
/* cilk library support */
ProcArgsName = ApplyPrefix("procargs");
ProcArgsName_v = ApplyPrefix("procargs_v");
ProcResultName = ApplyPrefix("proc_result");
/* nondeterminator support */
AccessReadProfileName = "_READ_CHECK_VALUE";
AccessWriteProfileName = "_WRITE_CHECK_VALUE";
AccessReadProfileName4 = "_READ_CHECK_VALUE4";
AccessWriteProfileName4 = "_WRITE_CHECK_VALUE4";
AccessReadProfileName8 = "_READ_CHECK_VALUE8";
AccessWriteProfileName8 = "_WRITE_CHECK_VALUE8";
AccessReadProfileAddrName = "_READ_CHECK";
AccessWriteProfileAddrName = "_WRITE_CHECK";
AccessReadProfileAddrName4 = "_READ_CHECK4";
AccessWriteProfileAddrName4 = "_WRITE_CHECK4";
AccessReadProfileAddrName8 = "_READ_CHECK8";
AccessWriteProfileAddrName8 = "_WRITE_CHECK8";
SpawnVarProfileName = "_SPAWNVAR_CHECK";
}
/* true iff transforming a cilk procedure */
PRIVATE int in_procedure = 0;
PRIVATE int in_inlet = 0;
PRIVATE Node *curr_proc;
PRIVATE const char *proc_name;
PRIVATE Node *curr_inlet;
PRIVATE const char *inlet_name;
PRIVATE int sync_count;
typedef enum {
Fast, /* generating fast version of procedure */
Slow, /* generating slow version of procedure */
Link, /* generating linkage information */
InletProc, /* generating stand-alone inlet */
Export,
Import
} VersionType;
VersionType version;
List *link_initializers;
List *standalone_inlets;
/* for Nondeterminator */
typedef enum {
Read,
Write
} AccessProfileType;
#define CHECK_READ(node, type) \
AccessProfile(node, type, Read, 0, 0, 1, '=')
#define CHECK_READ_ADDR(node, type) \
AccessProfile(node, type, Read, 1, 0, 1, '=')
#define CHECK_READ_MULT(node, type, multiple) \
AccessProfile(node, type, Read, 0, 0, multiple, '=')
#define CHECK_READ_OPT(node, type) \
AccessProfile(node, type, Read, 0, 1, 1, '=')
#define CHECK_READ_OPT_MULT(node, type, multiple) \
AccessProfile(node, type, Read, 0, 1, multiple, '=')
#define CHECK_WRITE(node, type, operator) \
AccessProfile(node, type, Write, 0, 0, 1, operator)
#define CHECK_WRITE_ADDR(node, type, operator) \
AccessProfile(node, type, Write, 1, 0, 1, operator)
#define CHECK_WRITE_MULT(node, type, multiple, operator) \
AccessProfile(node, type, Write, 0, 0, multiple, operator)
#define CHECK_WRITE_OPT(node, type, operator) \
AccessProfile(node, type, Write, 0, 1, 1, operator)
#define CHECK_WRITE_OPT_MULT(node, type, multiple, operator) \
AccessProfile(node, type, Write, 0, 1, multiple, operator)
PRIVATE Node *AccessProfile(Node *node, Node *type,
AccessProfileType accesstype, int withaddress,
int opt, int multiple, int operator);
PRIVATE Node *SpawnVarProfile(Node *node, Node *type, OpType assign_op);
PRIVATE void AnalyzeFrameReadWrite(Node *node);
PRIVATE Node *MakeFrameType(const char *procname)
{
return MakeSdcl(EMPTY_TQ,
make_SUE(Sdcl, MakeFrameTypeName(procname), NULL));
}
PRIVATE Node *MakeGenericFrameType(void)
{
return MakeTdef(EMPTY_TQ, GenericFrameTypeName);
}
PRIVATE Node *MakeWorkerStateType(void)
{
return MakeTdef(EMPTY_TQ, WorkerStateTypeName);
}
Node *MakeContextType(void)
{
return MakeTdef(EMPTY_TQ, ContextTypeName);
}
PRIVATE Node *MakeInletArgsType(const char *inletname)
{
return MakeSdcl(EMPTY_TQ,
make_SUE(Sdcl, MakeInletArgsTypeName(inletname), NULL));
}
PRIVATE Node *MakeProcArgsType(const char *procname)
{
return MakeSdcl(EMPTY_TQ,
make_SUE(Sdcl, MakeProcArgsTypeName(procname), NULL));
}
PRIVATE Bool IsInletProc(Node *proc)
{
Node *decl, *fdcl;
assert(proc->typ == Proc);
decl = proc->u.proc.decl;
assert(decl->typ == Decl);
fdcl = decl->u.decl.type;
assert(fdcl->typ == Fdcl);
return tq_has_inlet(fdcl->u.fdcl.tq);
}
/*
* Figures out the type (Fdcl) of a spawned function. Pass the
* function expression (p->u.spawn.name) to this routine.
* Also works for inlet decls.
*/
PRIVATE Node *GetSpawnFdcl(Node *spawned_fn)
{
Node *type = NodeDataType(spawned_fn);
if (IsPtrToFunction(type))
type = type->u.ptr.type;
assert(type->typ == Fdcl);
return type;
}
PRIVATE Node *TransformNode(Node *node);
PRIVATE List *TransformList(List *list)
{
List *aptr;
for (aptr = list; aptr; aptr = Rest(aptr)) {
Node *item = FirstItem(aptr);
SetItem(aptr, TransformNode(item));
}
return list;
}
PRIVATE inline Node *TransformConst(Node *node, UNUSED(ConstNode *u))
{
USE_UNUSED(u);
return node;
}
PRIVATE inline Node *TransformIdOld(Node *node, idNode *u)
{
const char *scope;
if (!u->decl)
return node;
/* rename id to decl's name: implements static variable renaming */
assert(u->decl->typ == Decl);
u->text = u->decl->u.decl.name;
/* get scope name of id's declaration */
scope = u->decl->u.decl.scope;
switch (version) {
case Fast:
/* EBA
* adding case "kind == 1" to make formal args of outer cilk
* proc to be accessed through "frame" (inside inlets)
* also adding (kind == 3) for inlets
*/
if (((u->decl->u.decl.kind == 1) && (in_inlet == 1)) ||
((u->decl->u.decl.kind == 3) && (in_inlet == 1)) ||
(u->decl->u.decl.kind == 2) ||
(node->memorycheckedp && (u->decl->u.decl.kind == 3))) {
Node *result = MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(scope)),
MakeId(u->decl->u.decl.name));
SetCoords(result, node->coord, Subtree);
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(result, NodeCopy(u->decl->u.decl.type,
Subtree));
else
return (result);
}
break;
case Slow:
if (u->decl->u.decl.kind == 2 || u->decl->u.decl.kind == 3) {
Node *result = MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(scope)),
MakeId(u->decl->u.decl.name));
SetCoords(result, node->coord, Subtree);
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(result, NodeCopy(u->decl->u.decl.type,
Subtree));
else
return (result);
}
break;
case Link:
return MakeBinop('.',
MakeId(scope),
MakeId(u->decl->u.decl.name));
case InletProc:
if (u->decl->u.decl.kind == 4) {
Node *result = MakeBinop(ARROW,
MakeId(InletArgsName),
MakeId(u->decl->u.decl.name));
SetCoords(result, node->coord, Subtree);
return result;
} else if (u->decl->u.decl.kind != 0) {
Node *result = MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(scope)),
MakeId(u->decl->u.decl.name));
SetCoords(result, node->coord, Subtree);
return result;
}
break;
case Export:
case Import:
FAIL("I don't know what to think of Export or Import");
}
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(node, NodeCopy(u->decl->u.decl.type, Subtree));
else
return node;
}
PRIVATE inline Node *TransformId(Node *node, idNode *u)
{
const char *scope;
if (!u->decl)
return node;
/* rename id to decl's name: implements static variable renaming */
assert(u->decl->typ == Decl);
u->text = u->decl->u.decl.name;
/* get scope name of id's declaration */
scope = u->decl->u.decl.scope;
switch (version) {
case Fast:
/* EBA: Adding case kind=1 and kind=3, in inlets, to make variables accessed through frame. */
if ((u->decl->u.decl.kind == 2) ||
(in_inlet && (u->decl->u.decl.kind == 1)) ||
(in_inlet && (u->decl->u.decl.kind == 3)) ||
(node->memorycheckedp && (u->decl->u.decl.kind == 3))) {
Node *result = ParseWildcardStringNode("%d->%d.%d;",
FrameName,
scope,
u->decl->u.decl.name);
/* Node *result = MakeBinop('.', */
/* MakeBinop(ARROW, */
/* MakeId(FrameName), */
/* MakeId(scope)), */
/* MakeId(u->decl->u.decl.name)); */
SetCoords(result, node->coord, Subtree);
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(result, NodeCopy(u->decl->u.decl.type,
Subtree));
else
return (result);
}
break;
case Slow:
/* EBA: Adding case for kind=3, in inlets, to make variables accessed through frame. */
if (u->decl->u.decl.kind == 2 ||
u->decl->u.decl.kind == 3 ||
(in_inlet && u->decl->u.decl.kind == 1)) {
Node *result = ParseWildcardStringNode("%d->%d.%d;",
FrameName,
scope,
u->decl->u.decl.name);
/* Node *result = MakeBinop('.', */
/* MakeBinop(ARROW, */
/* MakeId(FrameName), */
/* MakeId(scope)), */
/* MakeId(u->decl->u.decl.name)); */
SetCoords(result, node->coord, Subtree);
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(result, NodeCopy(u->decl->u.decl.type,
Subtree));
else
return (result);
}
break;
case Link:
return ParseWildcardStringNode("%d.%d;",
scope,
u->decl->u.decl.name);
/* return MakeBinop('.', */
/* MakeId(scope), */
/* MakeId(u->decl->u.decl.name)); */
case InletProc:
if (u->decl->u.decl.kind == 4) {
Node *result = ParseWildcardStringNode("%d->%d;",
InletArgsName,
u->decl->u.decl.name);
/* Node *result = MakeBinop(ARROW, */
/* MakeId(InletArgsName), */
/* MakeId(u->decl->u.decl.name)); */
SetCoords(result, node->coord, Subtree);
return result;
} else if (u->decl->u.decl.kind != 0) {
Node *result = ParseWildcardStringNode("%d->%d.%d;",
FrameName,
scope,
u->decl->u.decl.name);
/* Node *result = MakeBinop('.', */
/* MakeBinop(ARROW, */
/* MakeId(FrameName), */
/* MakeId(scope)), */
/* MakeId(u->decl->u.decl.name)); */
SetCoords(result, node->coord, Subtree);
return result;
}
break;
case Export:
case Import:
FAIL("I don't know what to think of Export or Import");
}
if (node->memorycheckedp && node->nondeterminator)
return CHECK_READ(node, NodeCopy(u->decl->u.decl.type, Subtree));
else
return node;
}
PRIVATE inline Node *TransformBinop(Node *node, binopNode *u)
{
u->left = TransformNode(u->left);
if (IsAssignmentOp(u->op) && node->memorycheckedp &&
node->nondeterminator) {
/* This could be written as*/
/* if (PatternEqualsAST(u->left, "*%e1;"))*/
if ((u->left->typ == Unary) && (u->left->u.unary.op == INDIR)) {
u->left->u.unary.expr = CHECK_WRITE_ADDR(u->left->u.unary.expr,
NodeCopy(u->type, Subtree),
u->op);
}
else {
u->left = CHECK_WRITE_MULT(u->left,
NodeCopy(u->type, Subtree),
node->nondeterminator,
u->op);
}
}
u->right = TransformNode(u->right);
if (node->memorycheckedp && node->nondeterminator) {
/* Could be written as */
/*if (PatternEqualsAST(node, "%e1->%d1;") || PatternEqualsAST(node, "%e1.%d1;"))*/
if ((u->op == ARROW) || (u->op == '.'))
node = CHECK_READ(node, NodeCopy(u->type, Subtree));
else if (!IsAssignmentOp(u->op))
UNREACHABLE;
}
return node;
}
PRIVATE inline Node *TransformUnaryOriginal(Node *node, unaryNode *u)
{
if (version == Link && u->op == INDIR) {
/*
* transform *a to a[0], *(a+n) to a[n], *(n+a) to a[n],
* and *&x to x
*/
switch (u->expr->typ) {
case Id:
return (MakeArray(TransformNode(u->expr), List1(MakeConstSint(0))));
case Binop:
if (u->expr->u.binop.op == '+' ||
u->expr->u.binop.op == '-') {
if (NodeIsConstant(u->expr->u.binop.left))
return (MakeArray(TransformNode(u->expr->u.binop.right),
List1(TransformNode(u->expr->u.binop.left))));
if (NodeIsConstant(u->expr->u.binop.right))
return (MakeArray(TransformNode(u->expr->u.binop.left),
List1(TransformNode(u->expr->u.binop.right))));
}
break;
case Unary:
if (u->expr->u.unary.op == ADDRESS)
return (TransformNode(u->expr->u.unary.expr));
break;
default:
break;
}
}
u->expr = TransformNode(u->expr);
if (node->memorycheckedp && node->nondeterminator) {
if (IsIncDecOp(u->op)) {
u->expr = CHECK_WRITE(u->expr,NodeCopy(u->type, Subtree), u->op);
}
else if (u->op == INDIR)
u->expr = CHECK_READ_ADDR(u->expr, NodeCopy(u->type, Subtree));
else
UNREACHABLE;
}
return node;
}
PRIVATE inline Node *TransformUnaryLatest(Node *node, unaryNode *u)
{
WildcardTable *wcTable = NewWildcardTable(0);
if (version == Link && PatternMatch(node,
ParseWildcardStringNode("%e1;"),
wcTable)) {
/*
* transform *a to a[0], *(a+n) to a[n], *(n+a) to a[n],
* and *&x to x
*/
switch (u->expr->typ) {
case Id:
return ParseWildcardStringNode("%e[0];", TransformNode(u->expr));
/*return (MakeArray(TransformNode(u->expr), List1(MakeConstSint(0))));*/
case Binop:
if (PatternMatch(node, ParseWildcardStringNode("*(%e2 + %e3);"), wcTable)) {
Node *e2 = LookupWildcard(wcTable, "%e2");
Node *e3 = LookupWildcard(wcTable, "%e3");
printf("Executing this strange line here. \n");
if (NodeIsConstant(e2)) {
return ParseWildcardStringNode("%e3[%e2];",
TransformNode(e3),
TransformNode(e2));
}
if (NodeIsConstant(e3)) {
return ParseWildcardStringNode("%e2[%e3];",
TransformNode(e2),
TransformNode(e3));
}
}
if (u->expr->u.binop.op == '+' ||
u->expr->u.binop.op == '-') {
if (NodeIsConstant(u->expr->u.binop.left))
return ParseWildcardStringNode("%e[%e];",
TransformNode(u->expr->u.binop.right),
TransformNode(u->expr->u.binop.left));
/* return (MakeArray(TransformNode(u->expr->u.binop.right),*/
/* List1(TransformNode(u->expr->u.binop.left))));*/
if (NodeIsConstant(u->expr->u.binop.right))
return ParseWildcardStringNode("%e[%e];",
TransformNode(u->expr->u.binop.left),
TransformNode(u->expr->u.binop.right));
/* return (MakeArray(TransformNode(u->expr->u.binop.left),*/
/* List1(TransformNode(u->expr->u.binop.right))));*/
}
break;
case Unary:
if (u->expr->u.unary.op == ADDRESS)
return (TransformNode(u->expr->u.unary.expr));
break;
default:
break;
}
}
u->expr = TransformNode(u->expr);
if (node->memorycheckedp && node->nondeterminator) {
if (IsIncDecOp(u->op)) {
u->expr = CHECK_WRITE(u->expr,NodeCopy(u->type, Subtree), u->op);
}
else if (u->op == INDIR)
u->expr = CHECK_READ_ADDR(u->expr, NodeCopy(u->type, Subtree));
else
UNREACHABLE;
}
return node;
}
PRIVATE inline Node *TransformUnary(Node *node, unaryNode *u)
{
if (version == Link && u->op == INDIR) {
/*
* transform *a to a[0], *(a+n) to a[n], *(n+a) to a[n],
* and *&x to x
*/
switch (u->expr->typ) {
case Id:
return ParseWildcardStringNode("%e[0];", TransformNode(u->expr));
/*return (MakeArray(TransformNode(u->expr), List1(MakeConstSint(0))));*/
case Binop:
if (u->expr->u.binop.op == '+' ||
u->expr->u.binop.op == '-') {
if (NodeIsConstant(u->expr->u.binop.left))
return ParseWildcardStringNode("%e[%e];",
TransformNode(u->expr->u.binop.right),
TransformNode(u->expr->u.binop.left));
/* return (MakeArray(TransformNode(u->expr->u.binop.right),*/
/* List1(TransformNode(u->expr->u.binop.left))));*/
if (NodeIsConstant(u->expr->u.binop.right))
return ParseWildcardStringNode("%e[%e];",
TransformNode(u->expr->u.binop.left),
TransformNode(u->expr->u.binop.right));
/* return (MakeArray(TransformNode(u->expr->u.binop.left),*/
/* List1(TransformNode(u->expr->u.binop.right))));*/
}
break;
case Unary:
if (u->expr->u.unary.op == ADDRESS)
return (TransformNode(u->expr->u.unary.expr));
break;
default:
break;
}
}
u->expr = TransformNode(u->expr);
if (node->memorycheckedp && node->nondeterminator) {
if (IsIncDecOp(u->op)) {
u->expr = CHECK_WRITE(u->expr,NodeCopy(u->type, Subtree), u->op);
}
else if (u->op == INDIR)
u->expr = CHECK_READ_ADDR(u->expr, NodeCopy(u->type, Subtree));
else
UNREACHABLE;
}
return node;
}
PRIVATE inline Node *TransformCast(Node *node, castNode *u)
{
u->type = TransformNode(u->type);
u->expr = TransformNode(u->expr);
return node;
}
PRIVATE inline Node *TransformComma(Node *node, commaNode *u)
{
u->exprs = TransformList(u->exprs);
return node;
}
PRIVATE inline Node *TransformConstructor(Node *node, constructorNode *u)
{
u->type = TransformNode(u->type);
u->initializerlist = TransformNode(u->initializerlist);
return node;
}
PRIVATE inline Node *TransformTernary(Node *node, ternaryNode *u)
{
u->cond = TransformNode(u->cond);
u->true = TransformNode(u->true);
u->false = TransformNode(u->false);
return node;
}
PRIVATE inline Node *TransformArray(Node *node, arrayNode *u)
{
u->name = TransformNode(u->name);
u->dims = TransformList(u->dims);
if (node->memorycheckedp && node->nondeterminator)
node = CHECK_READ_MULT(node, NodeCopy(u->type, Subtree),
node->nondeterminator);
return node;
}
PRIVATE Node *name_strip(Node *node);
PRIVATE inline Node *TransformCall(Node *node, callNode *u)
{
u->name = TransformNode(u->name);
u->args = TransformList(u->args);
if ((u->name->typ == Id) &&
u->name->u.id.text &&
(strcmp(u->name->u.id.text, "_LOCK_CHECK") == 0))
u->args = List2(FirstItem(u->args),
name_strip(NodeCopy(FirstItem(u->args), Subtree)));
return node;
}
PRIVATE inline Node *TransformInitializer(Node *node, initializerNode *u)
{
u->exprs = TransformList(u->exprs);
return node;
}
PRIVATE inline Node *TransformImplicitCast(Node *node, implicitcastNode *u)
{
u->expr = TransformNode(u->expr);
return node;
}
/*************************************************************************/
/* */
/* Statement nodes */
/* */
/*************************************************************************/
PRIVATE inline Node *TransformLabel(Node *node, UNUSED(labelNode *u))
{
USE_UNUSED(u);
return node;
}
PRIVATE inline Node *TransformSwitch(Node *node, SwitchNode *u)
{
u->expr = TransformNode(u->expr);
u->stmt = TransformNode(u->stmt);
return node;
}
PRIVATE inline Node *TransformCase(Node *node, UNUSED(CaseNode *u))
{
return node;
}
PRIVATE inline Node *TransformDefault(Node *node, UNUSED(DefaultNode *u))
{
return node;
}
PRIVATE inline Node *TransformIf(Node *node, IfNode *u)
{
u->expr = TransformNode(u->expr);
u->stmt = TransformNode(u->stmt);
return node;
}
PRIVATE inline Node *TransformIfElse(Node *node, IfElseNode *u)
{
u->expr = TransformNode(u->expr);
u->true = TransformNode(u->true);
u->false = TransformNode(u->false);
return node;
}
PRIVATE inline Node *TransformWhile(Node *node, WhileNode *u)
{
u->expr = TransformNode(u->expr);
u->stmt = TransformNode(u->stmt);
return node;
}
PRIVATE inline Node *TransformDo(Node *node, DoNode *u)
{
u->expr = TransformNode(u->expr);
u->stmt = TransformNode(u->stmt);
return node;
}
PRIVATE inline Node *TransformFor(Node *node, ForNode *u)
{
u->cond = TransformNode(u->cond);
u->init = TransformNode(u->init);
u->next = TransformNode(u->next);
u->stmt = TransformNode(u->stmt);
if (OptimizeChecking && node->nondeterminator) {
List *profile;
List *rvar, *wvar, *rarr, *warr, *list;
ListMarker marker;
Node *item;
rvar = (List *) FirstItem(u->rwlist);
wvar = (List *) FirstItem(Rest(u->rwlist));
rarr = (List *) FirstItem(Rest(Rest(u->rwlist)));
warr = (List *) FirstItem(Rest(Rest(Rest(u->rwlist))));
profile = List1(node);
IterateList(&marker, rvar);
while (NextOnList(&marker, (GenericREF) &item)) {
profile = ConsItem(
CHECK_READ_OPT(item,
NodeCopy(item->u.id.decl->u.decl.type,
Subtree)),
profile);
}
IterateList(&marker, wvar);
while (NextOnList(&marker, (GenericREF) &item)) {
profile = ConsItem(
CHECK_WRITE_OPT(item,
NodeCopy(item->u.id.decl->u.decl.type,
Subtree),
'='),
profile);
}
IterateList(&marker, rarr);
while (NextOnList(&marker, (GenericREF) &list)) {
item = (Node *) FirstItem(list);
profile = ConsItem(
CHECK_READ_OPT_MULT(item,
NodeCopy(item->u.array.type,
Subtree),
((Node *) FirstItem(Rest(list)))->u.Const.value.i),
profile);
}
IterateList(&marker, warr);
while (NextOnList(&marker, (GenericREF) &list)) {
item = (Node *) FirstItem(list);
profile = ConsItem(
CHECK_WRITE_OPT_MULT(item,
NodeCopy(item->u.array.type,
Subtree),
((Node *) FirstItem(Rest(list)))->u.Const.value.i,
'='),
profile);
}
return MakeBlock(NULL, NULL, profile);
}
else
return node;
}
PRIVATE inline Node *TransformGoto(Node *node, UNUSED(GotoNode *u))
{
return node;
}
PRIVATE inline Node *TransformContinue(Node *node, UNUSED(ContinueNode *u))
{
return node;
}
PRIVATE inline Node *TransformBreak(Node *node, UNUSED(BreakNode *u))
{
return node;
}
PRIVATE inline Node *TransformReturn(Node *node, ReturnNode *u)
{
Node *result;
List *statements = NULL;
List *decls = NULL;
if (!in_procedure)
return node;
if (u->needs_sync) {
result = MakeBlockCoord(NULL,
NULL,
List2(MakeSyncCoord(node->coord),
MakeReturnCoord(u->expr, node->coord)),
node->coord,
UnknownCoord);
/* copy over analysis results from return to sync node */
((Node *) FirstItem(result->u.Block.stmts))->analysis.livevars = u->livevars;
((Node *) FirstItem(result->u.Block.stmts))->analysis.dirtyvars = u->dirtyvars;
return TransformNode(result);
}
u->expr = TransformNode(u->expr);
/* I'm not sure if this condition is right... -KHR */
if (in_inlet && (version == Fast || version == Slow))
return node;
else if (version == Fast) {
/* return x ==> { T _tmp = x; _BEFORE_RETURN_FAST(); return _tmp; } */
/* return ==> { _BEFORE_RETURN_FAST(); return; } */
/* if u->needs_sync == 1 then no need to create temparary value
* as it is already done in AnalyzeReturnExpressions. -fengmd */
if (u->expr && (!(u->needs_sync))) {
const char *tmp = MakeTempName();
Node *returntype = curr_proc->u.proc.decl->u.decl.type->u.fdcl.returns;
decls = ParseWildcardString("%t %d = %e;",
NodeCopy(returntype, Subtree),
tmp,
u->expr);
/* Node *decl = MakeDecl(tmp, */
/* EMPTY_TQ, */
/* NodeCopy(returntype, Subtree), */
/* u->expr, */
/* NULL); */
/* decls = List1(decl); */
statements = ParseWildcardString("%d(); %e;",
BeforeReturnFastName,
MakeReturn(MakeId(tmp)));
/* statements = List2(MakeCall(MakeId(BeforeReturnFastName), NULL), */
/* MakeReturn(MakeId(tmp))); */
} else
statements = ParseWildcardString("%d(); %e;",
BeforeReturnFastName,
node);
/* statements = List2(MakeCall(MakeId(BeforeReturnFastName), NULL), */
/* node); */
} else if (version == Slow) {
/* return x ==> {_SET_RESULT(x); _SET_VALID; return;} */
/* return ==> {_SET_VALID; return;} */
if (u->expr) {
Node *returntype = curr_proc->u.proc.decl->u.decl.type->u.fdcl.returns;
statements = ParseWildcardString("{%t __tmp = %e; Cilk_set_result(_cilk_ws, &__tmp, sizeof(__tmp)); } %d();",
NodeCopy(returntype, Subtree),
u->expr,
BeforeReturnSlowName);
}
/* statements = List1(MakeCall(MakeId(SetResultName), */
/* List1(u->expr))); */
else
statements = ParseWildcardString("%d(); %d();",
SetNoResultName,
BeforeReturnSlowName);
/* statements = List1(MakeCall(MakeId(SetNoResultName), NULL));*/
/* statements = AppendItem(statements,*/
/* MakeCall(MakeId(BeforeReturnSlowName), NULL));*/
statements = AppendItem(statements, MakeReturn(NULL));
} else if (version == InletProc) {
/* return x ==> {*_inletresult = x; return;} */
/* return ==> return */
if (!u->expr)
return ParseWildcardStringNode("{%d(); %e;}", BeforeReturnInletName, node);
/* return MakeBlock(NULL, NULL, */
/* List2(MakeCall(MakeId(BeforeReturnInletName), */
/* NULL), */
/* node)); */
statements = ParseWildcardString("*%d = %e; %d(); %e;",
InletResultName,
u->expr,
BeforeReturnInletName,
MakeReturn(NULL));
/* statements = List3(MakeBinop('=', */
/* MakeUnary('*', */
/* MakeId(InletResultName)), */
/* u->expr), */
/* MakeCall(MakeId(BeforeReturnInletName), NULL), */
/* MakeReturn(NULL)); */
} else
FAIL("bad version in TransformReturn");
result = MakeBlock(NULL, decls, statements);
SetCoords(result, node->coord, Subtree);
return result;
}
#if 0
PRIVATE inline Node *TransformReturnOld(Node *node, ReturnNode *u)
{
Node *result;
List *statements = NULL;
List *decls = NULL;
if (!in_procedure)
return node;
if (u->needs_sync) {
result = MakeBlockCoord(NULL,
NULL,
List2(MakeSyncCoord(node->coord),
MakeReturnCoord(u->expr, node->coord)),
node->coord,
UnknownCoord);
/* copy over analysis results from return to sync node */
((Node *) FirstItem(result->u.Block.stmts))->analysis.livevars = u->livevars;
((Node *) FirstItem(result->u.Block.stmts))->analysis.dirtyvars = u->dirtyvars;
return TransformNode(result);
}
u->expr = TransformNode(u->expr);
/* I'm not sure if this condition is right... -KHR */
if (in_inlet && (version == Fast || version == Slow))
return node;
else if (version == Fast) {
/* return x ==> { T _tmp = x; _BEFORE_RETURN_FAST(); return _tmp; } */
/* return ==> { _BEFORE_RETURN_FAST(); return; } */
/* if u->needs_sync == 1 then no need to create temparary value
* as it is already done in AnalyzeReturnExpressions. -fengmd */
if (u->expr && (!(u->needs_sync))) {
const char *tmp = MakeTempName();
Node *returntype = curr_proc->u.proc.decl->u.decl.type->u.fdcl.returns;
Node *decl = MakeDecl(tmp,
EMPTY_TQ,
NodeCopy(returntype, Subtree),
u->expr,
NULL);
decls = List1(decl);
statements = List2(MakeCall(MakeId(BeforeReturnFastName), NULL),
MakeReturn(MakeId(tmp)));
} else
statements = List2(MakeCall(MakeId(BeforeReturnFastName), NULL),
node);
} else if (version == Slow) {
/* return x ==> {_SET_RESULT(x); _SET_VALID; return;} */
/* return ==> {_SET_VALID; return;} */
if (u->expr)
statements = List1(MakeCall(MakeId(SetResultName),
List1(u->expr)));
else
statements = List1(MakeCall(MakeId(SetNoResultName), NULL));
statements = AppendItem(statements,
MakeCall(MakeId(BeforeReturnSlowName), NULL));
statements = AppendItem(statements, MakeReturn(NULL));
} else if (version == InletProc) {
/* return x ==> {*_inletresult = x; return;} */
/* return ==> return */
if (!u->expr)
return MakeBlock(NULL, NULL,
List2(MakeCall(MakeId(BeforeReturnInletName),
NULL),
node));
statements = List3(MakeBinop('=',
MakeUnary('*',
MakeId(InletResultName)),
u->expr),
MakeCall(MakeId(BeforeReturnInletName), NULL),
MakeReturn(NULL));
} else
FAIL("bad version in TransformReturn");
result = MakeBlock(NULL, decls, statements);
SetCoords(result, node->coord, Subtree);
return result;
}
#endif
PRIVATE inline Node *TransformBlock(Node *node, BlockNode *u)
{
ListMarker decl_marker;
Node *decl;
List *new_decl_list = NULL;
IterateList(&decl_marker, u->decl);
while (NextOnList(&decl_marker, (GenericREF) & decl)) {
decl = TransformNode(decl);
SetCurrentOnList(&decl_marker, decl);
/* build the generated list after extraction of declarations
* from blocks (see TransformDecl for why a Block can apear in here)
*/
if (decl != NULL) {
if (decl->typ == Block) {
new_decl_list = JoinLists(new_decl_list, decl->u.Block.decl);
} else {
new_decl_list = AppendItem(new_decl_list, decl);
}
}
}
u->decl = new_decl_list;
u->stmts = TransformList(u->stmts);
return node;
}
PRIVATE inline Node *TransformXBlock(Node *node, XBlockNode *u)
{
ListMarker decl_marker;
Node *decl;
IterateList(&decl_marker, u->decl);
while (NextOnList(&decl_marker, (GenericREF) & decl)) {
decl = TransformNode(decl);
SetCurrentOnList(&decl_marker, decl);
}
u->stmts = TransformList(u->stmts);
return node;
}
/*************************************************************************/
/* Determine whether a declaration has the CONST type qualifier */
/*************************************************************************/
PRIVATE Bool HasConstQual(Node *node)
{
return (NodeIsConstQual(NodeDataType(node)) ||
NodeIsConstQual(NodeDataTypeSuperior(node)));
}
/*************************************************************************/
/* */
/* Type nodes */
/* */
/*************************************************************************/
PRIVATE inline Node *TransformPrim(Node *node, UNUSED(primNode *u))
{
return node;
}
PRIVATE inline Node *TransformTdef(Node *node, UNUSED(tdefNode *u))
{
return node;
}
PRIVATE inline Node *TransformPtr(Node *node, ptrNode *u)
{
u->type = TransformNode(u->type);
return node;
}
PRIVATE inline Node *TransformAdcl(Node *node, adclNode *u)
{
u->type = TransformNode(u->type);
u->tq = NodeTq(u->type);
u->dimp->dim = TransformNode(u->dimp->dim);
return node;
}
PRIVATE inline Node *TransformFdcl(Node *node, fdclNode *u)
{
u->args = TransformList(u->args);
u->returns = TransformNode(u->returns);
/*
* EBA:
* for an inlet function, add :
* 1) the frame of the containing Cilk procedure to be the end of the
* arguments list.
* 2) the cilk worker state of the containing Cilk procedure to the end
* of the argument list (last formal argument). this is required for
* the Cilk_die() macro & others.
*/
if (in_inlet == 1) {
Node* frame;
Node* worker_state;
frame = MakeDecl(FrameName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
MakeFrameType(proc_name)),
NULL,
NULL);
worker_state = MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST, MakeWorkerStateType()),
NULL,
NULL);
AppendItem(u->args, frame);
AppendItem(u->args, worker_state);
}
if (tq_has_procedure(u->tq)) {
List *args;
Node *n;
args = u->args;
n = MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST, MakeWorkerStateType()),
NULL,
NULL);
if (args) {
if (IsVoidType(FirstItem(args))) {
u->args = List1(n);
} else {
u->args = ConsItem(n, args);
}
} else {
/* old-style fdecl, don't do anything and hope for the best */
}
}
return node;
}
#define UnionCheckFields(x) x=x
#define AssignEnumValues(x) x=x
PRIVATE void TransformSUE(SUEtype *sue)
{
if (sue->transformed == FALSE) {
ListMarker marker;
Node *field;
/* To stop infinite recursion */
sue->transformed = TRUE;
/* Loop over the fields of the SDCL */
IterateList(&marker, sue->fields);
while (NextOnList(&marker, (GenericREF) & field)) {
assert(field->typ == Decl);
field->u.decl.type = TransformNode(field->u.decl.type);
}
}
}
PRIVATE inline Node *TransformSdcl(Node *node, sdclNode *u)
{
TransformSUE(u->type);
return node;
}
PRIVATE inline Node *TransformUdcl(Node *node, udclNode *u)
{
TransformSUE(u->type);
return node;
}
PRIVATE inline Node *TransformEdcl(Node *node, edclNode *u)
{
TransformSUE(u->type);
return node;
}
/*************************************************************************/
/* */
/* Other nodes (decls et al.) */
/* */
/*************************************************************************/
PRIVATE inline Node *TransformDecl(Node *node, declNode *u)
{
u->type = TransformNode(u->type);
u->init = TransformNode(u->init);
u->bitsize = TransformNode(u->bitsize);
if (in_procedure && (u->kind == 2 ||
((version == Slow || node->memorycheckedp) &&
u->kind == 3))) {
if (!u->init)
return NULL;
{
/* We do an incredible hack to get a frame-only variable
* with initialization to compile correctly.
* t x = i;
* compiles to (ANSI compliant):
* int tmp1 = i;
* void* tmp2 = (f->x=tmp1),&tmp2;
* or
* int tmp1 = i;
* void* tmp2 = memcpy(&f->x, &tmp1, sizeof(tmp1));
* Why is this required ?
* Assume you have a variable x of type t (t is a structure)
* that is initialized when declared in the Cilk code.
* If the variable is designated as frame-only, cilk2c will
* not generate it on the stack - it will replace every
* usage of it with the value from the "_frame" structure.
* but there are 2 problems:
* 1) The initialization of the structure with values
* (e.g.: {1,2,"str",{TRUE, FALSE}, 'u'}) is allowed only
* when the variable is declared - it is not a valid syntax
* as an assignment statement.
* 2) Assignment cannot be put in the declarative part of a
* block. this means that we cannot convert the declaration
* into an assignment - we have to do the assignment in a
* way that declares a new temporary (unused) variable.
* so this transformation solves the problem by declaring a
* temporary variable & assigning it the initialization at
* declaration time & then copying that temporary variable
* into the frame variable using 'memcpy' whos result is the
* initialization of another temporary variable. this makes
* the memcpy part of a valid variable declaration !!!
*
* one technical issue is that we now have 2 declarations as
* a result of transforming a single declaration. to overcome
* this we wrap the 2 declarations in a Block node & return it
* as the result of the transformation. the caller will extract
* the declarations from the block & get rid of the Block node
* by concatenating the 2 declarations into the declarative
* list.
*/
const char *tmp1 = MakeTempName();
const char *tmp2 = MakeTempName();
Node *newdecl1 = MakeDecl(tmp1, u->tq, u->type, u->init, u->bitsize);
Node *newdecl2 ;
Node *id = MakeId(u->name);
id->u.id.decl = node;
if (NodeDataType(node)->typ == Adcl) {
newdecl2 = ParseWildcardStringNode("void * %d = memcpy(%e, &%d, sizeof(%d));",
tmp2, TransformNode(id), tmp1, tmp1);
} else {
newdecl2 = ParseWildcardStringNode("void * %d = ((%e = %d),&%d);",
tmp2, TransformNode(id), tmp1, tmp2);
}
/*
* a block in which the 2 generated declarations will be
* stored for having a single node returned.
* the caller (which is a block) will identify this & extract
* the declarations from the block. See TransformBlock() above.
*/
return MakeBlockCoord(NULL,
List2(newdecl1, newdecl2),
NULL,
node->coord, UnknownCoord);
}
}
/* delete static declarations (they have been globalized) -KHR */
if (in_procedure && tq_has_static(NodeStorageClass(node)))
return NULL;
/*
* remove const in slow declaration (to allow it to be loaded from
* frame)
*/
if (in_procedure && version == Slow)
NodeUpdateTq(node->u.decl.type, tq_remove_const);
/*
* Generate attribute for T_SHARED and T_PRIVATE variables
*/
if (tq_has_private(NodeDeclTq(node))) {
if (GenerateSegments) {
if (!HasConstQual(node))
u->attribs =
ConsItem(
MakeAttrib(
UniqueString("CILK_ATTRIBUTE_PRIVATE_VAR"),
NULL),
u->attribs);
} else
WarningCoord(2, node->coord,
"`private' qualifier not supported on this target\n");
} else if (tq_has_shared(NodeDeclTq(node)) ||
(GenerateSegments &&
tq_has_top_decl(NodeDeclLocation(node)) &&
!tq_has_extern(NodeStorageClass(node)) &&
!tq_has_register(NodeStorageClass(node)) &&
!tq_has_typedef(NodeStorageClass(node)) &&
NodeDataType(node)->typ != Fdcl)) {
if (tq_has_shared(NodeDeclTq(node)) && !GenerateSegments) {
#if 0
WarningCoord(2, node->coord,
"`shared' qualifier not supported on this target\n");
#endif
} else if (!HasConstQual(node))
u->attribs =
ConsItem(
MakeAttrib(UniqueString("CILK_ATTRIBUTE_SHARED_VAR"),
NULL),
u->attribs);
}
return node;
}
#if 0
/* this is no longer valid code, and it is drifting quickly. */
***OBSOLETE*** PRIVATE inline Node *TransformDeclOld(Node *node, declNode *u)
***OBSOLETE*** {
***OBSOLETE*** u->type = TransformNode(u->type);
***OBSOLETE*** u->init = TransformNode(u->init);
***OBSOLETE*** u->bitsize = TransformNode(u->bitsize);
***OBSOLETE***
***OBSOLETE*** if (in_procedure && (u->kind == 2 ||
***OBSOLETE*** ((version == Slow || node->memorycheckedp) &&
***OBSOLETE*** u->kind == 3))) {
***OBSOLETE*** if (!u->init)
***OBSOLETE*** return NULL;
***OBSOLETE*** {
***OBSOLETE*** /* We do an incredible hack to get a frame-only variable
***OBSOLETE*** * with initialization to compile correctly.
***OBSOLETE*** * t x = i;
***OBSOLETE*** * compiles to:
***OBSOLETE*** * int tmp1 = ({t tmp2 = i; f->x = tmp2; tmp1;});
***OBSOLETE*** */
***OBSOLETE*** const char *tmp1 = MakeTempName();
***OBSOLETE*** const char *tmp2 = MakeTempName();
***OBSOLETE*** Node *newinit, *newdecl, *assign;
***OBSOLETE*** Node *id = MakeId(u->name);
***OBSOLETE*** id->u.id.decl = node;
***OBSOLETE***
***OBSOLETE*** if (NodeDataType(node)->typ == Adcl)
***OBSOLETE*** assign = MakeCall(MakeId(UniqueString("memcpy")),
***OBSOLETE*** List3(TransformNode(id),
***OBSOLETE*** MakeId(tmp2),
***OBSOLETE*** MakeUnary(SIZEOF,
***OBSOLETE*** MakeId(tmp2))));
***OBSOLETE*** else
***OBSOLETE*** assign = MakeBinop('=', TransformNode(id), MakeId(tmp2));
***OBSOLETE***
***OBSOLETE*** newinit = MakeBlock(NULL,
***OBSOLETE*** List1(MakeDecl(tmp2,
***OBSOLETE*** u->tq,
***OBSOLETE*** u->type,
***OBSOLETE*** u->init,
***OBSOLETE*** u->bitsize)),
***OBSOLETE*** List2(assign,
***OBSOLETE*** MakeId(tmp1)));
***OBSOLETE*** newdecl = MakeDecl(tmp1,
***OBSOLETE*** EMPTY_TQ,
***OBSOLETE*** MakePrim(EMPTY_TQ, Sint),
***OBSOLETE*** newinit,
***OBSOLETE*** NULL);
***OBSOLETE*** SetCoords(newdecl, node->coord, Subtree);
***OBSOLETE*** return newdecl;
***OBSOLETE*** }
***OBSOLETE*** }
***OBSOLETE*** /* delete static declarations (they have been globalized) -KHR */
***OBSOLETE*** if (in_procedure && NodeStorageClass(node) == T_STATIC)
***OBSOLETE*** return NULL;
***OBSOLETE***
***OBSOLETE*** /*
***OBSOLETE*** * remove const in slow declaration (to allow it to be loaded from
***OBSOLETE*** * frame)
***OBSOLETE*** */
***OBSOLETE*** if (in_procedure && version == Slow)
***OBSOLETE*** NodeRemoveTq(node->u.decl.type, T_CONST);
***OBSOLETE***
***OBSOLETE*** /*
***OBSOLETE*** * Generate attribute for T_SHARED and T_PRIVATE variables
***OBSOLETE*** */
***OBSOLETE*** if (NodeDeclQuals(node) & T_PRIVATE) {
***OBSOLETE*** if (GenerateSegments) {
***OBSOLETE*** if (!HasConstQual(node))
***OBSOLETE*** u->attribs =
***OBSOLETE*** ConsItem(
***OBSOLETE*** MakeAttrib(
***OBSOLETE*** UniqueString("CILK_ATTRIBUTE_PRIVATE_VAR"),
***OBSOLETE*** NULL),
***OBSOLETE*** u->attribs);
***OBSOLETE*** } else
***OBSOLETE*** WarningCoord(2, node->coord,
***OBSOLETE*** "`private' qualifier not supported on this target\n");
***OBSOLETE*** } else if (NodeDeclQuals(node) & T_SHARED ||
***OBSOLETE*** (GenerateSegments &&
***OBSOLETE*** NodeDeclLocation(node) == T_TOP_DECL &&
***OBSOLETE*** NodeStorageClass(node) != T_EXTERN &&
***OBSOLETE*** NodeStorageClass(node) != T_REGISTER &&
***OBSOLETE*** NodeStorageClass(node) != T_TYPEDEF &&
***OBSOLETE*** NodeDataType(node)->typ != Fdcl)) {
***OBSOLETE*** if ((NodeDeclQuals(node) & T_SHARED) && !GenerateSegments) {
***OBSOLETE***#if 0
***OBSOLETE*** WarningCoord(2, node->coord,
***OBSOLETE*** "`shared' qualifier not supported on this target\n");
***OBSOLETE***#endif
***OBSOLETE*** } else if (!HasConstQual(node))
***OBSOLETE*** u->attribs =
***OBSOLETE*** ConsItem(
***OBSOLETE*** MakeAttrib(UniqueString("CILK_ATTRIBUTE_SHARED_VAR"),
***OBSOLETE*** NULL),
***OBSOLETE*** u->attribs);
***OBSOLETE*** }
***OBSOLETE***
***OBSOLETE*** return node;
***OBSOLETE***}
#endif
PRIVATE inline Node *TransformAttrib(Node *node, UNUSED(attribNode *u))
{
USE_UNUSED(u);
return node;
}
void MakeInletProc(Node *node)
{
Node *decl = node->u.proc.decl;
const char *name = MakeSlowInletName(proc_name, decl->u.decl.name);
Node *args_decl, *args_type;
/* Node *inlet_type;*/
Node *inlet_decl;
Node *inlet;
if (!IsVoidType(FirstItem(decl->u.decl.type->u.fdcl.args))) {
args_decl = MakeSdcl(TQ_SUE_ELABORATED,
make_SUE(Sdcl,
MakeInletArgsTypeName(name),
decl->u.decl.type->u.fdcl.args));
args_type = MakeInletArgsType(name);
} else {
args_decl = NULL;
args_type = MakePrim(EMPTY_TQ, Void);
}
/* inlet_type = MakeFdcl(EMPTY_TQ, */
/* List4(MakeDecl(WorkerStateName, */
/* T_FORMAL_DECL, */
/* MakePtr(T_CONST, */
/* MakeWorkerStateType()), */
/* NULL, */
/* NULL), */
/* MakeDecl(FrameName, */
/* EMPTY_TQ, */
/* MakePtr(EMPTY_TQ, */
/* MakeFrameType(proc_name)), */
/* NULL, */
/* NULL), */
/* MakeDecl(InletArgsName, */
/* EMPTY_TQ, */
/* MakePtr(EMPTY_TQ, */
/* args_type), */
/* NULL, */
/* NULL), */
/* MakeDecl(InletResultName, */
/* EMPTY_TQ, */
/* MakePtr(EMPTY_TQ, */
/* NodeCopy(decl->u.decl.type->u.fdcl.returns, */
/* Subtree)), */
/* NULL, */
/* NULL)), */
/* MakePrim(EMPTY_TQ, Void)); */
/* inlet_decl = MakeDecl(name, */
/* T_STATIC | T_SLOW_INLET, */
/* inlet_type, */
/* NULL, */
/* NULL); */
inlet_decl = ParseWildcardStringNode("static void %d(%t %d, %t *%d, %t *%d, %t *%d);",
name,
MakePtr(TQ_CONST, MakeWorkerStateType()), WorkerStateName,
MakeFrameType(proc_name), FrameName,
args_type, InletArgsName,
NodeCopy(decl->u.decl.type->u.fdcl.returns, Subtree), InletResultName);
NodeUpdateTq(inlet_decl, tq_add_slow_inlet);
if (args_decl)
SetCoords(args_decl, node->coord, Subtree);
SetCoords(inlet_decl, node->coord, Subtree);
in_inlet = 1;
version = InletProc;
assert(node->u.proc.body->typ==Block);
node->u.proc.body->u.Block.stmts = JoinLists(ParseWildcardString("(void)%d;(void)%d;(void)%d;", WorkerStateName, FrameName, InletResultName),
node->u.proc.body->u.Block.stmts);
inlet = MakeProc(inlet_decl,
TransformNode(node->u.proc.body));
version = Slow;
in_inlet = 0;
standalone_inlets = AppendItem(standalone_inlets, args_decl);
standalone_inlets = AppendItem(standalone_inlets, inlet);
}
void MakeInletProcOld(Node *node)
{
Node *decl = node->u.proc.decl;
const char *name = MakeSlowInletName(proc_name, decl->u.decl.name);
Node *args_decl, *args_type;
Node *inlet_type;
Node *inlet_decl;
Node *inlet;
if (!IsVoidType(FirstItem(decl->u.decl.type->u.fdcl.args))) {
args_decl = MakeSdcl(TQ_SUE_ELABORATED,
make_SUE(Sdcl,
MakeInletArgsTypeName(name),
decl->u.decl.type->u.fdcl.args));
args_type = MakeInletArgsType(name);
} else {
args_decl = NULL;
args_type = MakePrim(EMPTY_TQ, Void);
}
inlet_type = MakeFdcl(EMPTY_TQ,
List4(MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST,
MakeWorkerStateType()),
NULL,
NULL),
MakeDecl(FrameName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
MakeFrameType(proc_name)),
NULL,
NULL),
MakeDecl(InletArgsName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
args_type),
NULL,
NULL),
MakeDecl(InletResultName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
NodeCopy(decl->u.decl.type->u.fdcl.returns,
Subtree)),
NULL,
NULL)),
MakePrim(EMPTY_TQ, Void));
inlet_decl = MakeDecl(name,
tq_add_static(TQ_SLOW_INLET),
inlet_type,
NULL,
NULL);
if (args_decl)
SetCoords(args_decl, node->coord, Subtree);
SetCoords(inlet_decl, node->coord, Subtree);
/* printf("The node here...: \n");*/
/* PrintNode(stdout, inlet_decl, 3);*/
in_inlet = 1;
version = InletProc;
inlet = MakeProc(inlet_decl,
TransformNode(node->u.proc.body));
version = Slow;
in_inlet = 0;
standalone_inlets = AppendItem(standalone_inlets, args_decl);
standalone_inlets = AppendItem(standalone_inlets, inlet);
}
PRIVATE void MakeImplicitInletProc(Node *node)
{
const char *name = MakeImplicitInletName(proc_name, sync_count + 1); /* +1 because inlet is made before entry number is allocated */
Node *inlet_type, *inlet_decl, *stmt, *inlet;
Node *rhs_type, *lhs_type;
assert(node->typ == Spawn);
assert(node->u.spawn.assign_op != '=');
/*
* Generate inlet code for implicit inlet. It should look
* something like this:
* void _foo_inlet(_foo_frame *_frame, int *arg, int *result)
* { *result += *arg; }
* Note: frame pointer is not used.
*/
rhs_type = NodeCopy(GetSpawnFdcl(node->u.spawn.name)->u.fdcl.returns, Subtree);
lhs_type = NodeCopy(NodeDataType(node->u.spawn.receiver), Subtree);
inlet_type = MakeFdcl(EMPTY_TQ,
List4(MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST,
MakeWorkerStateType()),
NULL,
NULL),
MakeDecl(FrameName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
MakeFrameType(proc_name)),
NULL,
NULL),
MakeDecl(InletArgsName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
rhs_type),
NULL,
NULL),
MakeDecl(InletResultName,
EMPTY_TQ,
MakePtr(EMPTY_TQ,
lhs_type),
NULL,
NULL)),
MakePrim(EMPTY_TQ, Void));
inlet_decl = MakeDecl(name,
tq_add_static(TQ_SLOW_INLET),
inlet_type,
NULL,
NULL);
stmt = MakeBinop(node->u.spawn.assign_op,
MakeUnary('*', MakeId(InletResultName)),
MakeUnary('*', MakeId(InletArgsName)));
inlet = MakeProc(inlet_decl,
MakeBlock(NULL,
NULL,
AppendItem(ParseWildcardString("(void)%d;(void)%d;(void)%d;", WorkerStateName, FrameName, InletResultName),
stmt)));
SetCoords(inlet, UnknownCoord, Subtree);
standalone_inlets = AppendItem(standalone_inlets, inlet);
}
PRIVATE inline Node *TransformProc(Node *node, procNode *u)
{
Node *standalone_copy = NULL;
if (IsInletProc(node)) {
assert(in_procedure && !in_inlet);
if (version == Slow)
standalone_copy = NodeCopy(node, Subtree);
in_inlet = 1;
curr_inlet = node;
inlet_name = UniqueString(u->decl->u.decl.name);
}
else {
/* indicate this starts C code for CILK_WHERE_AM_I */
NodeUpdateTq(u->decl, tq_add_c_code);
curr_inlet = NULL;
inlet_name = NULL;
}
u->decl = TransformNode(u->decl);
u->body = TransformNode(u->body);
if (IsInletProc(node)) {
in_inlet = 0;
/* Change the type qualifier into T_SLOW_INLET for CILK_WHERE_AM_I */
if (version == Fast)
NodeUpdateTq(u->decl, tq_add_fast_inlet);
if (version == Slow)
NodeUpdateTq(u->decl, tq_add_slow_inlet);
/* make standalone inlet */
if (version == Slow)
MakeInletProc(standalone_copy);
}
return node;
}
PRIVATE inline Node *TransformText(Node *node, UNUSED(textNode *u))
{
USE_UNUSED(u);
return node;
}
PRIVATE List *SaveVariables(List *vars, Node *except)
{
ListMarker m;
Node *var;
List *statements = NULL;
IterateList(&m, vars);
while (NextOnList(&m, (GenericREF) & var)) {
if (var != except &&
(var->u.decl.kind == 1 ||
(version == Fast && (!(var->memorycheckedp)) &&
var->u.decl.kind == 3))) {
statements = AppendItem(statements,
MakeBinop('=',
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(var->u.decl.scope)),
MakeId(var->u.decl.name)),
MakeId(var->u.decl.name)));
}
}
return (statements);
}
/* if a is an empty list, then return a list with a NULL in it.*/
/* otherwise return a.*/
PRIVATE List *NonEmptyList (List *a) {
if (a==0) return List1(0);
else return a;
}
PRIVATE List *RestoreVariables(List *vars)
{
ListMarker m;
Node *var;
List *statements = NULL;
IterateList(&m, vars);
while (NextOnList(&m, (GenericREF) & var)) {
if ((var->u.decl.kind == 1 ||
(version == Fast && (!(var->memorycheckedp)) &&
var->u.decl.kind == 3))) {
statements = AppendItem(statements,
MakeBinop('=',
MakeId(var->u.decl.name),
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(var->u.decl.scope)),
MakeId(var->u.decl.name))));
}
}
return (statements);
}
/*
* This function generates one of two constructions
*
* {typeof(__tmp); _XPOP_FRAME_RESULT(frame, return_value, stuff for slow, result);}
* _XPOP_FRAME_NORESULT(frame, return_value, stuff for slow)
*
* depending on the presence of a receiver for the result.
*
* The _tmp variable is defined here to avoid actually emititng a non-ansi "typeof" construct.
*/
PRIVATE inline Node *MakeXPopFrame(UNUSED(Node *node), spawnNode *u)
{
Node *frame;
Node *return_value;
/* return type of the procedure being compiled, not the procedure *
* being spawned! */
Node *returntype = curr_proc->u.proc.decl->u.decl.type->u.fdcl.returns;
USE_UNUSED(node);
frame = MakeId(FrameName);
if (version == Slow)
return_value = MakeText(UniqueString("/* return nothing */"),
FALSE);
else if (IsScalarType(returntype))
return_value = MakeConstSint(0);
else if (IsVoidType(returntype))
return_value = MakeText(UniqueString("/* return nothing */"),
FALSE);
else
return_value = MakeBinop(ARROW,
MakeId(FrameName),
MakeId(DummyReturnName));
if (u->receiver) {
return ParseWildcardStringNode("{ %t __tmp; CILK2C_XPOP_FRAME_RESULT(%e, %e, %e); }",
NodeCopy(NodeDataType(u->receiver), Subtree),
frame,
return_value,
u->receiver);
}
else
return MakeCall(MakeId(XPopFrameNoResultName),
List2(frame,
return_value));
}
PRIVATE Node *MakeSetReceiver(Node *receiver_addr)
{
/* sets index of current frame to be the index of receiver in the *
* frame. */
/* _frame->_header.receiver = (void*) receiver_addr */
return MakeBinop('=',
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(HeaderName)),
MakeId(ReceiverName)),
MakeCast(MakePtr(EMPTY_TQ, MakePrim(EMPTY_TQ, Void)),
receiver_addr));
}
PRIVATE Bool SimplePointer(Node *receiver);
/* returns TRUE if receiver's address in the frame can be calculated
* statically, and if receiver is side-effect-free. Returns FALSE otherwise.
*/
PRIVATE Bool SimpleReceiver(Node *receiver)
{
List *dims;
switch (receiver->typ) {
case Id:
if (receiver->u.id.decl->u.decl.kind != 0)
return TRUE;
break;
case Binop:
if (receiver->u.binop.op == '.')
return SimpleReceiver(receiver->u.binop.left);
break;
case Unary:
if (receiver->u.unary.op == INDIR)
return SimplePointer(receiver->u.unary.expr);
break;
case Array:
/* First check if array is stored in the frame */
if (receiver->u.id.decl->u.decl.kind != 0) {
/* simple if all array dimensions are constant */
for (dims = receiver->u.array.dims; dims; dims = Rest(dims))
if (!NodeIsConstant(FirstItem(dims)))
return FALSE;
return SimplePointer(receiver->u.array.name);
}
break;
default:
/* there are probably other cases, but I don't feel like *
* dealing * with them now. KHR */
break;
}
return FALSE;
}
/* returns TRUE if pointer's offset in frame can be calculated statically,
* and if receiver is side-effect-free. Returns FALSE otherwise.
*/
PRIVATE Bool SimplePointer(Node *pointer)
{
switch (pointer->typ) {
case Id:
if (pointer->u.id.decl->u.decl.type->typ == Adcl)
return TRUE;
break;
case Binop:
if (pointer->u.binop.op == '+' || pointer->u.binop.op == '-') {
if (NodeIsConstant(pointer->u.binop.right) &&
SimplePointer(pointer->u.binop.left))
return TRUE;
if (NodeIsConstant(pointer->u.binop.left) &&
SimplePointer(pointer->u.binop.right))
return TRUE;
}
break;
case Unary:
if (pointer->u.unary.op == ADDRESS)
return SimpleReceiver(pointer->u.unary.expr);
break;
case Cast:
return SimplePointer(pointer->u.cast.expr);
case ImplicitCast:
return SimplePointer(pointer->u.implicitcast.expr);
default:
break;
}
return FALSE;
}
/* gcc asm extensions */
PRIVATE inline Node *TransformAsm(Node *node, asmNode *u)
{
u->template = TransformNode(u->template);
u->output = TransformList(u->output);
u->input = TransformList(u->input);
u->clobbered = TransformList(u->clobbered);
return node;
}
PRIVATE inline Node *TransformAsmArg(Node *node, asmargNode *u)
{
u->constraint = TransformNode(u->constraint);
u->expr = TransformNode(u->expr);
return node;
}
/* gcc stdarg.h support */
PRIVATE inline Node *TransformBuiltinVaArg(Node *node, builtinvaargNode *u)
{
u->expr = TransformNode(u->expr);
u->type = TransformNode(u->type);
return node;
}
PRIVATE Bool side_effect_free;
PRIVATE void CheckSideEffectFree(Node *node)
{
switch (node->typ) {
case Binop:
if (IsAssignmentOp(node->u.binop.op)) {
side_effect_free = FALSE;
return;
}
break;
case Unary:
if (IsIncDecOp(node->u.unary.op)) {
side_effect_free = FALSE;
return;
}
break;
case Block:
case Call:
case Spawn:
side_effect_free = FALSE;
return;
case Label:
case Switch:
case Case:
case Default:
case If:
case IfElse:
case While:
case Do:
case For:
case Goto:
case Continue:
case Break:
case Return:
case Sync:
FAIL("Statement in spawn arg");
break;
case Prim:
case Tdef:
case Adcl:
case Fdcl:
case Sdcl:
case Udcl:
case Edcl:
case Decl:
case Attrib:
case Proc:
/* don't need to touch types */
return;
default:
break;
}
#define CHILD(n) CheckSideEffectFree(n)
ASTWALK(node, CHILD);
#undef CHILD
}
PRIVATE Bool SideEffectFree(Node *node)
{
side_effect_free = TRUE;
CheckSideEffectFree(node);
return side_effect_free;
}
/* returns a decl of a temporary variable with type <type> */
PRIVATE Node *MakeTempDecl(Node *type)
{
const char *temp_arg = MakeTempName();
return MakeDecl(temp_arg,
EMPTY_TQ,
NodeCopy(type, Subtree),
NULL,
NULL);
}
PRIVATE inline List *TransformSpawnArgs(List *args,
List **declarations,
List **statements)
{
List *side_effect_free_args;
Node *arg, *temp_arg, *temp_decl;
ListMarker marker;
side_effect_free_args = NULL;
IterateList(&marker, args);
while (NextOnList(&marker, (GenericREF) & arg)) {
if (!SideEffectFree(arg)) {
temp_decl = MakeTempDecl(NodeDataType(arg));
temp_arg = MakeId(temp_decl->u.decl.name);
*declarations = AppendItem(*declarations,
temp_decl);
*statements = AppendItem(*statements,
MakeBinop('=',
MakeId(temp_decl->u.decl.name),
TransformNode(arg)));
} else
temp_arg = TransformNode(arg);
side_effect_free_args = AppendItem(side_effect_free_args, temp_arg);
}
return side_effect_free_args;
}
PRIVATE Node *TransformReceiver(Node *receiver,
OpType assign_op,
Node *return_type,
Node **linkage_index, /* linkage info */
Node **assignment, /* assignment *
* statement */
List **declarations,
List **statements)
{
Node *rec, *receiver_tmp, *receiver_addr;
Node *spawn_result = NULL;
int receiver_type; /*
* 0 - no receiver
* 1 - register variable
* 2 - fixed location in frame
* (SimpleReceiver)
* 3 - unknown location
* or side-effecting receiver */
/* figure out receiver type */
if (!receiver)
receiver_type = 0;
else if (receiver->typ == Id &&
(receiver->u.id.decl->u.decl.kind == 1 ||
(version == Fast && (!(receiver->memorycheckedp)) &&
receiver->u.id.decl->u.decl.kind == 3)))
receiver_type = 1;
else if (SimpleReceiver(receiver))
receiver_type = 2;
else
receiver_type = 3;
/* generate linkage_index part of link information - slow version only. */
if (version == Slow)
switch (receiver_type) {
case 0: /* no receiver */
*linkage_index = MakeConstSint(0);
break;
case 1: /* register variable */
*linkage_index = MakeCall(MakeId(OffsetofName),
List2(MakeFrameType(proc_name),
MakeBinop('.',
MakeId(receiver->u.id.decl->u.decl.scope),
MakeId(receiver->u.id.decl->u.decl.name))));
break;
case 2: /* fixed loc in frame */
rec = NodeCopy(receiver, Subtree);
version = Link;
rec = TransformNode(rec);
version = Slow;
*linkage_index = MakeCall(MakeId(OffsetofName),
List2(MakeFrameType(proc_name),
rec));
break;
case 3: /* unknown location */
*linkage_index = MakeConstSint(-1);
break;
default:
FAIL("bad receiver type");
break;
}
/* make <spawn_result>, <assignment> */
switch (receiver_type) {
case 0: /* no receiver */
spawn_result = NULL;
*assignment = NULL;
break;
case 1: /* register variable */
if (assign_op == '=') {
spawn_result = receiver;
*assignment = NULL;
break;
}
/* otherwise, fall through */
case 2: /* fixed loc in frame */
receiver_tmp = MakeTempDecl(NodeCopy(return_type, Subtree));
*declarations = AppendItem(*declarations, receiver_tmp);
spawn_result = MakeIdFromDecl(receiver_tmp);
rec = NodeCopy(receiver, Subtree);
rec->nondeterminator = FALSE;
*assignment = MakeBinop(assign_op,
TransformNode(rec),
MakeId(receiver_tmp->u.decl.name));
break;
case 3: /* unknown location */
receiver_tmp = MakeTempDecl(NodeCopy(return_type, Subtree));
*declarations = AppendItem(*declarations, receiver_tmp);
receiver_addr = MakeTempDecl(MakePtr(EMPTY_TQ,
NodeDataType(receiver)));
*declarations = AppendItem(*declarations, receiver_addr);
rec = NodeCopy(receiver, Subtree);
*statements = AppendItem(*statements,
MakeBinop('=',
MakeId(receiver_addr->u.decl.name),
TransformNode(MakeUnary(ADDRESS,
rec))));
spawn_result = MakeIdFromDecl(receiver_tmp);
*assignment = MakeBinop(assign_op,
MakeUnary('*',
MakeId(receiver_addr->u.decl.name)),
MakeId(receiver_tmp->u.decl.name));
*statements = AppendItem(*statements,
MakeSetReceiver(MakeId(receiver_addr->u.decl.name)));
break;
}
return spawn_result;
}
PRIVATE void TransformSpawn2(Node *node, spawnNode *u,
List **declarations, List **statements)
{
Node *linkage_index, *assignment;
Node *worker_state;
List *nargs;
Node *return_type = GetSpawnFdcl(u->name)->u.fdcl.returns;
assert(in_procedure && !in_inlet);
/* reserve a sync number */
sync_count++;
u->receiver = TransformReceiver(u->receiver, u->assign_op, return_type, &linkage_index,
&assignment, declarations, statements);
assert(SideEffectFree(u->name)); /* need this for now -KHR */
u->name = TransformNode(u->name);
/* Just change the name */
u->name->u.decl.name = MakeFastProcName( u->name->u.decl.name );
u->args = TransformSpawnArgs(u->args, declarations, statements);
/* add extra argument for worker state */
worker_state = MakeId(WorkerStateName);
nargs = ConsItem(worker_state, u->args);
/* set up link information */
if (version == Slow && !u->in_inlet) {
Node *size, *inlet, *argsize, *argindex;
if (u->receiver)
size = MakeUnary(SIZEOF, NodeCopy(return_type, Subtree));
else
size = MakeConstSint(0);
if (u->assign_op == '=') {
inlet = MakeConstSint(0);
argsize = MakeConstSint(0);
argindex = MakeConstSint(0);
} else {
inlet = MakeId(MakeImplicitInletName(proc_name, sync_count));
argsize = MakeUnary(SIZEOF, NodeCopy(return_type, Subtree));
argindex = MakeConstSint(0);
}
link_initializers =
AppendItem(link_initializers,
MakeInitializer(List5(size,
linkage_index,
inlet,
argsize,
argindex)));
}
/* make entry setting statement */
*statements = AppendItem(*statements,
MakeBinop('=',
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(HeaderName)),
MakeId(EntryName)),
MakeConstSint(sync_count)));
/* save live, dirty variables */
*statements = JoinLists(*statements,
SaveVariables(node->analysis.dirtyvars, NULL));
/* Insert _BEFORE_SPAWN_[FAST|SLOW] hook */
*statements =
AppendItem(*statements,
MakeCall(MakeId(version == Slow ? BeforeSpawnSlowName :
BeforeSpawnFastName),
NULL)
);
/* push frame */
*statements = AppendItem(*statements,
MakeCall(MakeId(PushFrameName),
List1(MakeId(FrameName))));
/* do call */
if (u->receiver) {
*statements = AppendItem(*statements,
MakeBinop('=',
u->receiver,
MakeCall(u->name,
nargs)));
if (node->memorycheckedp && (!(u->in_inlet))) {
/* inform the Nondeterminator that this is a spawn var */
*statements = AppendItem(*statements,
SpawnVarProfile(TransformNode(u->receiver),
NodeCopy(return_type,
Subtree),
u->assign_op));
}
}
else
*statements = AppendItem(*statements,
MakeCall(u->name,
nargs));
/* Extended pop: pop, check for steal, locking (in some unspecified order) */
*statements = AppendItem(*statements,
MakeXPopFrame(node, u));
/* Insert _AFTER_SPAWN_[FAST|SLOW] hook */
*statements =
AppendItem(*statements,
MakeCall(MakeId(version == Slow ? AfterSpawnSlowName :
AfterSpawnFastName),
NULL)
);
/* save spawn result somewhere, if necessary */
if (assignment != NULL)
*statements = AppendItem(*statements, assignment);
}
PRIVATE inline Node *TransformSpawn(Node *node, spawnNode *u)
{
List *declarations = NULL;
List *statements = NULL;
Node *result;
Coord coord = u->receiver ? u->receiver->coord : node->coord;
/* make standalone implicit inlet */
if (version == Slow && u->assign_op != '=')
MakeImplicitInletProc(node);
/* do guts of transformation */
TransformSpawn2(node, u, &declarations, &statements);
/* delay the call of Cilk_lreturn_spbags after the inlet is called */
if (MemoryChecking && u->receiver)
statements = AppendItem(statements,
MakeCall(MakeId("_ND_LRETURN_SPBAGS"),
List1(MakeId(FrameName))));
/* Add entry recovery statements to slow version */
if (version == Slow) {
statements = AppendItem(statements,
MakeIf(MakeConstSint(0),
MakeBlock(NULL, NULL,
ConsItem(MakeLabel(MakeSyncName(sync_count)),
NonEmptyList(RestoreVariables(node->analysis.livevars))))));
statements = AppendItem(statements,
MakeCall(MakeId(AtThreadBoundarySlowName),
NULL));
}
/* make block of stuff to replace spawn statement */
result = MakeBlock(NULL, declarations, statements);
SetCoords(result, coord, Subtree);
return result;
}
PRIVATE inline Node *TransformSync(Node *node, UNUSED(syncNode *u))
{
Node *result;
List *statements;
List *outerstatements;
USE_UNUSED(u);
assert(in_procedure && !in_inlet);
/* reserve a sync number */
sync_count++;
if (version == Fast) {
result = MakeCall(MakeId(AtSyncFastName), NULL);
SetCoords(result, node->coord, Subtree);
return result;
}
/* set up dummy link information */
if (version == Slow) {
link_initializers =
AppendItem(link_initializers,
MakeInitializer(List5(MakeConstSint(0),
MakeConstSint(0),
MakeConstSint(0),
MakeConstSint(0),
MakeConstSint(0))));
}
/*
* generate sync code. Sync code goes something like this:
* {
* _BEFORE_SYNC_SLOW();
* _frame->_header.entry = 3;
* <save dirty variables>
* if (_SYNC) {
* _POP_FRAME(_frame);
* return;
* _sync3:;
* <restore live variables>
* }
* _AFTER_SYNC_SLOW();
* }
*/
outerstatements = List1(MakeCall(MakeId(BeforeSyncSlowName), NULL));
/* set entry */
outerstatements = AppendItem(outerstatements,
MakeBinop('=',
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(HeaderName)),
MakeId(EntryName)),
MakeConstSint(sync_count)));
/* save live, dirty variables */
outerstatements = JoinLists(outerstatements,
SaveVariables(node->analysis.dirtyvars, NULL));
/* return */
statements = List1(MakeReturn(NULL));
/* sync label */
statements = AppendItem(statements,
MakeLabel(MakeSyncName(sync_count)));
/* restore variables */
statements = JoinLists(statements,
NonEmptyList(RestoreVariables(node->analysis.livevars)));
outerstatements = AppendItem(outerstatements,
MakeIf(MakeId(SynchronizeName),
MakeBlock(NULL, NULL, statements)));
outerstatements = AppendItem(outerstatements,
MakeCall(MakeId(AfterSyncSlowName), NULL));
outerstatements = AppendItem(outerstatements,
MakeCall(MakeId(AtThreadBoundarySlowName),
NULL));
result = MakeBlock(NULL, NULL, outerstatements);
SetCoords(result, node->coord, Subtree);
return result;
}
PRIVATE Node *TransformInletCall(Node *node, inletcallNode *u)
{
List *declarations = NULL;
List *statements = NULL;
Node *result;
Node *spawnarg;
List *otherargs;
List *formals, *actuals;
Node *temp_arg, *temp_decl;
Node *linkage_index, *assignment;
Coord coord = node->coord;
Bool void_spawn;
assert(in_procedure && !in_inlet);
/* get spawn argument and any other arguments */
assert(u->args != NULL);
spawnarg = FirstItem(u->args);
assert(spawnarg->typ == Spawn);
void_spawn = IsVoidType(spawnarg);
otherargs = Rest(u->args);
{
void *tmp= TransformReceiver(NULL, '=', NodeDataType(spawnarg), &linkage_index,
&assignment, &declarations, &statements);
assert(tmp==NULL);
}
u->name = TransformNode(u->name);
otherargs = TransformSpawnArgs(otherargs, &declarations, &statements);
/* set up link information */
if (version == Slow) {
Node *size, *inlet, *argindex, *argsize;
const char *scope;
const char *name;
/* calculate size entry - size of spawn's return value */
if (void_spawn)
size = MakeConstSint(0);
else
size = MakeUnary(SIZEOF, NodeDataType(spawnarg));
/* make inlet pointer */
name = MakeSlowInletName(proc_name, u->name->u.id.decl->u.decl.name);
inlet = MakeId(name);
/* make argsize and argindex */
formals = GetSpawnFdcl(u->name)->u.fdcl.args;
if (formals != NULL && !IsVoidType(FirstItem(formals))) {
scope = ((Node *) FirstItem(formals))->u.decl.scope;
assert(scope != NULL);
argsize = MakeUnary(SIZEOF,
MakeInletArgsType(name));
argindex = MakeCall(MakeId(OffsetofName),
List2(MakeFrameType(proc_name),
MakeId(scope)));
} else {
argsize = MakeConstSint(0);
argindex = MakeConstSint(0);
}
link_initializers =
AppendItem(link_initializers,
MakeInitializer(List5(size,
linkage_index,
inlet,
argsize,
argindex)));
}
/* save other arguments besides spawn argument to frame */
actuals = otherargs;
if (void_spawn)
formals = GetSpawnFdcl(u->name)->u.fdcl.args;
else
formals = Rest(GetSpawnFdcl(u->name)->u.fdcl.args);
for (; actuals != NULL; actuals = Rest(actuals), formals = Rest(formals)) {
Node *actual = FirstItem(actuals);
Node *formal = FirstItem(formals);
formal = MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(formal->u.decl.scope)),
MakeId(formal->u.decl.name));
statements = AppendItem(statements,
MakeBinop('=',
formal,
actual));
}
/* transform spawn argument */
if (!void_spawn) {
temp_decl = MakeTempDecl(NodeDataType(spawnarg));
/* treat this variable as a register variable, regardless of type */
temp_decl->u.decl.kind = 1;
declarations = AppendItem(declarations,
temp_decl);
temp_arg = MakeId(temp_decl->u.decl.name);
temp_arg->u.id.decl = temp_decl;
spawnarg->u.spawn.receiver = temp_arg;
otherargs = ConsItem(temp_arg, otherargs);
} else
spawnarg->u.spawn.receiver = NULL;
TransformSpawn2(spawnarg, &spawnarg->u.spawn, &declarations, &statements);
/* tell the Nondeterminator that we are entering an inlet */
if (MemoryChecking)
statements = AppendItem(statements,
MakeCall(MakeId("_ND_ENTER_INLET"),
List1(MakeCast(
MakePtr(EMPTY_TQ,
MakeGenericFrameType()),
MakeId(FrameName)))));
/* EBA:
* append "_cilk_frame" & "_cilk_ws" argument to inlet call, as last
* argument
*/
AppendItem(otherargs, MakeId(FrameName));
AppendItem(otherargs, MakeId(WorkerStateName));
/* do call of inlet */
statements = AppendItem(statements,
MakeCall(u->name,
otherargs));
/* EBA:
* Restore variables from "_cilk_frame" into local variables of procedure.
*/
statements = AppendItem(statements,
MakeText("/* Restore variables from frame */\n",
TRUE));
statements = AppendItem(statements,
MakeBlock(NULL, NULL,
NonEmptyList(RestoreVariables(node->analysis.livevars/*dirtyvars*/))));
/* tell the Nondeterminator that we are leaving an inlet */
if (MemoryChecking)
statements = AppendItem(statements,
MakeCall(MakeId("_ND_LEAVE_INLET"), NULL));
/* save inlet result somewhere, if necessary */
if (assignment != NULL)
statements = AppendItem(statements, assignment);
/* delay the call of Cilk_lreturn_spbags after the inlet is called */
if (MemoryChecking)
statements = AppendItem(statements,
MakeCall(MakeId("_ND_LRETURN_SPBAGS"),
List1(MakeId(FrameName))));
/* Add entry recovery statements to slow version */
if (version == Slow) {
statements = AppendItem(statements,
MakeIf(MakeConstSint(0),
MakeBlock(NULL, NULL,
ConsItem(MakeLabel(MakeSyncName(sync_count)),
NonEmptyList(RestoreVariables(node->analysis.livevars))))));
statements = AppendItem(statements,
MakeCall(MakeId(AtThreadBoundarySlowName),
NULL));
}
/* make block of stuff to replace inlet_call statement */
result = MakeBlock(NULL, declarations, statements);
SetCoords(result, coord, Subtree);
return result;
}
PRIVATE inline Node *TransformAbort(Node *node, UNUSED(abortNode *u))
{
Node *result;
USE_UNUSED(u);
assert(in_procedure);
switch (version) {
case Fast:
return MakeTextCoord(UniqueString("/* abort */;"), FALSE, node->coord);
case Slow:
result = MakeCall(MakeId(AbortSlowName), NULL);
SetCoords(result, node->coord, Subtree);
return result;
case InletProc:
result = MakeCall(MakeId(AbortStandaloneName), NULL);
SetCoords(result, node->coord, Subtree);
return result;
default:
FAIL("Unknown version");
}
return node;
}
PRIVATE inline Node *TransformSynched(Node *node, UNUSED(synchedNode *u))
{
USE_UNUSED(u);
assert(in_procedure && !in_inlet);
switch (version) {
case Fast:
return MakeConstSint(1);
case Slow:
case InletProc:
return MakeId(SynchedName);
default:
FAIL("Unknown version");
}
return node;
}
/* if implicit sync is needed, calculating return expressions and
* saving the result into temporary variables before implicit sync.
* This is done first in TransformCilkProc so that the temporary
* variables will be included in the procedure frames. -fengmd */
PRIVATE Node *AnalyzeReturnExpressions(Node *node)
{
#define CHILD(n) n = AnalyzeReturnExpressions(n)
{
ASTWALK(node, CHILD)
}
#undef CHILD
if ((node->typ == Return) &&
(node->u.Return.needs_sync) &&
(node->u.Return.expr)) {
const char *tmp = MakeTempName();
Node *returntype = node->u.Return.proc->u.proc.decl->u.decl.type->u.fdcl.returns;
Node *decl = MakeDecl(tmp,
TQ_BLOCK_DECL,
NodeCopy(returntype, Subtree),
node->u.Return.expr,
NULL);
Node *tmp_id = MakeIdCoord(tmp, node->coord);
Node *return_node = MakeReturnCoord(tmp_id, node->coord);
List *decls = List1(decl);
Node *result;
tmp_id->u.id.decl = decl;
return_node->u.Return.needs_sync = 1;
/* set analysis results of return node for later passing to sync node */
return_node->u.Return.livevars = decls;
return_node->u.Return.dirtyvars = decls;
result = MakeBlockCoord(NULL, decls, List1(return_node),
node->coord, UnknownCoord);
SetCoords(result, node->coord, Subtree);
return result;
} else
return node;
}
PRIVATE Node *MakeSlowDecl(const char *name)
{
Node *arg = MakeDecl(FrameName,
TQ_FORMAL_DECL,
MakePtr(EMPTY_TQ, MakeFrameType(name)),
NULL,
NULL);
Node *ws = MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST, MakeWorkerStateType()),
NULL,
NULL);
Node *n =
MakeDecl(MakeSlowProcName(name),
tq_add_static(tq_add_top_decl(TQ_SLOW_PROCEDURE)),
MakeFdcl(EMPTY_TQ, List2(ws, arg),
MakePrim(EMPTY_TQ, Void)),
NULL,
NULL);
return n;
}
PRIVATE Node *MakeExportDecl(procNode *u)
{
Node *n;
List *args;
Node *context;
n = NodeCopy(u->decl, Subtree);
n->u.decl.name = MakeExportProcName(n->u.decl.name);
n->u.decl.tq = tq_add_top_decl(tq_add_c_code(n->u.decl.tq));
args = TransformList(n->u.decl.type->u.fdcl.args);
/*printf("MakeExportDecl -name=%s\n", name);*/
context = MakeDecl(ContextName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST, MakeContextType()),
NULL,
NULL);
if (args) {
if (IsVoidType(FirstItem(args))) {
n->u.decl.type->u.fdcl.args = MakeNewList(context);
} else {
n->u.decl.type->u.fdcl.args = ConsItem(context, args);
}
} else {
/* old-style fdecl, don't do anything and hope for the best */
}
return n;
}
PRIVATE Node *MakeImportDecl(procNode *u)
{
Node *n;
List *args;
Node *returns;
Node *ws, *arg_struct;
n = NodeCopy(u->decl, Subtree);
n->u.decl.name = MakeImportProcName(n->u.decl.name);
n->u.decl.tq = tq_add_static(tq_add_top_decl(TQ_C_CODE));
n->u.decl.type->u.fdcl.returns = MakePrim(EMPTY_TQ, Void);
args = TransformList(n->u.decl.type->u.fdcl.args);
returns = u->decl->u.decl.type->u.fdcl.returns;
ws = MakeDecl(WorkerStateName,
TQ_FORMAL_DECL,
MakePtr(TQ_CONST, MakeWorkerStateType()),
NULL,
NULL);
arg_struct = MakeDecl(ProcArgsName_v,
TQ_FORMAL_DECL,
MakePtr(EMPTY_TQ, NodeCopy(PrimVoid, Subtree)), /*MakeProcArgsType(u->decl->u.decl.name)),*/
NULL,
NULL);
/* We still want to have the arg_struct in the fdcl.args list
* even in the case there the function has no incoming arguments
* and no return value
if (IsVoidArglist(args) && returns && IsVoidType(returns)){
n->u.decl.type->u.fdcl.args = List1(ws);
} else {
n->u.decl.type->u.fdcl.args = List2(ws, arg_struct);
}*/
n->u.decl.type->u.fdcl.args = List2(ws, arg_struct);
return n;
}
PRIVATE void SetDecl(Node *decl, List *register_vars, List *spawn_vars,
int scope_count)
{
TypeQual sc = NodeStorageClass(decl);
if (tq_has_extern(sc) || tq_has_static(sc) || tq_has_typedef(sc) ||
decl->u.decl.type->typ == Fdcl)
return; /* leave as kind 0 */
if (scope_count > 0 && tq_has_formal_decl(decl->u.decl.tq)) {
/* inlet argument variable */
decl->u.decl.kind = 4;
} else if (FindItem(register_vars, decl)) {
/* decl is for a register variable. */
if (FindItem(spawn_vars, decl))
decl->u.decl.kind = 3;
else
decl->u.decl.kind = 1;
} else {
/* decl is for a frame-only variable. */
decl->u.decl.kind = 2;
}
decl->u.decl.scope = MakeScopeName(scope_count);
}
PRIVATE List *FindAllScopes(Node *node, List *declscopes)
{
if (node->typ == Block && node->u.Block.decl) {
declscopes =
AppendItem(declscopes, node->u.Block.decl);
} else if (node->typ == Proc && IsInletProc(node)) {
/* add function arguments to scope list */
Node *type = node->u.proc.decl->u.decl.type;
assert(type->typ == Fdcl);
declscopes = AppendItem(declscopes, type->u.fdcl.args);
return declscopes;
/* return keeps FindAllScopes from looking inside local
* procedure */
}
/* transform children */
#define CHILD(n) declscopes = FindAllScopes(n, declscopes)
ASTWALK(node, CHILD)
#undef CHILD
return declscopes;
}
PRIVATE List *FindSideEffectedVariables(Node *node, List *sofar)
{
switch (node->typ) {
case Binop:
if (IsAssignmentOp(node->u.binop.op) &&
node->u.binop.left->typ == Id)
sofar = ConsItem(node->u.binop.left->u.id.decl, sofar);
break;
case Unary:
if (IsIncDecOp(node->u.unary.op) &&
node->u.unary.expr->typ == Id)
sofar = ConsItem(node->u.unary.expr->u.id.decl, sofar);
break;
default:
break;
}
#define CODE(n) sofar = FindSideEffectedVariables(n, sofar)
ASTWALK(node, CODE)
#undef CODE
return sofar;
}
PRIVATE List *FindSpawnVariables(Node *node, List *sofar)
{
if (node->typ == Spawn) {
if (node->u.spawn.receiver &&
node->u.spawn.receiver->typ == Id)
return ConsItem(node->u.spawn.receiver->u.id.decl, sofar);
} else if (node->typ == InletCall) {
; /* sofar should just be returned, since inlets don't have spawns or inlets inside them. But just fall through is OK too. */
} else if (node->typ == Proc && IsInletProc(node)) {
/* need to find all variables modified by the inlet. These
* variables need to be in the frame for the slow version. */
return JoinLists(sofar,
FindSideEffectedVariables(node, NULL));
}
/* transform children */
#define CHILD(n) sofar = FindSpawnVariables(n, sofar)
ASTWALK(node, CHILD)
#undef CHILD
return sofar;
}
PRIVATE void AnalyzeVariables(Node *node)
{
ListMarker marker;
Node *decl;
int scope_count;
/* find out which variables can be stored in registers */
List *register_vars = RegisterVariables(node, NULL);
List *spawn_vars = FindSpawnVariables(node, NULL);
/* find all local scopes */
List *scopes = FindAllScopes(node, NULL);
scopes = ConsItem(node->u.proc.decl->u.decl.type->u.fdcl.args, scopes);
/* iterate over all local variables in the procedure */
scope_count = 0;
while (scopes) {
IterateList(&marker, FirstItem(scopes));
while (NextOnList(&marker, (GenericREF) & decl)) {
if (decl->typ == Decl)
SetDecl(decl, register_vars, spawn_vars, scope_count);
}
scopes = Rest(scopes);
scope_count++;
}
/* make frame references as global */
if (node->memorycheckedp)
AnalyzeFrameReadWrite(node);
}
PRIVATE Node *ExpandTypedefs(Node *node)
{
Node *junk;
Node *new = NodeCopy(node, NodeOnlyExact);
#define CHILD(n) n = ExpandTypedefs(n)
{
ASTWALK(new, CHILD)
}
#undef CHILD
/* expand locally declared typedefs */
if (new->typ == Tdef) {
if (LookupSymbol(Identifiers, new->u.tdef.name,
(GenericREF) & junk)) {
if (tq_has_typedef(NodeStorageClass(junk)) &&
junk->u.decl.type == new->u.tdef.type)
return new; /* external declaration is OK */
}
/*
* external declaration is not the same as the local one - must
* expand the typedef.
*/
/*
* tdef.type is not visited when doing an ASTWALK! could we
* get into circularity problems? I don't think so. -KHR
*/
new->u.tdef.type = ExpandTypedefs(new->u.tdef.type);
/*
* is this the right thing to do with tdef's type qualifiers? -
* KHR
*/
NodeUpdateTq2(new->u.tdef.type, tq_union, new->u.tdef.tq);
return new->u.tdef.type;
} else
return new;
}
PRIVATE int is_unused_attrib(Generic *item)
{
Node *attrib = item;
assert(attrib && attrib->typ==Attrib);
if (strcmp(attrib->u.attrib.name, "__unused__")==0) return 1;
else return 0;
}
PRIVATE void remove_const_register_unused_attribute(Generic *item)
{
Node *decl=item;
assert(decl != NULL && decl->typ == Decl);
if (tq_has_register(decl->u.decl.tq)) {
decl->u.decl.tq = tq_remove_all_storage_classes(decl->u.decl.tq);
}
NodeUpdateTq(decl->u.decl.type, tq_remove_const);
decl->u.decl.attribs = DeleteIf(decl->u.decl.attribs, is_unused_attrib);
}
PRIVATE Node *MakeFrame(procNode *u)
{
List *scopes, *scope;
int scope_count;
List *fields;
ListMarker marker1, marker2;
Node *result;
Node *type;
/*
* make frame:
*
* typedef struct foo_frame {
* StackFrameT _header;
* { ... args ... } _scope0;
* { ... scope 1 vars ...} _scope1;
* ...
* { ... scope <n> vars ...} _scope<n>;
* }
*
* for each different type of inlet, we also have a scope that
* holds its argument list.
* { ... args of inlet 1 ... } _scope<x>;
* { ... args of inlet <n> ... } _scope<y>;
*
* The inlet scopes are mixed in with the regular scopes in no
* particular order. We could put all of the inlet argument
* scopes in a oneof because only one is being used at a time.
*/
fields = List1(MakeDecl(HeaderName,
TQ_SU_DECL,
MakeGenericFrameType(),
NULL,
NULL));
/* if proc return type is not an arithmetic type, put it in frame */
type = u->decl->u.decl.type->u.fdcl.returns;
if (!IsVoidType(type) && !IsScalarType(type)) {
fields = AppendItem(fields,
MakeDecl(DummyReturnName,
TQ_SU_DECL,
NodeCopy(type, Subtree),
NULL,
NULL));
}
/* add scopes to frame */
scopes = FindAllScopes(u->body, NULL);
scopes = ConsItem(u->decl->u.decl.type->u.fdcl.args, scopes);
scope_count = 0;
IterateList(&marker1, scopes);
while (NextOnList(&marker1, (GenericREF) & scope)) {
List *scopefields = NULL;
Node *decl;
IterateList(&marker2, scope);
while (NextOnList(&marker2, (GenericREF) & decl)) {
if (decl->typ != Decl)
continue;
if (decl->u.decl.kind == 0)
continue;
SetCurrentOnList(&marker2, NodeCopy(decl, Subtree));
remove_const_register_unused_attribute(decl);
decl->u.decl.type = ExpandTypedefs(decl->u.decl.type);
decl->u.decl.init = NULL;
decl = TransformNode(NodeCopy(decl, Subtree));
scopefields = AppendItem(scopefields, decl);
}
if (scopefields)
fields = AppendItem(fields,
MakeDecl(MakeScopeName(scope_count),
TQ_SU_DECL,
MakeSdcl(TQ_SUE_ELABORATED,
make_SUE(Sdcl, NULL, scopefields)),
NULL,
NULL));
scope_count++;
}
/* finally, make struct declaration for frame */
result = MakeDecl(NULL,
TQ_TOP_DECL,
MakeSdcl(TQ_SUE_ELABORATED,
make_SUE(Sdcl, MakeFrameTypeName(u->decl->u.decl.name), fields)),
NULL,
NULL);
SetCoords(result, UnknownCoord, Subtree);
return result;
}
PRIVATE Node *MakeArgsAndResultStruct(procNode *u) {
Node *decl, *fdcl;
Node *args_decl;
List* fields = NULL;
Node *returns;
decl = u->decl;
assert(decl->typ == Decl);
fdcl = decl->u.decl.type;
assert(fdcl->typ == Fdcl);
if( !IsVoidType(FirstItem(fdcl->u.fdcl.args) ) ) {
fields = Mapc(ListCopyNodes(fdcl->u.fdcl.args, Subtree),
remove_const_register_unused_attribute);
fields = Mapc(fields, (void (*)(Generic *))TransformNode);
}
/* Append result item to the field list*/
if( !IsVoidType(fdcl->u.fdcl.returns) ) {
returns = NodeCopy(fdcl->u.fdcl.returns, Subtree);
fields = ConsItem( MakeDecl(ProcResultName,
TQ_FORMAL_DECL,
returns,
NULL,
NULL),
fields);
}
/* Create the structure */
if ( fields ) {
args_decl = MakeSdcl(TQ_SUE_ELABORATED,
make_SUE(Sdcl,
MakeProcArgsTypeName(decl->u.decl.name),
fields));
/*args_type = MakeProcArgsType(decl->u.decl.name);*/
} else {
args_decl = NULL;
/*args_type = MakePrim(EMPTY_TQ, Void);*/
}
return args_decl;
}
PRIVATE inline Node *MakeLinkage(UNUSED(Node *node))
{
Node *linkage;
USE_UNUSED(node);
/* make CilkProcInfo declaration */
linkage = MakeDecl(MakeLinkName(proc_name),
TQ_STATIC,
MakeAdcl(EMPTY_TQ,
MakeTdef(EMPTY_TQ,
UniqueString("CilkProcInfo")),
NULL),
MakeInitializer(link_initializers),
NULL);
SetCoords(linkage, UnknownCoord, Subtree);
return (linkage);
}
/*
* Add code to allocate frame to beginning of fast body. For example:
* _foo_frame *_frame;
* _INIT_FRAME(_frame, sizeof(_foo_frame), _foo_sig);
* _START_THREAD_FAST();
* (_INIT_FRAME does, among other things,
* _frame->_header.size = sizeof(_foo_frame);
* _frame->_header.sig = _foo_sig; )
*
* ... transfer non-register arguments to frame ...
*/
PRIVATE Node *AddFastStuff(Node *body, List *formals)
{
List *stmts;
ListMarker marker;
Node *decl;
stmts = List1(MakeCall(MakeId(InitFrameName),
List3(MakeId(FrameName),
MakeUnary(SIZEOF,
MakeFrameType(proc_name)),
MakeId(MakeLinkName(proc_name)))));
stmts = AppendItem(stmts,
MakeCall(MakeId(StartThreadFastName), NULL));
/* move any frame-only formals to frame */
IterateList(&marker, formals);
while (NextOnList(&marker, (GenericREF) & decl)) {
if (decl->u.decl.kind == 2) {
const char *name = decl->u.decl.name;
const char *scope = decl->u.decl.scope;
/*
* we need to do something different for array arguments
* -KHR
*/
stmts = AppendItem(stmts,
MakeBinop('=',
MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(scope)),
MakeId(name)),
MakeId(name)));
}
}
/* append code of procedure here */
stmts = AppendItem(stmts, body);
return MakeBlock(NULL,
List1(MakeDecl(FrameName,
TQ_BLOCK_DECL,
MakePtr(EMPTY_TQ,
MakeFrameType(proc_name)),
NULL,
NULL)),
stmts);
}
/*
* Add case statement and argument unpacking to beginning of slow body.
* For example:
* int n; < declaration for each register formal >
* _START_THREAD_SLOW();
* switch (_frame->_header.entry) {
* case 1: goto _sync1;
* case 2: goto _sync2;
* case 3: goto _sync3;
* }
* n = _frame->n; < initialization for each register formal >
*/
Node *AddSlowStuff(Node *body, List *formals)
{
List *cases = NULL;
List *regdecls = NULL;
ListMarker marker;
Node *decl;
/* make cases for case statement */
for (; sync_count; sync_count--) {
cases = ConsItem(MakeCase(MakeConstSint(sync_count),
NULL),
ConsItem(MakeGoto(MakeLabel(MakeSyncName(sync_count))),
cases));
}
/* get declarations for register formals */
IterateList(&marker, formals);
while (NextOnList(&marker, (GenericREF) & decl)) {
if (decl->u.decl.kind == 1) {
decl = NodeCopy(decl, Subtree);
remove_const_register_unused_attribute(decl);
regdecls = AppendItem(regdecls, decl);
}
}
return MakeBlock(NULL,
regdecls,
ConsItem(
MakeCall(MakeId(StartThreadSlowName), NULL),
ConsItem(
MakeSwitch(MakeBinop('.',
MakeBinop(ARROW,
MakeId(FrameName),
MakeId(HeaderName)),
MakeId(EntryName)),
MakeBlock(NULL, NULL, cases),
cases),
AppendItem(RestoreVariables(regdecls),
body))));
}
Node *MakeExportBody(Node *body, procNode *u)
{
List *original_args = u->decl->u.decl.type->u.fdcl.args;
Node *returns = u->decl->u.decl.type->u.fdcl.returns;
ListMarker marker;
Node *arg;
Node *arg_struct;
List *call_args = NULL;
Node *arg_assignment;
Node *malloc_call;
Node *free_call = NULL;
body->u.Block.decl = NULL;
body->u.Block.stmts = NULL;
/* Create arg struct */
if( (original_args && !IsVoidType(FirstItem(original_args))) || (returns && !IsVoidType(returns))) {
/* define the struct */
arg_struct = MakeDecl(ProcArgsName,
EMPTY_TQ,
MakePtr(EMPTY_TQ, MakeProcArgsType(u->decl->u.decl.name)),
NULL,
NULL);
body->u.Block.decl = List1(arg_struct);
/* Allocate the struct */
malloc_call = MakeCall(MakeId(UniqueString("Cilk_malloc_fixed")),
List1( MakeUnary(SIZEOF,
MakeProcArgsType(u->decl->u.decl.name))));
body->u.Block.stmts = List1( MakeBinop('=',
MakeId(ProcArgsName),
MakeCast(MakePtr(EMPTY_TQ,
MakeProcArgsType(u->decl->u.decl.name)),
malloc_call)));
free_call = MakeCall(MakeId(UniqueString("Cilk_free")),
List1(MakeId(ProcArgsName)));
}
/* Initialize the argument struct*/
IterateList(&marker, original_args);
while (NextOnList(&marker, (GenericREF) & arg)) {
if( ! IsVoidType(arg) ) {
arg_assignment = MakeBinop('=',
MakeBinop(ARROW,
MakeId(ProcArgsName),
MakeId(arg->u.id.text)),
MakeId(arg->u.id.text));
body->u.Block.stmts = AppendItem( body->u.Block.stmts, arg_assignment );
}
}
/* Create arg list for Cilk_start */
if( (original_args && !IsVoidType(FirstItem(original_args))) || (returns && !IsVoidType(returns)))
call_args = List3( MakeId(ContextName),
MakeId(MakeImportProcName(u->decl->u.decl.name)),
MakeId(ProcArgsName));
else
call_args = List3( MakeId(ContextName),
MakeId(MakeImportProcName(u->decl->u.decl.name)),
MakeConstPtr(0) /*NULL*/);
if(returns && !IsVoidType(returns) ) {
Node *result;
/* Add retval to defionitions */
body->u.Block.decl = AppendItem( body->u.Block.decl,
MakeDecl(ProcResultName,
EMPTY_TQ,
NodeCopy(returns, Subtree),
NULL,
NULL) );
call_args = AppendItem( call_args,
MakeUnary(SIZEOF, NodeCopy(returns, Subtree)));
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
MakeCall(MakeId(ExportCilkStartName), call_args ) );
result = MakeBinop(ARROW,
MakeId(ProcArgsName),
MakeId(ProcResultName));
/* Assign the return value to local varible */
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
MakeBinop('=',
MakeId(ProcResultName),
MakeBinop(ARROW,
MakeId(ProcArgsName),
MakeId(ProcResultName))));
/* Delete the allocated arg staruct */
if( free_call )
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
free_call );
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
MakeReturn(MakeId(ProcResultName)) );
}else {
call_args = AppendItem( call_args,
MakeConstSint(0));
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
MakeCall(MakeId(ExportCilkStartName), call_args ) );
/* Delete the allocated arg staruct */
if( free_call )
body->u.Block.stmts = AppendItem( body->u.Block.stmts,
free_call );
}
/*printf("MakeExportBody stmts typ=%d\n", body->u.Block.stmts->typ);*/
return body;
}
Node *MakeImportBody(Node *body, procNode *u)
{
List *original_args = u->decl->u.decl.type->u.fdcl.args;
Node *returns = u->decl->u.decl.type->u.fdcl.returns;
ListMarker marker;
Node *arg;
List *use_unused = ParseWildcardString("(void)%d;(void)%d;", WorkerStateName, ProcArgsName_v);
List *call_args = NULL;
Node *call, *result;
/* Create the list of the call arguments */
call_args = List1( MakeId(WorkerStateName));
IterateList(&marker, original_args);
while (NextOnList(&marker, (GenericREF) & arg)) {
if( ! IsVoidType(arg) )
call_args = AppendItem( call_args,
MakeBinop(ARROW,
MakeCast(MakePtr(EMPTY_TQ, MakeProcArgsType(u->decl->u.decl.name)),
MakeId(ProcArgsName_v)),
MakeId(arg->u.id.text) ) );
}
call = MakeCall(MakeId(u->decl->u.decl.name), call_args );
body->u.Block.decl = NULL;
if( returns && !IsVoidType(returns) ) {
result = MakeBinop(ARROW,
MakeCast(MakePtr(EMPTY_TQ, MakeProcArgsType(u->decl->u.decl.name)),
MakeId(ProcArgsName_v)),
MakeId(ProcResultName));
body->u.Block.stmts = AppendItem( use_unused, MakeBinop('=', result,call ));
}
else {
body->u.Block.stmts = AppendItem( use_unused, call);
}
/*printf("MakeExportBody stmts typ=%d\n", body->u.Block.stmts->typ);*/
return body;
}
Node *GlobalizeSUE(SUEtype *type)
{
Node *junk;
assert(type->complete);
/* choose a globally unique name for this SUE */
if (LookupSymbol(Tags, type->name, (GenericREF) & junk)) {
char buf[40];
sprintf(buf, "%s%.16s", CilkPrefix, type->name);
type->name = InsertUniqueSymbol(Tags, type, buf);
}
switch (type->typ) {
case Sdcl:
return MakeSdcl(TQ_SUE_ELABORATED, type);
case Udcl:
return MakeUdcl(TQ_SUE_ELABORATED, type);
case Edcl:
return MakeEdcl(TQ_SUE_ELABORATED, type);
default:
FAIL("bad type in GlobalizeSUE");
return NULL;
}
}
List *MoveSUEToTop(Node *node, List *sofar)
{
Node *new = NULL;
#define CODE(n) sofar = MoveSUEToTop(n, sofar)
ASTWALK(node, CODE)
#undef CODE
switch (node->typ) {
case Sdcl:
if (tq_has_sue_elaborated(node->u.sdcl.tq)) {
new = GlobalizeSUE(node->u.sdcl.type);
NodeUpdateTq(node, tq_remove_sue_elaborated);
}
break;
case Udcl:
if (tq_has_sue_elaborated(node->u.udcl.tq)) {
new = GlobalizeSUE(node->u.udcl.type);
NodeUpdateTq(node, tq_remove_sue_elaborated);
}
break;
case Edcl:
if (tq_has_sue_elaborated(node->u.edcl.tq)) {
new = GlobalizeSUE(node->u.edcl.type);
NodeUpdateTq(node, tq_remove_sue_elaborated);
}
break;
case Decl:
if (tq_has_static(NodeStorageClass(node)) &&
tq_has_block_decl(NodeDeclLocation(node))) {
Node *junk;
/* choose a globally unique name for this static *
* variable */
if (LookupSymbol(Identifiers, node->u.decl.name, (GenericREF) & junk)) {
node->u.decl.name = InsertUniqueSymbol(Identifiers, node, node->u.decl.name);
} else {
InsertSymbol(Identifiers, node->u.decl.name, node, NULL);
}
new = node;
NodeSetDeclLocation(new, TQ_TOP_DECL);
new = TransformDecl(new, &new->u.decl);
/*
* Note: the static variables will be renamed (if necessary)
* by TransformId, and the local static declaration will be
* removed by TransformDecl. -KHR
*/
}
break;
default:
break;
}
if (new) {
/*
* make sure we expand any typedefs of declarations moved to
* the top level. -KHR
*/
new = ExpandTypedefs(new);
SetCoords(new, UnknownCoord, Subtree);
sofar = AppendItem(sofar, new);
}
return sofar;
}
PRIVATE const char* MakeInnerInletName(const char* this_inlet_name)
{
if (version == Slow) {
return (MakeInnerSlowInletName(proc_name, this_inlet_name));
} else {
assert(version == Fast);
return (MakeInnerFastInletName(proc_name, this_inlet_name));
}
}
/*
* EBA:
* move the inlet function from the scope of the Cilk procedure to top
* (global) scope.
* also, change its name as described in RenameCallsToInnerInletNames
*
* arguments:
* node - current node on the AST.
* inlets - a list of nodes of the inlet procedures. filled by this recursion.
* inlets_original_name - a list of string name of the inlet procedures as it
* apears in the original code. filled by this recursion.
*/
PRIVATE Node* ExtractInletFunc (Node* node,
List** inlets,
List** inlets_original_name)
{
if ((node->typ == Proc) && (IsInletProc(node) == FALSE)) {
/* set the curr_proc & proc_name global variables. */
proc_name = node->u.proc.decl->u.decl.name;
/*
printf("entering Cilk proc %s\n", proc_name);
*/
}
/* EBA
* Extract the inlet out of the procedure's body. it will be added
* later as a top level function.
*/
if ((node->typ == Proc) &&
(tq_has_slow_inlet(node->u.proc.decl->u.decl.tq) ||
tq_has_fast_inlet(node->u.proc.decl->u.decl.tq))) {
const char* this_inlet_name = MakeInnerInletName(node->u.proc.decl->u.decl.name);
const char* short_name;
assert((version == Slow) || (version == Fast));
if (version == Slow) {
short_name = "Slow";
} else {
short_name = "Fast";
}
/*
printf("changing inlet name from '%s' to '%s'\n",
node->u.proc.decl->u.decl.name,
this_inlet_name);
*/
*inlets_original_name =
AppendItem(*inlets_original_name,
UniqueString(node->u.proc.decl->u.decl.name));
node->u.proc.decl->u.decl.name = this_inlet_name;
*inlets = AppendItem(*inlets, node);
return (MakeText(MakeRemovedInletRemark(short_name),
TRUE));
}
/* transform children */
#define CHILD(n) n = ExtractInletFunc(n, inlets, inlets_original_name)
ASTWALK(node, CHILD)
#undef CHILD
return (node);
}
#if 0
/*
* EBA:
* remove all inlet functions from the scope of the Cilk procedure.
* This is done by replacing them with text nodes containing a remark.
*/
PRIVATE Node* RemoveInletFunctions (Node* node)
{
/* EBA:
* the "Proc" node that declares an INLET is found, the original node
* is replaced with the returned node. so i replace it with an text
* node :)
*/
if ((node->typ == Proc) &&
(node->u.proc.decl->u.decl.tq & T_FAST_INLET)) {
return (MakeText("/*------- Fast inlet as inner function was removed"
" ------*/",
TRUE));
}
/* transform children */
#define CHILD(n) n = RemoveInletFunctions(n)
ASTWALK(node, CHILD)
#undef CHILD
return node;
}
#endif
/* EBA
* because the inner inlet is extracted to global scope its name is changed.
* the inlet named INLET in Cilk procedure PROC will be named
* "_cilk_PROC_INLET_inlet_{slow|fast}".
*/
PRIVATE Node* RenameCallsToInnerInletNames (Node* node,
List* inlets_original_name)
{
if ((node->typ == Proc) && (IsInletProc(node) == FALSE)) {
/* set the curr_proc & proc_name global variables. */
proc_name = node->u.proc.decl->u.decl.name;
/*
printf("entering Cilk proc %s\n", proc_name);
*/
}
if (node->typ == Call) {
int is_call_to_inlet;
/* check whether this call is made to an inlet */
is_call_to_inlet = FALSE;
#define FIND_INLET_OP(iname) \
if (strcmp(node->u.call.name->u.id.text, \
(const char*)iname) == 0) \
is_call_to_inlet = TRUE;
LISTWALK(inlets_original_name, FIND_INLET_OP)
#undef FIND_INLET_OP
if (is_call_to_inlet == TRUE) {
/* its a call to an inlet - replace name of function to be
* called
*/
const char* this_inlet_name = MakeInnerInletName(node->u.proc.decl->u.decl.name);
/*
printf("changing inlet name from '%s' to '%s'\n",
node->u.proc.decl->u.decl.name,
this_inlet_name);
*/
node->u.proc.decl->u.decl.name = this_inlet_name;
return node;
}
}
/* transform children */
#define CHILD(n) n = RenameCallsToInnerInletNames(n, inlets_original_name)
ASTWALK(node, CHILD)
#undef CHILD
return node;
}
PRIVATE inline List *TransformCilkProc(Node *node, procNode *u)
{
Node *fastnode, *slownode, *exportnode, *importnode;
Node *decl;
List *result;
List *inlets_nodes = NULL;
List *slow_inlets_original_name = NULL;
List *fast_inlets_original_name = NULL;
if (!strcmp("main",u->decl->u.decl.name)) {
u->decl->u.decl.name = UniqueString("cilk_main");
}
/* if implicit sync is needed, calculating return expressions and
* saving the result into tempary variables before implicit sync.
* -fengmd */
node = AnalyzeReturnExpressions(node);
/* analyze procedure variables */
AnalyzeVariables(node);
/* start with empty text node - just enforces coord start */
result = List1(MakeTextCoord("", FALSE, node->coord));
/* move structures/unions/enums, static variables to outer scope */
result = JoinLists(result, MoveSUEToTop(node, NULL));
/* make frame declaration for procedure */
result = AppendItem(result, MakeFrame(u));
/* Make arg structure declaration for import/export procedures */
result = AppendItem(result, MakeArgsAndResultStruct(u));
/* write down some global variables for other routines to read */
proc_name = u->decl->u.decl.name;
curr_proc = node;
fastnode = NodeCopy(node, Subtree);
slownode = NodeCopy(node, Subtree);
exportnode = NodeCopy(node, Subtree);
importnode = NodeCopy(node, Subtree);
/*printf("TransformCilkProc - exoprtnode->decl=%p exoprtnode->decl->typ=%d\n", exportnode->u.proc.decl, exportnode->u.proc.decl->typ);*/
/* add implicit sync and return to slow and fast bodies, if needed */
if (node->u.proc.needs_sync) {
slownode->u.proc.body->u.Block.stmts =
AppendItem(slownode->u.proc.body->u.Block.stmts,
MakeSyncCoord(slownode->u.proc.body->u.Block.right_coord));
fastnode->u.proc.body->u.Block.stmts =
AppendItem(fastnode->u.proc.body->u.Block.stmts,
MakeSyncCoord(fastnode->u.proc.body->u.Block.right_coord));
}
if (node->u.proc.needs_return) {
slownode->u.proc.body->u.Block.stmts =
AppendItem(slownode->u.proc.body->u.Block.stmts,
MakeReturnCoord(NULL,
slownode->u.proc.body->u.Block.right_coord));
fastnode->u.proc.body->u.Block.stmts =
AppendItem(fastnode->u.proc.body->u.Block.stmts,
MakeReturnCoord(NULL,
fastnode->u.proc.body->u.Block.right_coord));
}
/* transform export body */
sync_count = 0;
version = Export;
exportnode->u.proc.decl = MakeExportDecl(u);
in_procedure = 1;
exportnode->u.proc.body = MakeExportBody(exportnode->u.proc.body, u);
in_procedure = 0;
SetCoords(exportnode->u.proc.decl, exportnode->coord, Subtree);
/* transform import body */
sync_count = 0;
version = Import;
importnode->u.proc.decl = MakeImportDecl(u);
in_procedure = 1;
importnode->u.proc.body = MakeImportBody(importnode->u.proc.body, u);
in_procedure = 0;
SetCoords(importnode->u.proc.decl, importnode->coord, Subtree);
/* transform fast body */
sync_count = 0;
version = Fast;
fastnode->u.proc.decl = TransformNode(fastnode->u.proc.decl);
in_procedure = 1;
fastnode->u.proc.body = TransformNode(fastnode->u.proc.body);
in_procedure = 0;
/* transform slow body */
sync_count = 0;
version = Slow;
/* add info for entry 0 */
link_initializers =
List1(MakeInitializer(
List5(IsVoidType(u->decl->u.decl.type->u.fdcl.returns) ?
MakeConstSint(0) :
MakeUnary(SIZEOF, NodeCopy(u->decl->u.decl.type->u.fdcl.returns, Subtree)),
MakeUnary(SIZEOF, MakeFrameType(proc_name)),
MakeId(MakeSlowProcName(proc_name)),
MakeConstSint(0),
MakeConstSint(0)
)
));
standalone_inlets = NULL;
slownode->u.proc.decl = TransformNode(slownode->u.proc.decl);
in_procedure = 1;
slownode->u.proc.body = TransformNode(slownode->u.proc.body);
in_procedure = 0;
/* add stuff to beginning of procedure */
fastnode->u.proc.body = AddFastStuff(fastnode->u.proc.body,
fastnode->u.proc.decl->u.decl.type->u.fdcl.args);
slownode->u.proc.body = AddSlowStuff(slownode->u.proc.body,
slownode->u.proc.decl->u.decl.type->u.fdcl.args);
/* EBA:
* remove inner inlet function of FAST clone.
* move inner inlet function of SLOW clone to global scope.
* change name of the inlet function that has now become global.
*/
version = Slow;
slownode = ExtractInletFunc(slownode,
&inlets_nodes,
&slow_inlets_original_name);
RenameCallsToInnerInletNames(slownode, slow_inlets_original_name);
version = Fast;
fastnode = ExtractInletFunc(fastnode,
&inlets_nodes,
&fast_inlets_original_name);
RenameCallsToInnerInletNames(fastnode, fast_inlets_original_name);
/* make slow decl */
/*
* cilk int foo(int x, int y) ==> void _foo_slow(_foo_frame *_frame)
*/
decl = MakeSlowDecl(proc_name);
SetCoords(decl, slownode->coord, Subtree);
slownode->u.proc.decl = decl;
/* make fast decl */
/*
* cilk int foo(int x, int y) ==> int _foo_fast(int x, int y)
*/
/* Just change the name */
fastnode->u.proc.decl->u.decl.name = MakeFastProcName( fastnode->u.proc.decl->u.decl.name );
/* set fast decl flag */
NodeUpdateTq(fastnode->u.proc.decl, tq_add_fast_procedure);
/* make slow procedure declaration */
result = AppendItem(result,
MakeSlowDecl(u->decl->u.decl.name));
/* make export procedure declaration */
/* result = AppendItem(result,
MakeExportDecl(u));
*/
/* add in standalone inlets */
result = JoinLists(result, standalone_inlets);
/* add linkage stuff */
result = AppendItem(result, MakeLinkage(node));
/*printf("TransformCilkProc - exportnode=%p exoprtnode->typ=%d\n", exportnode, exportnode->typ);*/
/*printf("TransformCilkProc - exoprtnode->decl=%p exoprtnode->decl->typ=%d\n", exportnode->u.proc.decl, exportnode->u.proc.decl->typ);*/
/*printf("TransformCilkProc - slownode->decl->typ=%d\n", slownode->u.proc.decl->typ);*/
result = JoinLists(result, inlets_nodes);
result = AppendItem(result, fastnode);
result = AppendItem(result, slownode);
result = AppendItem(result, importnode);
result = AppendItem(result, exportnode);
return result;
}
PRIVATE Node *TransformNode(Node *node)
{
if (node == NULL)
return NULL;
#define CODE(name, node, union) return Transform##name(node, union)
ASTSWITCH(node, CODE)
#undef CODE
UNREACHABLE;
return NULL;
}
GLOBAL List *TransformTopDecl(Node *node)
{
List *result;
if (!node)
return NULL;
if (node->typ == Proc &&
node->u.proc.decl->u.decl.type->typ == Fdcl &&
tq_has_procedure(node->u.proc.decl->u.decl.type->u.fdcl.tq)) {
/* cilk procedure */
result = TransformCilkProc(node, &node->u.proc);
} else
result = List1(TransformNode(node));
return (result);
}
GLOBAL List *TransformPass1(List *program)
{
ListMarker marker;
Node *node;
List *newprogram = NULL;
IterateList(&marker, program);
while (NextOnList(&marker, (GenericREF) & node)) {
newprogram = JoinLists(newprogram, TransformTopDecl(node));
}
return newprogram;
}
/*
* TransformProgram should convert a type-checked source language tree
* into a standard C tree. Type information does not need to be preserved,
* but all new Decl nodes must be properly annotated with their DECL_LOCATION
* (e.g. top-level, block, structure field, etc.).
*/
GLOBAL List *TransformProgram(List *program)
{
InitCilkTransform();
program = TransformPass1(program);
program = ConsItem(MakeText("#include <cilk-cilk2c.h>\n", TRUE),
program);
return program;
}
PRIVATE int operator_type_number(OpType assign_op, Node *type)
{
unsigned int operator = 0;
unsigned int type_num;
/* commutative operators have same op_num */
switch (assign_op) {
case PLUSassign:
case MINUSassign:
case PREINC:
case PREDEC:
case POSTINC:
case POSTDEC:
operator = 0;
break;
case MULTassign:
if (IsFloatingType(type))
operator = 1;
else
operator = 2;
break;
case DIVassign:
operator = 1;
break;
case ANDassign:
case ERassign:
case ORassign:
operator = 2;
break;
case LSassign:
case RSassign:
case MODassign:
case '=':
operator = 3;
break;
default:
FAIL("bad operator in operator_number");
}
if (IsIntegralType(type))
type_num = 0;
else if (IsFloatingType(type))
type_num = 1;
else if (IsPointerType(type))
type_num = 2;
else
type_num = 3;
assert(operator < 4);
assert(type_num < 4);
return ((type_num << 2) + operator);
}
PRIVATE void ClearCoord(Node *node)
{
node->coord = UnknownCoord;
#define CHILD(n) ClearCoord(n)
ASTWALK(node, CHILD)
#undef CHILD
}
PRIVATE Node *name_strip(Node *node)
{
Node *anode;
#define CHILD(n) n = name_strip(n)
ASTWALK(node, CHILD)
#undef CHILD
if ((node->typ == Unary) && (node->u.unary.op == INDIR)) {
anode = node->u.unary.expr;
if (anode->typ == Cast) {
anode = anode->u.cast.expr;
if ((anode->typ == Call) && (anode->u.call.name->typ == Id)) {
if ((strcmp(anode->u.call.name->u.id.text,
AccessReadProfileName) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessReadProfileName4) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessReadProfileName8) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileName) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileName4) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileName8) == 0))
return FirstItem(anode->u.call.args);
else if ((strcmp(anode->u.call.name->u.id.text,
AccessReadProfileAddrName) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessReadProfileAddrName4) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessReadProfileAddrName8) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileAddrName) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileAddrName4) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
AccessWriteProfileAddrName8) == 0) ||
(strcmp(anode->u.call.name->u.id.text,
SpawnVarProfileName) == 0))
return MakeUnary(INDIR, FirstItem(anode->u.call.args));
}
}
}
else if ((node->typ == Binop) && (node->u.binop.op == '.') &&
(node->u.binop.left->typ == Binop) &&
(node->u.binop.left->u.binop.op == ARROW) &&
(node->u.binop.left->u.binop.left->typ == Id) &&
(strcmp(node->u.binop.left->u.binop.left->u.id.text, "_frame") == 0))
return node->u.binop.right;
return node;
}
PRIVATE Node *AccessProfile(Node *node, Node *type, AccessProfileType accesstype, int withaddress, int opt, int multiple, int operator)
{
Node *call = NULL, *atype, *op_type_node, *var_node;
int size;
/*
if (!(node->memorycheckedp))
return node;
*/
if (!node)
return node;
/* for array, we are taking address of the array, no memory access.
for example, int a[2], and any use of a is no access of memory */
if (type->typ == Adcl)
return node;
/* if the real type of node is an array (though typedef), we convert
this into a pointer type.
for example, typedef int aa[10]; typedef aa *bb; bb y; then *y.
however, the cast type is unchanged, so *y=*((aa *)(y,sizeof(int *))).
The sizeof is correct for function call with argument *y because
we pass pointer rather than the whole array.
But the sizeof would be wrong if *y is used elsewhere (I couldn't
think of any other legal use (*y), so I leave it unconsidered */
atype = NodeCopy(NodeDataType(type), Subtree);
assert(atype);
if (atype->typ == Adcl)
atype = MakePtr(EMPTY_TQ, atype->u.adcl.type);
if (atype->typ == Ptr) {
assert(atype->u.ptr.type);
}
ClearCoord(atype);
assert(type);
if (type->typ == Ptr) {
assert(type->u.ptr.type);
}
ClearCoord(type);
size = NodeSizeof(node, atype, FALSE) * multiple;
op_type_node = MakeConstSint(operator_type_number(operator, atype));
var_node = name_strip(NodeCopy(node, Subtree));
switch (accesstype) {
case Read:
if (size == sizeof(int)) {
call = MakeId(withaddress ?
AccessReadProfileAddrName4 :
AccessReadProfileName4);
call = MakeCall(call, List3(node, op_type_node, var_node));
}
else if (size == sizeof(double)) {
call = MakeId(withaddress ?
AccessReadProfileAddrName8 :
AccessReadProfileName8);
call = MakeCall(call, List3(node, op_type_node, var_node));
}
else {
call = MakeId(withaddress ?
AccessReadProfileAddrName :
AccessReadProfileName);
call = MakeCall(call, List4(node, MakeConstSint(size), op_type_node,
var_node));
}
break;
case Write:
if (size == sizeof(int)) {
call = MakeId(withaddress ?
AccessWriteProfileAddrName4 :
AccessWriteProfileName4);
call = MakeCall(call, List3(node, op_type_node, var_node));
}
else if (size == sizeof(double)) {
call = MakeId(withaddress ?
AccessWriteProfileAddrName8 :
AccessWriteProfileName8);
call = MakeCall(call, List3(node, op_type_node, var_node));
}
else {
call = MakeId(withaddress ?
AccessWriteProfileAddrName :
AccessWriteProfileName);
call = MakeCall(call, List4(node, MakeConstSint(size), op_type_node,
var_node));
}
break;
default:
FAIL("bad access type in AccessProfile");
}
if (opt == 0) {
call = MakeCast(MakePtr(EMPTY_TQ, type), call);
call->parenthesized = 1;
if (!withaddress) {
call = MakeUnary(INDIR, call);
call->u.unary.type = type;
call->parenthesized = 1;
}
call->coord = node->coord;
}
return call;
}
PRIVATE Node *SpawnVarProfile(Node *node, Node *type, OpType assign_op)
{
Node *var_node;
/*
if (node->memorycheckedp)
return node;
*/
if (!node)
return node;
assert(type);
type = NodeDataType(type);
assert(type);
var_node = name_strip(NodeCopy(node, Subtree));
return MakeCall(MakeId(SpawnVarProfileName),
List5(node,
MakeConstSint(NodeSizeof(node, type, FALSE)),
MakeConstSint(
operator_type_number(assign_op, type)),
MakeCast(MakePtr(EMPTY_TQ,
MakeGenericFrameType()),
MakeId(FrameName)),
var_node));
/* Could be*/
/* ParseWildcardStringNode("%d1(%e1, %e2, %e3, (%t1)%d2, %e4);",*/
/* SpawnVarProfileName,*/
/* node,*/
/* MakeConstSint(NodeSizeof(node, type, FALSE)),*/
/* MakeConstSint(operator_type_nmber(assign_op, type))*/
/* MakePtr(EMPTY_TQ, MakeGenericFrameType())*/
/* FrameName,*/
/* var_node);*/
}
/*
* similar routine as AnalyzeGlobalReadWrite in analyze.c.
* use bottom-up tree-search to find all frame reference.
* called in AnalyzeVariables after the kind of Id is analyzed.
* node->nondeterminator is TRUE if node potentially accesses shared location.
*/
PRIVATE void AnalyzeFrameReadWrite(Node *node)
{
switch (node->typ) {
case Id:
if (node->u.id.decl && ((node->u.id.decl->u.decl.kind == 2) ||
(node->u.id.decl->u.decl.kind == 3)))
node->nondeterminator = TRUE;
break;
default:
break;
}
#define CODE(n) AnalyzeFrameReadWrite(n)
ASTWALK(node, CODE)
#undef CODE
switch (node->typ) {
case Array:
if (node->u.array.name->nondeterminator) {
node->nondeterminator = TRUE;
node->u.array.name->nondeterminator = FALSE;
}
break;
case Binop:
if (IsAssignmentOp(node->u.binop.op) &&
node->u.binop.left->nondeterminator) {
node->nondeterminator = TRUE;
node->u.binop.left->nondeterminator = FALSE;
}
else if ((node->u.binop.op == '.') &&
node->u.binop.left->nondeterminator) {
node->nondeterminator = TRUE;
node->u.binop.left->nondeterminator = FALSE;
}
break;
case Unary:
if (IsIncDecOp(node->u.unary.op) && node->u.unary.expr->nondeterminator) {
/*
if ((node->u.unary.expr->typ == Id) &&
(node->u.unary.expr->u.id.decl->u.decl.kind == 3))
node->u.unary.expr->nondeterminator = FALSE;
*/
node->nondeterminator = TRUE;
node->u.unary.expr->nondeterminator = FALSE;
}
else if (node->u.unary.op == ADDRESS) {
node->nondeterminator = FALSE;
node->u.unary.expr->nondeterminator = FALSE;
}
break;
case Spawn:
if (node->u.spawn.receiver && node->u.spawn.receiver->nondeterminator) {
node->u.spawn.receiver->nondeterminator = FALSE;
}
break;
case InletCall:
break;
default:
break;
}
}
| 30.248958 | 185 | 0.612334 |
0cb5558fd712cd9664d2840e0dfa1433d69b0ae5 | 7,491 | py | Python | CameraCalibration.py | lsmanoel/StereoVision | 22e9a422a217290e6fb2b71afc663db87e530842 | [
"MIT"
] | null | null | null | CameraCalibration.py | lsmanoel/StereoVision | 22e9a422a217290e6fb2b71afc663db87e530842 | [
"MIT"
] | null | null | null | CameraCalibration.py | lsmanoel/StereoVision | 22e9a422a217290e6fb2b71afc663db87e530842 | [
"MIT"
] | null | null | null |
import numpy as np
import cv2
import glob
from matplotlib import pyplot as plt
class CameraCalibration():
def __init__(self):
pass
# ===========================================================
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def find_chess(frame_input, chess_size=(6, 6)):
status = None
print("chess...")
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((chess_size[0]*chess_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:chess_size[0], 0:chess_size[1]].T.reshape(-1, 2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(frame_gray, (chess_size[0], chess_size[1]), None)
# If found, add object points, image points (after refining them)
frame_output = None
if ret == True:
status = "checkmate!"
print(status)
objpoints.append(objp)
corners2 = cv2.cornerSubPix(frame_gray,
corners,
(11, 11),
(-1, -1),
criteria)
imgpoints.append(corners2)
# Draw and display the corners
frame_output = cv2.drawChessboardCorners(frame_input, (chess_size[0], chess_size[1]), corners2, ret)
plt.imshow(frame_output)
plt.show()
if frame_output is None:
frame_output = frame_input
return frame_output, objpoints, imgpoints, status
# ===========================================================
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def calibrateCoefficients(frame_input, objpoints, imgpoints):
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints,
imgpoints,
frame_input.shape[::-1],
None,
None)
tot_error = 0
mean_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2)
tot_error += error
print("total error: ", mean_error/len(objpoints))
return ret, mtx, dist, rvecs, tvecs
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def testbench(video_source=2):
capture = cv2.VideoCapture(video_source)
count_frame = 0
while 1:
# ++++++++++++++++++++++++++++++++++++++++++++++++
print('calibrate state...')
status = None
while status is None:
status = None
ret, frame_input = capture.read()
print(count_frame)
count_frame += 1
frame_chess, objpoints, imgpoints, status = CameraCalibration.find_chess(frame_input)
plt.imshow(frame_chess)
plt.show()
# ++++++++++++++++++++++++++++++++++++++++++++++++
frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY)
plt.imshow(frame_gray)
plt.show()
ret, mtx, dist, rvecs, tvecs = CameraCalibration.calibrateCoefficients(frame_gray, objpoints, imgpoints)
h, w = frame_gray.shape[:2]
newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
# ++++++++++++++++++++++++++++++++++++++++++++++++
print('test state...')
while 1:
ret, frame_input = capture.read()
frame_gray = cv2.cvtColor(frame_input,cv2.COLOR_BGR2GRAY)
h, w = frame_gray.shape[:2]
newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
frame_undist = cv2.undistort(frame_input, mtx, dist, None, newcameramtx)
x,y,w,h = roi
print(x,y,w,h)
# frame_undist = frame_undist[y:y+h, x:x+w]
frame_concat = np.concatenate((frame_undist, frame_input), axis=1)
plt.imshow(frame_concat)
plt.show()
# ----------------------------------------------------------
# Esc -> EXIT while
# while 1:
# k = cv2.waitKey(1) & 0xff
# if k ==13 or k==27:
# break
# if k == 27:
# break
# ----------------------------------------------------------
capture.release()
cv2.destroyAllWindows()
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
@staticmethod
def getPhoto(video_source=0):
capture = cv2.VideoCapture(video_source)
while 1:
ret, frame_input = capture.read()
frame_line = frame_input
frame_output = cv2.line(frame_line,
(0, frame_line.shape[0]//2),
(frame_line.shape[1], frame_line.shape[0]//2),
(255,0,0),
1)
frame_output = cv2.line(frame_line,
(frame_line.shape[1]//2, 0),
(frame_line.shape[1]//2, frame_line.shape[0]),
(255,0,0),
1)
cv2.imshow("Video", frame_line)
# ------------------------------------------------------------------------------------------------------------------
# Esc -> EXIT while
k = cv2.waitKey(30) & 0xff
if k == 27:
break
# ------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------------------------------------
ret, frame_input = capture.read()
frame_input = cv2.cvtColor(frame_input, cv2.COLOR_BGR2RGB)
plt.imshow(frame_input)
plt.xticks([])
plt.yticks([])
plt.show()
# ----------------------------------------------------------------------------------------------------------------------
capture.release()
cv2.destroyAllWindows()
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
# CameraCalibration.testbench(video_source=2) | 39.015625 | 128 | 0.394206 |
954c58dc83cf867d9d2e6bfa6bd9927d54f8c47b | 1,652 | css | CSS | assets/css/country.css | katylorny/table | fe102f8a031ff3973ae6a1fed85021f0ad607040 | [
"BSD-3-Clause"
] | null | null | null | assets/css/country.css | katylorny/table | fe102f8a031ff3973ae6a1fed85021f0ad607040 | [
"BSD-3-Clause"
] | null | null | null | assets/css/country.css | katylorny/table | fe102f8a031ff3973ae6a1fed85021f0ad607040 | [
"BSD-3-Clause"
] | null | null | null | .country-wrapper {
height: 350px;
overflow-y: auto;
position: relative;
/*border-bottom: 1px solid #ddd;*/
border-radius: 8px;
box-shadow: 0 0 13px 5px rgba(0, 0, 0, 0.2);
color: #898A86;
}
.country-wrapper .summary {
display: none;
}
.country-wrapper table {
margin: 0;
}
.country-wrapper table th {
position: sticky;
top: -1px;
z-index: 20;
background-color: #6C7AE0;
color: white;
}
.country-wrapper table td {
color: #898A86;
border-color: transparent;
}
.country-wrapper table th a {
color: white;
}
.country-wrapper .simplebar-scrollbar::before {
background-color: red;
}
.country-wrapper .simplebar-track {
background-color: rgba(0, 0, 0, 0.05);
}
.country-wrapper .simplebar-track.simplebar-vertical {
top: 40px;
}
.country-wrapper [data-simplebar] {
z-index: 22;
}
.simplebar-track.simplebar-vertical .simplebar-scrollbar:before {
left: 0;
right: 0;
/*height: 100px;*/
background-color: rgba(0, 0, 0, 0.2);
}
.simplebar-track.simplebar-vertical {
width: 7px;
right: 1px;
}
.table-striped > tbody > tr:nth-of-type(odd) {
background-color: #F8F6FF;
}
.table-bordered > thead > tr > th, .table-bordered > tbody > tr > th, .table-bordered > tfoot > tr > th, .table-bordered > thead > tr > td, .table-bordered > tbody > tr > td, .table-bordered > tfoot > tr > td {
border: none !important;
}
.table > thead > tr > th, .table > tbody > tr > th, .table > tfoot > tr > th, .table > thead > tr > td, .table > tbody > tr > td, .table > tfoot > tr > td {
border-top: none !important;
padding-left: 37px !important;
} | 22.026667 | 210 | 0.624092 |
7a3f2214a50f9aceff3edcc5cdfab5f63c23097c | 672 | kt | Kotlin | src/main/kotlin/com/bftcom/democrud/graphql/PersonMutation.kt | Shaposhnikov-Alexey/democrud | 94b094a423b763a05078a8ebcd034124e395b6e7 | [
"MIT"
] | null | null | null | src/main/kotlin/com/bftcom/democrud/graphql/PersonMutation.kt | Shaposhnikov-Alexey/democrud | 94b094a423b763a05078a8ebcd034124e395b6e7 | [
"MIT"
] | null | null | null | src/main/kotlin/com/bftcom/democrud/graphql/PersonMutation.kt | Shaposhnikov-Alexey/democrud | 94b094a423b763a05078a8ebcd034124e395b6e7 | [
"MIT"
] | null | null | null | package com.bftcom.democrud.graphql
import com.bftcom.democrud.model.PersonRepository
import com.expediagroup.graphql.server.operations.Mutation
import org.springframework.stereotype.Component
@Component
class PersonMutation(val personRepository: PersonRepository) : Mutation {
fun addPerson(name: String, lastName: String): Boolean = personRepository.savePerson(name, lastName)
fun addPersonWithEmail(name: String, lastName: String, email: String): Boolean =
personRepository.savePerson(name, lastName, email)
fun deletePerson(id: Int): Boolean {
personRepository.deleteById(id)
return personRepository.findById(id).isEmpty
}
} | 37.333333 | 104 | 0.776786 |
c3a7c86be06eaa6d4287fd7885743754fe92afb9 | 4,217 | swift | Swift | Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift | dpassage/advent2018 | c22d892a37b532667e5c50a4e16b49c70e38ad51 | [
"BSD-2-Clause"
] | null | null | null | Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift | dpassage/advent2018 | c22d892a37b532667e5c50a4e16b49c70e38ad51 | [
"BSD-2-Clause"
] | null | null | null | Advent2018.playground/Pages/Day 4 - Repose Record.xcplaygroundpage/Contents.swift | dpassage/advent2018 | c22d892a37b532667e5c50a4e16b49c70e38ad51 | [
"BSD-2-Clause"
] | null | null | null | //: [Previous](@previous)
import Foundation
import AdventLib
let testInput = """
[1518-11-01 00:00] Guard #10 begins shift
[1518-11-01 00:05] falls asleep
[1518-11-01 00:25] wakes up
[1518-11-01 00:30] falls asleep
[1518-11-01 00:55] wakes up
[1518-11-01 23:58] Guard #99 begins shift
[1518-11-02 00:40] falls asleep
[1518-11-02 00:50] wakes up
[1518-11-03 00:05] Guard #10 begins shift
[1518-11-03 00:24] falls asleep
[1518-11-03 00:29] wakes up
[1518-11-04 00:02] Guard #99 begins shift
[1518-11-04 00:36] falls asleep
[1518-11-04 00:46] wakes up
[1518-11-05 00:03] Guard #99 begins shift
[1518-11-05 00:45] falls asleep
[1518-11-05 00:55] wakes up
""".components(separatedBy: "\n")
struct Sleep {
var start: Int
var end: Int
var length: Int { return end - start }
}
struct Guard {
var sleeps: [Sleep] = []
mutating func startSleeping(at: Int) {
let newSleep = Sleep(start: at, end: Int.max)
sleeps.append(newSleep)
}
mutating func stopSleeping(at: Int) {
sleeps[sleeps.count - 1].end = at
}
var totalSleeps: Int { return sleeps.reduce(0, { return $0 + $1.length }) }
func sleepiestMinute() -> (minute: Int, sleeps: Int) {
var minutes: [Int: Int] = [:]
for sleep in sleeps {
for minute in sleep.start ..< sleep.end {
minutes[minute, default: 0] += 1
}
}
let keyValue = minutes.sorted { $0.value > $1.value }.first!
return (minute: keyValue.key, sleeps: keyValue.value)
}
}
struct GuardSet {
var guards: [Int: Guard] = [:]
subscript(id: Int) -> Guard {
get { return guards[id] ?? Guard() }
set { guards[id] = newValue }
}
init(lines: [Line]) {
var currentGuard = -1
for line in lines {
switch line {
case let .newGuard(id: id): currentGuard = id
case let .startSleep(at: minute): guards[currentGuard, default: Guard()].startSleeping(at: minute)
case let .endSleep(at: minute): guards[currentGuard, default: Guard()].stopSleeping(at: minute)
}
}
}
}
enum Line {
case newGuard(id: Int)
case startSleep(at: Int)
case endSleep(at: Int)
private static let newGuardRegex = try! Regex(pattern: ".* Guard #(\\d+) begins shift")
private static let startSleepRegex = try! Regex(pattern: "\\[.*:(\\d\\d)] falls asleep")
private static let endSleepRegex = try! Regex(pattern: "\\[.*:(\\d\\d)] wakes up")
init?(text: String) {
if let matches = Line.newGuardRegex.match(input: text),
let id = Int(matches[0]) {
self = .newGuard(id: id)
} else if let matches = Line.startSleepRegex.match(input: text),
let minute = Int(matches[0]) {
self = .startSleep(at: minute)
} else if let matches = Line.endSleepRegex.match(input: text),
let minute = Int(matches[0]) {
self = .endSleep(at: minute)
} else {
return nil
}
}
}
let testLines = testInput.compactMap { Line(text: $0) }
print(testLines)
func strategyOne(lines: [Line]) -> Int {
let guardSet = GuardSet(lines: lines)
let sleepiestGuard = guardSet.guards.sorted { $0.value.totalSleeps > $1.value.totalSleeps }.first!
let sleepiestGuardId = sleepiestGuard.key
let sleepiestMinute = sleepiestGuard.value.sleepiestMinute()
return sleepiestGuardId * sleepiestMinute.minute
}
print(strategyOne(lines: testLines))
let url = Bundle.main.url(forResource: "day4.input", withExtension: "txt")!
let day4Input = try! String(contentsOf: url).components(separatedBy: "\n").sorted()
let day4Lines = day4Input.compactMap { Line(text: $0) }
print(strategyOne(lines: day4Lines))
func strategyTwo(lines: [Line]) -> Int {
let guardSet = GuardSet(lines: lines)
let guardSleepiestMinutes = guardSet.guards.mapValues { $0.sleepiestMinute() }
let guardWithSleepiestMinute = guardSleepiestMinutes.sorted { $0.value.sleeps > $1.value.sleeps }.first!
return guardWithSleepiestMinute.key * guardWithSleepiestMinute.value.minute
}
print(strategyTwo(lines: testLines))
print(strategyTwo(lines: day4Lines))
//: [Next](@next)
| 29.907801 | 110 | 0.631729 |
c7ee31ca44090e6b285a3f692a5e9ebafb790c6a | 1,447 | java | Java | app/src/main/java/com/myhailov/mykola/fishpay/activities/charity/CharitySuccessActivity.java | mykola-myhailov/fishpay-android | e4f74bc7afca303cf547ed09009324d1be052189 | [
"MIT"
] | null | null | null | app/src/main/java/com/myhailov/mykola/fishpay/activities/charity/CharitySuccessActivity.java | mykola-myhailov/fishpay-android | e4f74bc7afca303cf547ed09009324d1be052189 | [
"MIT"
] | null | null | null | app/src/main/java/com/myhailov/mykola/fishpay/activities/charity/CharitySuccessActivity.java | mykola-myhailov/fishpay-android | e4f74bc7afca303cf547ed09009324d1be052189 | [
"MIT"
] | null | null | null | package com.myhailov.mykola.fishpay.activities.charity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.myhailov.mykola.fishpay.R;
import com.myhailov.mykola.fishpay.activities.BaseActivity;
import com.myhailov.mykola.fishpay.activities.CharityActivity;
import static com.myhailov.mykola.fishpay.utils.Keys.CHARITY_ID;
public class CharitySuccessActivity extends BaseActivity {
TextView tvLink;
String id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_charity_success);
Bundle extras = getIntent().getExtras();
if (extras != null) {
id = extras.getString(CHARITY_ID);
}
findViewById(R.id.tv_to_work).setOnClickListener(this);
tvLink = findViewById(R.id.tv_link);
tvLink.setText(getString(R.string.charity_link, id));
tvLink.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_to_work:
Intent intent = new Intent(context, CharityActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
break;
case R.id.tv_link:
break;
}
}
}
| 30.787234 | 97 | 0.674499 |
4fa814aa1132d79e7ee3bdad430b88ee254ff701 | 2,811 | swift | Swift | ContactSyncing/Helpers/Extensions/RACTerminal.swift | bastienFalcou/ContactSync | 9263e0dbd0e5060c63e29fb58d2fe708b27158c0 | [
"MIT"
] | 3 | 2020-12-13T08:46:19.000Z | 2021-07-09T11:56:55.000Z | ContactSyncing/Helpers/Extensions/RACTerminal.swift | bastienFalcou/ContactSync | 9263e0dbd0e5060c63e29fb58d2fe708b27158c0 | [
"MIT"
] | null | null | null | ContactSyncing/Helpers/Extensions/RACTerminal.swift | bastienFalcou/ContactSync | 9263e0dbd0e5060c63e29fb58d2fe708b27158c0 | [
"MIT"
] | null | null | null | //
// RACTerminal.swift
// Owners
//
// Created by Ravindra Soni on 25/05/2016.
// Copyright © 2016 Fueled. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import DataSource
import Result
extension Reactive where Base: NSObject {
func target<U>(_ action: @escaping (Base, U) -> Void) -> BindingTarget<U> {
return BindingTarget(on: ImmediateScheduler(), lifetime: lifetime) {
[weak base = self.base] value in
if let base = base {
action(base, value)
}
}
}
}
extension Reactive where Base: UIViewController {
var title: BindingTarget<String> {
return target { $0.title = $1 }
}
}
extension Reactive where Base: UISwitch {
var isOn: BindingTarget<Bool> {
return target { $0.isOn = $1 }
}
}
extension Reactive where Base: UIView {
var isHidden: BindingTarget<Bool> {
return target { $0.isHidden = $1 }
}
var backgroundColor: BindingTarget<UIColor> {
return target { $0.backgroundColor = $1 }
}
var borderWidth: BindingTarget<CGFloat> {
return target { $0.layer.borderWidth = $1 }
}
}
extension Reactive where Base: UILabel {
var textColor: BindingTarget<UIColor> {
return target { $0.textColor = $1 }
}
var attributedText: BindingTarget<NSAttributedString> {
return target { $0.attributedText = $1 }
}
}
extension Reactive where Base: UITextField {
var text: BindingTarget<String> {
return target { $0.text = $1 }
}
var placeholder: BindingTarget<String> {
return target { $0.placeholder = $1 }
}
}
extension Reactive where Base: UISearchBar {
var text: BindingTarget<String> {
return target { $0.text = $1 }
}
}
extension Reactive where Base: UINavigationBar {
var barTintColor: BindingTarget<UIColor> {
return target { $0.barTintColor = $1 }
}
}
extension Reactive where Base: UIControl {
var isSelected: BindingTarget<Bool> {
return target { $0.isSelected = $1 }
}
}
extension Reactive where Base: UIBarButtonItem {
var isEnabled: BindingTarget<Bool> {
return target { $0.isEnabled = $1 }
}
var title: BindingTarget<String> {
return target { $0.title = $1 }
}
}
extension Reactive where Base: UISegmentedControl {
var selectedSegmentIndex: BindingTarget<Int> {
return target { $0.selectedSegmentIndex = $1 }
}
}
extension Reactive where Base: UITableView {
var setEditing: BindingTarget<Bool> {
return target { $0.setEditing($1, animated: true) }
}
var showSeparator: BindingTarget<Bool> {
return target { $0.separatorStyle = $1 ? .singleLine : .none }
}
}
extension Reactive where Base: UICollectionView {
var reloadData: BindingTarget<Bool> {
return target { if $1 { $0.reloadData() } }
}
}
extension Reactive where Base: UITableViewCell {
var setEditing: BindingTarget<(editing: Bool, animated: Bool)> {
return target { $0.setEditing($1.0, animated: $1.1) }
}
}
| 22.853659 | 76 | 0.698684 |
4a4e0d65e47daeca2407284e5e95dfd0a4a5bda7 | 243 | js | JavaScript | lib/dupes/filterDupes.js | jonschlinkert/extract-components | 26909d1073d4aee98bf947e2e5719fabf0f630a1 | [
"MIT"
] | 1 | 2021-04-12T23:10:40.000Z | 2021-04-12T23:10:40.000Z | lib/dupes/filterDupes.js | jonschlinkert/extract-components | 26909d1073d4aee98bf947e2e5719fabf0f630a1 | [
"MIT"
] | null | null | null | lib/dupes/filterDupes.js | jonschlinkert/extract-components | 26909d1073d4aee98bf947e2e5719fabf0f630a1 | [
"MIT"
] | null | null | null | const _ = require('lodash');
module.exports = function(val, arr) {
_.filter(_.keys(val), function (key) {
return val[key] > 1;
});
_.filter(val, function (key) {
return arr[key] && arr[key].length !== 0;
});
return arr;
};
| 18.692308 | 45 | 0.576132 |
4e83dc7ba6d0a1827ad1b150532f20b0b9332bea | 879 | asm | Assembly | oeis/268/A268093.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/268/A268093.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/268/A268093.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A268093: Number of 1 X n 0..2 arrays with every repeated value in every row not one larger and in every column one larger mod 3 than the previous repeated value, and upper left element zero.
; Submitted by Christian Krause
; 1,3,9,26,74,208,580,1608,4440,12224,33584,92128,252448,691200,1891392,5173376,14145920,38671360,105700096,288873984,789410304,2157092864,5894054912,16104392704,44001089536,120219353088,328457662464,897387585536,2451757604864,6698424598528,18300632842240,49998651752448,136599642931200,373198736850944,1019601054531584,2785608172699648,7610435634331648,20792121973800960,56805183935741952,155194749258039296,424000141265469440,1158390330802831360,3164782043648229376,8646346947925377024
mov $1,2
mov $2,1
mov $4,1
lpb $0
sub $0,1
mul $1,2
mov $3,$2
mul $2,2
add $3,$4
mov $4,$1
add $1,$3
lpe
mul $1,2
sub $1,4
div $1,4
add $1,1
mov $0,$1
| 39.954545 | 487 | 0.796359 |
2884eefb2b5268bf40ea0b324c53391d9016c7dd | 322 | rb | Ruby | test/integration/postgresql/serverspec/redis_spec.rb | maoueh/cookbook-gitlab | 4167ec60fcd24bd4143ccdbcb81dbc95043d31af | [
"MIT"
] | null | null | null | test/integration/postgresql/serverspec/redis_spec.rb | maoueh/cookbook-gitlab | 4167ec60fcd24bd4143ccdbcb81dbc95043d31af | [
"MIT"
] | null | null | null | test/integration/postgresql/serverspec/redis_spec.rb | maoueh/cookbook-gitlab | 4167ec60fcd24bd4143ccdbcb81dbc95043d31af | [
"MIT"
] | null | null | null | require 'spec_helper'
describe 'Redis Database' do
describe file('/var/run/redis/sockets/redis.sock') do
it { should be_socket }
it { should be_owned_by('redis') }
it { should be_grouped_into('git') }
end
it 'has a running service named redis0' do
expect(service('redis0')).to be_running
end
end
| 23 | 55 | 0.689441 |