code
stringlengths
4
1.01M
language
stringclasses
2 values
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BB.Poker.WinFormsClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BB.Poker.WinFormsClient")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9703352c-1cab-4c2a-bbc9-183b9245edc6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CharacterModelLib.Models { public class CharacterProject : NotifyableBase { public CharacterProject() { characterCollection = new ObservableCollection<Character>(); } void characterCollection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { RaisePropertyChanged("CharacterCollection"); } Character selectedCharacter; public Character SelectedCharacter { get { return selectedCharacter; } set { if (selectedCharacter != null) { selectedCharacter.PropertyChanged -= selectedCharacter_PropertyChanged; } selectedCharacter = value; if (selectedCharacter != null) { selectedCharacter.PropertyChanged += selectedCharacter_PropertyChanged; } RaisePropertyChanged("SelectedCharacter"); RaisePropertyChanged("NextCharacter"); RaisePropertyChanged("PreviousCharacter"); } } public Character NextCharacter { get { if (selectedCharacter == null) { return CharacterCollection[0]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index >= CharacterCollection.Count - 1) { return CharacterCollection[0]; } else { return CharacterCollection[index + 1]; } } } public Character PreviousCharacter { get { if (selectedCharacter == null) { return CharacterCollection[CharacterCollection.Count - 1]; } int index = CharacterCollection.IndexOf(selectedCharacter); if (index <= 0) { return CharacterCollection[CharacterCollection.Count - 1]; } else { return CharacterCollection[index - 1]; } } } private void selectedCharacter_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { RaisePropertyChanged("SelectedCharacter." + e.PropertyName); //RaisePropertyChanged(e.PropertyName); //RaisePropertyChanged("SelectedCharacter"); } private ObservableCollection<Character> characterCollection; public ObservableCollection<Character> CharacterCollection { get { return characterCollection; } set { if (characterCollection != null) { characterCollection.CollectionChanged -= characterCollection_CollectionChanged; } characterCollection = value; if (characterCollection != null) { characterCollection.CollectionChanged += characterCollection_CollectionChanged; } RaisePropertyChanged("CharacterCollection"); } } private string name; public string Name { get { return name; } set { name = value; RaisePropertyChanged("Name"); } } private string projectPath; public string ProjectPath { get { return projectPath; } set { projectPath = value; RaisePropertyChanged("ProjectPath"); } } public override string ToString() { return base.ToString() + ": Name=" + Name; } public override bool Equals(object obj) { if (obj.GetType() == this.GetType()) { return ((obj as CharacterProject).Name == this.Name); } return false; } public override int GetHashCode() { return base.GetHashCode(); } } }
Java
import uuid from django.db import models from django.conf import settings from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import BaseUserManager from django.utils import timezone from accelerator_abstract.models import BaseUserRole from accelerator_abstract.models.base_base_profile import EXPERT_USER_TYPE MAX_USERNAME_LENGTH = 30 class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): """ Creates and saves an User with the given email and password. """ now = timezone.now() if not email: raise ValueError('An email address must be provided.') email = self.normalize_email(email) if "is_active" not in extra_fields: extra_fields["is_active"] = True if "username" not in extra_fields: # For now we need to have a unique id that is at # most 30 characters long. Using uuid and truncating. # Ideally username goes away entirely at some point # since we're really using email. If we have to keep # username for some reason then we could switch over # to a string version of the pk which is guaranteed # be unique. extra_fields["username"] = str(uuid.uuid4())[:MAX_USERNAME_LENGTH] user = self.model(email=email, is_staff=is_staff, is_superuser=is_superuser, last_login=None, date_joined=now, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_user(self, email=None, password=None, **extra_fields): return self._create_user(email, password, False, False, **extra_fields) def create_superuser(self, email, password, **extra_fields): return self._create_user(email, password, True, True, **extra_fields) class User(AbstractUser): # Override the parent email field to add uniqueness constraint email = models.EmailField(blank=True, unique=True) objects = UserManager() class Meta: db_table = 'auth_user' managed = settings.ACCELERATOR_MODELS_ARE_MANAGED def __init__(self, *args, **kwargs): super(User, self).__init__(*args, **kwargs) self.startup = None self.team_member = None self.profile = None self.user_finalist_roles = None class AuthenticationException(Exception): pass def __str__(self): return self.email def full_name(self): fn = self.first_name ln = self.last_name if fn and ln: name = u"%s %s" % (fn, ln) else: name = str(self.email) return name def user_phone(self): return self._get_profile().phone def image_url(self): return self._get_profile().image_url() def team_member_id(self): return self.team_member.id if self._get_member() else '' def user_title(self): return self._get_title_and_company()['title'] def user_twitter_handle(self): return self._get_profile().twitter_handle def user_linked_in_url(self): return self._get_profile().linked_in_url def user_facebook_url(self): return self._get_profile().facebook_url def user_personal_website_url(self): return self._get_profile().personal_website_url def type(self): return self._get_profile().user_type def startup_name(self): return self._get_title_and_company()['company'] def _get_title_and_company(self): if self._is_expert() and self._has_expert_details(): profile = self._get_profile() title = profile.title company = profile.company return { "title": title, "company": company } self._get_member() title = self.team_member.title if self.team_member else "" company = self.startup.name if self._get_startup() else None return { "title": title, "company": company } def _has_expert_details(self): if self._is_expert(): profile = self._get_profile() return True if profile.title or profile.company else False def startup_industry(self): return self.startup.primary_industry if self._get_startup() else None def top_level_startup_industry(self): industry = ( self.startup.primary_industry if self._get_startup() else None) return industry.parent if industry and industry.parent else industry def startup_status_names(self): if self._get_startup(): return [startup_status.program_startup_status.startup_status for startup_status in self.startup.startupstatus_set.all()] def finalist_user_roles(self): if not self.user_finalist_roles: finalist_roles = BaseUserRole.FINALIST_USER_ROLES self.user_finalist_roles = self.programrolegrant_set.filter( program_role__user_role__name__in=finalist_roles ).values_list('program_role__name', flat=True).distinct() return list(self.user_finalist_roles) def program(self): return self.startup.current_program() if self._get_startup() else None def location(self): program = self.program() return program.program_family.name if program else None def year(self): program = self.program() return program.start_date.year if program else None def is_team_member(self): return True if self._get_member() else False def _get_startup(self): if not self.startup: self._get_member() if self.team_member: self.startup = self.team_member.startup return self.startup def _get_member(self): if not self.team_member: self.team_member = self.startupteammember_set.last() return self.team_member def _get_profile(self): if self.profile: return self.profile self.profile = self.get_profile() return self.profile def has_a_finalist_role(self): return len(self.finalist_user_roles()) > 0 def _is_expert(self): profile = self._get_profile() return profile.user_type == EXPERT_USER_TYPE.lower()
Java
from setuptools import setup, find_packages from codecs import open import os def read(*paths): """Build a file path from *paths* and return the contents.""" with open(os.path.join(*paths), 'r') as f: return f.read() setup( name='transposer', version='0.0.3', description='Transposes columns and rows in delimited text files', long_description=(read('README.rst')), url='https://github.com/keithhamilton/transposer', author='Keith Hamilton', maintainer='Keith Hamilton', maintainer_email='the.keith.hamilton@gmail.com', license='BSD License', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Office/Business' ], keywords='text, csv, tab-delimited, delimited, excel, sheet, spreadsheet', packages=find_packages(exclude=['contrib', 'docs', 'test*', 'bin', 'include', 'lib', '.idea']), install_requires=[], package_data={}, data_files=[], entry_points={ 'console_scripts': [ 'transposer=transposer.script.console_script:main' ] } )
Java
package experiments; import java.io.File; import java.util.Arrays; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import data.StateImpl; import datahandler.word2vec.MedicalSequenceIterator; import state2vec.State2Vec; public class State2VecTest { protected static final Logger logger = LoggerFactory.getLogger(State2VecTest.class); public State2VecTest(File file, String run) throws Exception { List<Integer> windowSizes; List<Double> learningRates; if(run.equals("0")){ logger.info("Run 0"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.025, 0.1); } else if(run.equals("1")) { logger.info("Run 1"); windowSizes = Arrays.asList(5); learningRates = Arrays.asList(0.1); } else if(run.equals("2")) { logger.info("Run 2"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.025); } else if(run.equals("3")) { logger.info("Run 3"); windowSizes = Arrays.asList(10); learningRates = Arrays.asList(0.1); } else if(run.equals("4")) { logger.info("Run 4"); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.025); } else { logger.info("Run " + run); windowSizes = Arrays.asList(15); learningRates = Arrays.asList(0.1); } //List<Integer> windowSizes = Arrays.asList(5, 10, 15); //List<Double> learningRates = Arrays.asList(0.025, 0.1); List<Integer> vectorLengths = Arrays.asList(50, 100); List<Integer> minWordFreqs = Arrays.asList(5, 10); int batchsize = 500; int epoch = 1; MedicalSequenceIterator<StateImpl> sequenceIterator = new MedicalSequenceIterator<StateImpl>(file, false); for(int windowSize: windowSizes) { for(double learningRate: learningRates) { for(int vectorLength: vectorLengths) { for(int minWordFreq: minWordFreqs) { logger.info("STATE2VEC - EXPERIMENT"); logger.info(""); logger.info("==PARAMETERS=="); logger.info("windowSize: " + windowSize); logger.info("learningRate: " + learningRate); logger.info("vectorLength: " + vectorLength); logger.info("batchSize: " + batchsize); logger.info("epoch: " + epoch); logger.info("minWordFreq: " + minWordFreq); logger.info(""); sequenceIterator.reset(); State2Vec state2vec = new State2Vec(); state2vec.trainSequenceVectors(sequenceIterator, windowSize, learningRate, vectorLength, batchsize, epoch, minWordFreq); List<Integer> ks = Arrays.asList(100, 1000, 5000); ClusterSeqTest clusterTest = new ClusterSeqTest(); for(int k: ks) { ResultWriter writer1 = new ResultWriter("State2Vec - ", "Cluster1Test"); writer1.writeLine("STATE2VEC - EXPERIMENT"); writer1.writeLine(""); writer1.writeLine("==PARAMETERS=="); writer1.writeLine("windowSize: " + windowSize); writer1.writeLine("learningRate: " + learningRate); writer1.writeLine("vectorLength: " + vectorLength); writer1.writeLine("batchSize: " + batchsize); writer1.writeLine("epoch: " + epoch); writer1.writeLine("minWordFreq: " + minWordFreq); writer1.writeLine(""); clusterTest.checkClusters1(state2vec.getTrainedModel(), k, writer1); ResultWriter writer2 = new ResultWriter("State2Vec - ", "Cluster2Test"); writer2.writeLine("STATE2VEC - EXPERIMENT"); writer2.writeLine(""); writer2.writeLine("==PARAMETERS=="); writer2.writeLine("windowSize: " + windowSize); writer2.writeLine("learningRate: " + learningRate); writer2.writeLine("vectorLength: " + vectorLength); writer2.writeLine("batchSize: " + batchsize); writer2.writeLine("epoch: " + epoch); writer2.writeLine("minWordFreq: " + minWordFreq); writer2.writeLine(""); clusterTest.checkClusters2(state2vec.getTrainedModel(), k, writer2); } } } } } } }
Java
#ifndef AC_GEGBLABB_H #define AC_GEGBLABB_H // // (C) Copyright 1993-2010 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // DESCRIPTION: // // Using the fully qualified names from the `AcGe' struct can be // cumbersome. If there are no global name conflicts use the // following synonyms for convenience. // // Note: All interface descriptions must use fully qualified names. // That is, header files MUST NOT include this file and MUST // NOT use these abbreviations. // // Note: If any of the following abbreviations cause conflicts and // this file cannot be included, then the acceptable abbreviations // (those that do not cause conflicts) will have to be manually // introduced, or another abbreviation header file will have to // be created containing only the acceptable abbreviations. // // Note: When this file is included in a source file, it MUST BE // included AFTER all other include files (except possibly // other abbreviation include files). // For example: // #include "foo.h" // #include "bar.h" // #include "gegblabb.h" // <- Must be last! #include "gegbl.h" const int eGood = AcGe::eGood; const int eBad = AcGe::eBad; typedef AcGe::EntityId EntityId; const AcGe::EntityId kEntity2d = AcGe::kEntity2d; const AcGe::EntityId kEntity3d = AcGe::kEntity3d; const AcGe::EntityId kPointEnt2d = AcGe::kPointEnt2d; const AcGe::EntityId kPointEnt3d = AcGe::kPointEnt3d; const AcGe::EntityId kPosition2d = AcGe::kPosition2d; const AcGe::EntityId kPosition3d = AcGe::kPosition3d; const AcGe::EntityId kPointOnCurve2d = AcGe::kPointOnCurve2d; const AcGe::EntityId kPointOnCurve3d = AcGe::kPointOnCurve3d; const AcGe::EntityId kBoundedPlane = AcGe::kBoundedPlane; const AcGe::EntityId kCircArc2d = AcGe::kCircArc2d; const AcGe::EntityId kCircArc3d = AcGe::kCircArc3d; const AcGe::EntityId kConic2d = AcGe::kConic2d; const AcGe::EntityId kConic3d = AcGe::kConic3d; const AcGe::EntityId kCurve2d = AcGe::kCurve2d; const AcGe::EntityId kCurve3d = AcGe::kCurve3d; const AcGe::EntityId kEllipArc2d = AcGe::kEllipArc2d; const AcGe::EntityId kEllipArc3d = AcGe::kEllipArc3d; const AcGe::EntityId kHelix = AcGe::kHelix; const AcGe::EntityId kLine2d = AcGe::kLine2d; const AcGe::EntityId kLine3d = AcGe::kLine3d; const AcGe::EntityId kLinearEnt2d = AcGe::kLinearEnt2d; const AcGe::EntityId kLinearEnt3d = AcGe::kLinearEnt3d; const AcGe::EntityId kLineSeg2d = AcGe::kLineSeg2d; const AcGe::EntityId kLineSeg3d = AcGe::kLineSeg3d; const AcGe::EntityId kPlanarEnt = AcGe::kPlanarEnt; const AcGe::EntityId kExternalCurve3d = AcGe::kExternalCurve3d; const AcGe::EntityId kExternalCurve2d = AcGe::kExternalCurve2d; const AcGe::EntityId kPlane = AcGe::kPlane; const AcGe::EntityId kRay2d = AcGe::kRay2d; const AcGe::EntityId kRay3d = AcGe::kRay3d; const AcGe::EntityId kSurface = AcGe::kSurface; const AcGe::EntityId kSphere = AcGe::kSphere; const AcGe::EntityId kCone = AcGe::kCone; const AcGe::EntityId kTorus = AcGe::kTorus; const AcGe::EntityId kCylinder = AcGe::kCylinder; const AcGe::EntityId kSplineEnt2d = AcGe::kSplineEnt2d; const AcGe::EntityId kSurfaceCurve2dTo3d = AcGe::kSurfaceCurve2dTo3d; const AcGe::EntityId kSurfaceCurve3dTo2d = AcGe::kSurfaceCurve3dTo2d; const AcGe::EntityId kPolyline2d = AcGe::kPolyline2d; const AcGe::EntityId kAugPolyline2d = AcGe::kAugPolyline2d; const AcGe::EntityId kNurbCurve2d = AcGe::kNurbCurve2d; const AcGe::EntityId kDSpline2d = AcGe::kDSpline2d; const AcGe::EntityId kCubicSplineCurve2d = AcGe::kCubicSplineCurve2d; const AcGe::EntityId kSplineEnt3d = AcGe::kSplineEnt3d; const AcGe::EntityId kPolyline3d = AcGe::kPolyline3d; const AcGe::EntityId kAugPolyline3d = AcGe::kAugPolyline3d; const AcGe::EntityId kNurbCurve3d = AcGe::kNurbCurve3d; const AcGe::EntityId kDSpline3d = AcGe::kDSpline3d; const AcGe::EntityId kCubicSplineCurve3d = AcGe::kCubicSplineCurve3d; const AcGe::EntityId kTrimmedCrv2d = AcGe::kTrimmedCrv2d; const AcGe::EntityId kCompositeCrv2d = AcGe::kCompositeCrv2d; const AcGe::EntityId kCompositeCrv3d = AcGe::kCompositeCrv3d; const AcGe::EntityId kEnvelope2d = AcGe::kEnvelope2d; const AcGe::EntityId kExternalSurface = AcGe::kExternalSurface; const AcGe::EntityId kNurbSurface = AcGe::kNurbSurface; const AcGe::EntityId kOffsetSurface = AcGe::kOffsetSurface; const AcGe::EntityId kTrimmedSurface = AcGe::kTrimmedSurface; const AcGe::EntityId kCurveBoundedSurface = AcGe::kCurveBoundedSurface; const AcGe::EntityId kPointOnSurface = AcGe::kPointOnSurface; const AcGe::EntityId kExternalBoundedSurface = AcGe::kExternalBoundedSurface; const AcGe::EntityId kCurveCurveInt2d = AcGe::kCurveCurveInt2d; const AcGe::EntityId kCurveCurveInt3d = AcGe::kCurveCurveInt3d; const AcGe::EntityId kBoundBlock2d = AcGe::kBoundBlock2d; const AcGe::EntityId kBoundBlock3d = AcGe::kBoundBlock3d; const AcGe::EntityId kOffsetCurve2d = AcGe::kOffsetCurve2d; const AcGe::EntityId kOffsetCurve3d = AcGe::kOffsetCurve3d; const AcGe::EntityId kPolynomCurve3d = AcGe::kPolynomCurve3d; const AcGe::EntityId kBezierCurve3d = AcGe::kBezierCurve3d; const AcGe::EntityId kObject = AcGe::kObject; const AcGe::EntityId kFitData3d = AcGe::kFitData3d; const AcGe::EntityId kHatch = AcGe::kHatch; const AcGe::EntityId kTrimmedCurve2d = AcGe::kTrimmedCurve2d; const AcGe::EntityId kTrimmedCurve3d = AcGe::kTrimmedCurve3d; const AcGe::EntityId kCurveSampleData = AcGe::kCurveSampleData; const AcGe::EntityId kEllipCone = AcGe::kEllipCone; const AcGe::EntityId kEllipCylinder = AcGe::kEllipCylinder; const AcGe::EntityId kIntervalBoundBlock = AcGe::kIntervalBoundBlock; const AcGe::EntityId kClipBoundary2d = AcGe::kClipBoundary2d; const AcGe::EntityId kExternalObject = AcGe::kExternalObject; const AcGe::EntityId kCurveSurfaceInt = AcGe::kCurveSurfaceInt; const AcGe::EntityId kSurfaceSurfaceInt = AcGe::kSurfaceSurfaceInt; typedef AcGe::ExternalEntityKind ExternalEntityKind; const AcGe::ExternalEntityKind kAcisEntity = AcGe::kAcisEntity; const AcGe::ExternalEntityKind kExternalEntityUndefined = AcGe::kExternalEntityUndefined; typedef AcGe::NurbSurfaceProperties NurbSurfaceProperties; const AcGe::NurbSurfaceProperties kOpen = AcGe::kOpen; const AcGe::NurbSurfaceProperties kClosed = AcGe::kClosed; const AcGe::NurbSurfaceProperties kPeriodic = AcGe::kPeriodic; const AcGe::NurbSurfaceProperties kRational = AcGe::kRational; const AcGe::NurbSurfaceProperties kNoPoles= AcGe::kNoPoles; const AcGe::NurbSurfaceProperties kPoleAtMin = AcGe::kPoleAtMin; const AcGe::NurbSurfaceProperties kPoleAtMax = AcGe::kPoleAtMax; const AcGe::NurbSurfaceProperties kPoleAtBoth = AcGe::kPoleAtBoth; typedef AcGe::PointContainment PointContainment; const AcGe::PointContainment kInside = AcGe::kInside; const AcGe::PointContainment kOutside = AcGe::kOutside; const AcGe::PointContainment kOnBoundary = AcGe::kOnBoundary; typedef AcGe::AcGeXConfig AcGeXConfig; const AcGe::AcGeXConfig kNotDefined = AcGe::kNotDefined; const AcGe::AcGeXConfig kUnknown = AcGe::kUnknown; const AcGe::AcGeXConfig kLeftRight = AcGe::kLeftRight; const AcGe::AcGeXConfig kRightLeft = AcGe::kRightLeft; const AcGe::AcGeXConfig kLeftLeft = AcGe::kLeftLeft; const AcGe::AcGeXConfig kRightRight = AcGe::kRightRight; const AcGe::AcGeXConfig kPointLeft = AcGe::kPointLeft; const AcGe::AcGeXConfig kPointRight = AcGe::kPointRight; const AcGe::AcGeXConfig kLeftOverlap = AcGe::kLeftOverlap; const AcGe::AcGeXConfig kOverlapLeft = AcGe::kOverlapLeft; const AcGe::AcGeXConfig kRightOverlap = AcGe::kRightOverlap; const AcGe::AcGeXConfig kOverlapRight = AcGe::kOverlapRight; const AcGe::AcGeXConfig kOverlapStart = AcGe::kOverlapStart; const AcGe::AcGeXConfig kOverlapEnd = AcGe::kOverlapEnd; const AcGe::AcGeXConfig kOverlapOverlap = AcGe::kOverlapOverlap; typedef AcGe::ErrorCondition AcGeError; const AcGe::ErrorCondition kOk = AcGe::kOk; const AcGe::ErrorCondition k0This = AcGe::k0This; const AcGe::ErrorCondition k0Arg1 = AcGe::k0Arg1; const AcGe::ErrorCondition k0Arg2 = AcGe::k0Arg2; const AcGe::ErrorCondition kPerpendicularArg1Arg2 = AcGe::kPerpendicularArg1Arg2; const AcGe::ErrorCondition kEqualArg1Arg2 = AcGe::kEqualArg1Arg2; const AcGe::ErrorCondition kEqualArg1Arg3 = AcGe::kEqualArg1Arg3; const AcGe::ErrorCondition kEqualArg2Arg3 = AcGe::kEqualArg2Arg3; const AcGe::ErrorCondition kLinearlyDependentArg1Arg2Arg3 = AcGe::kLinearlyDependentArg1Arg2Arg3; const AcGe::ErrorCondition kArg1TooBig = AcGe::kArg1TooBig; const AcGe::ErrorCondition kArg1OnThis = AcGe::kArg1OnThis; const AcGe::ErrorCondition kArg1InsideThis = AcGe::kArg1InsideThis; typedef AcGe::AcGeIntersectError AcGeIntersectError; const AcGe::AcGeIntersectError kXXOk = AcGe::kXXOk; const AcGe::AcGeIntersectError kXXIndexOutOfRange = AcGe::kXXIndexOutOfRange; const AcGe::AcGeIntersectError kXXWrongDimensionAtIndex = AcGe::kXXWrongDimensionAtIndex; const AcGe::AcGeIntersectError kXXUnknown = AcGe::kXXUnknown; typedef AcGe::KnotParameterization KnotParameterization; const AcGe::KnotParameterization kChord = AcGe::kChord; const AcGe::KnotParameterization kSqrtChord = AcGe::kSqrtChord; const AcGe::KnotParameterization kUniform = AcGe::kUniform; const AcGe::KnotParameterization kCustomParameterization = AcGe::kCustomParameterization; #endif
Java
<?php /* * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * This software consists of voluntary contributions made by many individuals * and is licensed under the MIT license. For more information, see * <http://www.doctrine-project.org>. */ namespace Doctrine\ODM\MongoDB\Mapping\Annotations; use Doctrine\Common\Annotations\Annotation; abstract class AbstractDocument extends Annotation { }
Java
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class KFContact; @protocol IKFContactExt <NSObject> @optional - (void)onKFContactHeadImgUpdate:(KFContact *)arg1; - (void)onModifyKFContact:(KFContact *)arg1; @end
Java
package lv.emes.libraries.utilities.validation; /** * Actions for error that occur in validation process. * * @author eMeS * @version 1.2. */ public interface MS_ValidationError<T> { MS_ValidationError withErrorMessageFormingAction(IFuncFormValidationErrorMessage action); /** * Returns message of validation error using pre-defined method to form message. * @return formatted message describing essence of this particular validation error. */ String getMessage(); Integer getNumber(); T getObject(); /** * @param object an object to validate. * @return reference to validation error itself. */ MS_ValidationError withObject(T object); }
Java
#ifndef _absnodeaction_h_ #define _absnodeaction_h_ #include "cocos2d.h" using namespace cocos2d; #include <string> #include <iostream> #include <vector> using namespace std; namespace uilib { class TouchNode; enum EaseType { EaseNone, EaseIn, EaseOut, EaseInOut, EaseExponentialIn, EaseExponentialOut, EaseExponentialInOut, EaseSineIn, EaseSineOut, EaseSineInOut, EaseElastic, EaseElasticIn, EaseElasticOut, EaseElasticInOut, EaseBounce, EaseBounceIn, EaseBounceOut, EaseBounceInOut, EaseBackIn, EaseBackOut, EaseBackInOut }; enum MoveInType{ HorizontalRightIn, HorizontalLeftIn, HorizontalBothIn, VerticalTopIn, VerticalBottomIn, VerticalBothin, ScaleIn, ScaleXIn, ScaleYIn, SwayIn, RotateIn, BlinkIn, ReelIn, FireIn, DropScaleIn }; enum MoveOutType{ HorizontalRightOut, HorizontalLeftOut, HorizontalBothOut, VerticalTopOut, VerticalBottomOut, VerticalBothOut, ScaleOut, ScaleXOut, ScaleYOut, SwayOut, RotateOut, BlinkOut, ReelOut, FireOut }; enum RunningEffectType { ShineEffect, SwayEffect, ScaleEffect, AnimEffect }; class BasNodeEffectAction : public CCNode { public: BasNodeEffectAction(); virtual ~BasNodeEffectAction(); virtual void finished(); virtual void doAction(TouchNode *node,bool enable) = 0; inline void setEaseType(EaseType type) { m_easeType = type;} inline EaseType getEaseType() { return m_easeType;} inline void setActionTime(float time) { m_actionTime = time;} inline float getActionTime() { return m_actionTime;} inline void setStartTime(float time) { m_startTime = time;} inline float getStartTime() { return m_startTime;} void setFinishCB(CCNode *listener,SEL_CallFuncN func); inline bool isRunning() { return m_running;} protected: EaseType m_easeType; float m_actionTime; float m_startTime; protected: bool m_running; protected: SEL_CallFuncN m_finishFunc; CCNode *m_listener; }; class BasNodeAction : public CCNode { public: BasNodeAction(); virtual ~BasNodeAction(); virtual void finished(); virtual void doAction(const std::vector<TouchNode*> &nodes) = 0; void setDelayTime(float delay) { m_delayTime = delay;} float getDelayTime() { return m_delayTime;} inline void setEaseType(EaseType type) { m_easeType = type;} inline EaseType getEaseType() { return m_easeType;} inline void setMoveInType(MoveInType type) { m_inType = type;} inline MoveInType getMoveInType() { return m_inType;} inline void setMoveOutType(MoveOutType type) { m_outType = type;} inline MoveOutType getMoveOutType() { return m_outType;} inline void setActionTime(float time) { m_actionTime = time;} inline float getActionTime() { return m_actionTime;} inline void setStartTime(float time) { m_startTime = time;} inline float getStartTime() { return m_startTime;} inline void setRate(float rate) { m_rate = rate;} inline float getRate() { return m_rate;} void setFinishCB(CCNode *listener,SEL_CallFuncN func,CCNode *actionNode = 0); protected: CCActionEase *createEaseAction(); protected: int m_actionRunNum; float m_delayTime; EaseType m_easeType; MoveInType m_inType; MoveOutType m_outType; float m_actionTime; float m_rate; float m_startTime; protected: SEL_CallFuncN m_finishFunc; CCNode *m_listener; CCNode *m_actionNode; }; class UiNodeActionFactory { UiNodeActionFactory(); ~UiNodeActionFactory(); static UiNodeActionFactory *m_instance; public: static UiNodeActionFactory *getInstance(); BasNodeAction *getMoveActionByName(const std::string &name); BasNodeEffectAction *getEffectActionByName(const std::string &name); protected: }; } #endif
Java
window.ImageViewer = function(url, alt, title){ var img = $('<img />').attr('src', url).attr('alt', title).css({ display: 'inline-block', 'max-width': '90vw', 'max-height': '90vh' }); var a = $('<a></a>').attr('target', '_blank') .attr('title', title) .attr('href', url) .css({ display: 'inline-block', height: '100%' }) .append(img); var close_it = function(){ overlay.remove(); container.remove(); }; var closeBtn = $('<a class="icon-remove-sign"></a>').css({ color: 'red', 'font-size': 'x-large', 'margin-left': '-0.1em' }).bind('click', close_it); var closeWrapper = $('<div></div>').css({ height: '100%', width: '2em', 'text-align': 'left', 'display': 'inline-block', 'vertical-algin': 'top', 'margin-top': '-0.6em', 'float': 'right' }).append(closeBtn); var container = $('<div></div>').append( $('<div></div>').css({ margin: '5vh 1vw', display: 'inline-block', 'vertical-align': 'top' }).append(a).append(closeWrapper)) .css({ 'z-index': 30000000, 'position': 'fixed', 'padding': 0, 'margin': 0, 'width': '100vw', 'height': '100vh', 'top': 0, 'left': 0, 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle' }) .bind('click',close_it) .appendTo('body'); var overlay = $('<div class="blockUI blockMsg blockPage">').css({ 'z-index': 9999, 'position': 'fixed', padding: 0, margin: 0, width: '100vw', height: '100vh', top: '0vh', left: '0vw', 'text-align': 'center', 'cursor': 'default', 'vertical-align': 'middle', 'background-color': 'gray', 'opacity': '0.4' }).bind('click', close_it).appendTo('body'); this.close = close_it; return this; }
Java
--- layout: post.html title: "Fundraising for PyLadies for PyCon 2015" tag: [PyCon] author: Lynn Root author_link: http://twitter.com/roguelynn --- **TL;DR**: [Donate](#ways-to-donate) to PyLadies for PyCon! It's that time again! With [PyCon 2015][0] planning in high gear, PyLadies is revving up to raise funds to help women attend the biggest Python conference of the year. Last year, we raised **$40,000**. We're hoping to do that again to help women attend PyCon. Here's the breakdown: ### Our numbers * In addition to registration, it will take about $500-1000 per woman in North America to attend PyCon 2015 in Montreal * In addition to registration, it will take about $1000-2000 per woman outside of North America to attend PyCon 2015 in Montreal ### Why PyLadies? Our effect on the community _(percentages are not at all accurate, and are roughly estimated based on guessing names-to-gender scripts):_ * PyCon 2011 had less than 10% women attendees (speaker % unknown) * PyLadies started in late 2011 * PyCon 2012 had about 11% women attendees, and about the same in speakers. * This included giving PyLadies and [Women Who Code][8] booths to help promote our messages * At the time of PyCon 2014, PyLadies had over [35 chapters][7], doing stuff like: * hosts events like learning python, learning git/github, * providing space for study groups, * enriching members with speaker series (like Guido van Rossum!), * events to help think up of talks to submit for PyCon (as well as DjangoCon), * hold events for folks to practice their talk, etc * PyLadies work showed: * PyCon 2013 had over 20% women attendees, and about 22% women speakers. * PyCon 2014 had over 30% women attendees, and about a third of the speakers were women. * No overhead - we're all volunteers! ;-) * Lastly, donations tax deductible since PyLadies is under the financial enclave of the Python Software Foundation ### What we're actively doing: * We're using all of the $12k that PyLadies raised at last year's PyCon auction to increase the aid pool - something that we were hoping to actually use towards growing PyLadies locations (but it's okay! $10k for more women friends at PyCon!) * We're bugging companies and individuals do donate (hence this blog post!). ### What you will get in return * Unless you explicitly choose to be anonymous (though the [online donation site][5] or in private discussions), we will profusely thank you via our public channels (Twitter, this blog, and at our PyCon booth) * Provide a detailed write-up and financial introspection of how many women we've helped because of this campaign * Visibility! It shows the PyCon/Python community that your company/you are serious about women in tech - which can directly benefit sponsors with increased hiring pool of female Pythonistas. ### Ways to donate All of the following methods are tax-deductible with funds going to the [Python Software Foundation][1], a 501(c)3 charitable organization. * Through our [donation page][4] (ideal for individuals) * Email me at [lynn@lynnroot.com][2] (ideal for companies or anyone needing a proper invoice, or individualized solutions) * Become a [sponsor][6] for PyCon (this is more indirect and less potent, but overall helpful to PyCon) More information is available on the [PyCon Financial Aid][5] site if you would like to apply for financial aid for PyCon, whether you are a PyLady or PyGent. [0]: http://us.pycon.org/2015 [1]: http://python.org/psf [2]: mailto:lynn@lynnroot.com?subject=PyLadies%20Donation [3]: http://pyladies.com/blog [4]: https://psfmember.org/civicrm/contribute/transact?reset=1&id=6 [5]: https://us.pycon.org/2014/assistance/ [6]: https://us.pycon.org/2014/sponsors/prospectus/ [7]: https://github.com/pyladies/pyladies/tree/master/www/locations [8]: http://www.meetup.com/women-who-code-sf [9]: http://www.marketwired.com/press-release/-1771597.htm
Java
// Copyright (c) 2017-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CONSENSUS_TX_VERIFY_H #define BITCOIN_CONSENSUS_TX_VERIFY_H #include "amount.h" #include <stdint.h> #include <vector> class CBlockIndex; class CCoinsViewCache; class CTransaction; class CValidationState; /** Transaction validation functions */ /** Context-independent validity checks */ bool CheckTransaction(const CTransaction& tx, CValidationState& state); namespace Consensus { /** * Check whether all inputs of this transaction are valid (no double spends and amounts) * This does not modify the UTXO set. This does not check scripts and sigs. * @param[out] txfee Set to the transaction fee if successful. * Preconditions: tx.IsCoinBase() is false. */ bool CheckTxInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& inputs, int nSpendHeight, CAmount& txfee); } // namespace Consensus /** Auxiliary functions for transaction validation (ideally should not be exposed) */ /** * Count ECDSA signature operations the old-fashioned (pre-0.6) way * @return number of sigops this transaction's outputs will produce when spent * @see CTransaction::FetchInputs */ unsigned int GetLegacySigOpCount(const CTransaction& tx); /** * Count ECDSA signature operations in pay-to-script-hash inputs. * * @param[in] mapInputs Map of previous transactions that have outputs we're spending * @return maximum number of sigops required to validate this transaction's inputs * @see CTransaction::FetchInputs */ unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs); /** * Count total signature operations for a transaction. * @param[in] tx Transaction for which we are counting sigops * @param[in] inputs Map of previous transactions that have outputs we're spending * @param[out] flags Script verification flags * @return Total signature operation count for a tx */ unsigned int GetTransactionSigOpCount(const CTransaction& tx, const CCoinsViewCache& inputs, int flags); /** * Check if transaction is final and can be included in a block with the * specified height and time. Consensus critical. */ bool IsFinalTx(const CTransaction &tx, int nBlockHeight, int64_t nBlockTime); /** * Calculates the block height and previous block's median time past at * which the transaction will be considered final in the context of BIP 68. * Also removes from the vector of input heights any entries which did not * correspond to sequence locked inputs as they do not affect the calculation. */ std::pair<int, int64_t> CalculateSequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); bool EvaluateSequenceLocks(const CBlockIndex& block, std::pair<int, int64_t> lockPair); /** * Check if transaction is final per BIP 68 sequence numbers and can be included in a block. * Consensus critical. Takes as input a list of heights at which tx's inputs (in order) confirmed. */ bool SequenceLocks(const CTransaction &tx, int flags, std::vector<int>* prevHeights, const CBlockIndex& block); #endif // BITCOIN_CONSENSUS_TX_VERIFY_H
Java
--- layout: post title: Week three and implementing twig template --- The week three of coding period has ended and this time I learnt about something very new to me, Twig template. In Drupal 8 Twig has replaced PHPTemplate as default templating engine which meant that the theming of module had to be done from beginning. Also since my module deals with creation of printer friendly version of nodes so it makes it even more important that theming should be paid more importance. The reference material present on drupal.org are good but still the things were not getting clear to me so I browsed more and more and finally found this small <a href="http://drewpull.drupalgardens.com/blog/drupal-8-twig-template-engine" target="_blank">blog </a>on Twig which helped me understand. In the process of learning theming I learnt about concept of rendering in Drupal and most importantly about invalidating catching while rendering, I mainly used getListCacheTags() to serve my purpose. Also knowing the that I can use template_preprocess_module() to create temporary variables and then rendering them in my templates was very helpful. In the present week I managed to develop a partial working prototype of module with not all but many configurations completed like links for printer friendly version are being shown in blocks as well as below the entities. Ofcourse the user can disable and re-enable these links. I have created view modes for the print version and hence generated core.entity_view_mode.$entity_type.$view_mode.yml file. I was impressed by the fact that I had to import configuration for this file becuase it was something very new to me. Next week I will mainly be working on completing the configuration of module and try to rectify the problem which I have found in this week. The progress of module develpoment can be viewed over <a href="https://github.com/zealfire/printable" style="text-decoration:none;" target="_blank">here</a>.
Java
#include <compiler.h> #if defined(CPUCORE_IA32) && defined(SUPPORT_MEMDBG32) #include <common/strres.h> #include <cpucore.h> #include <pccore.h> #include <io/iocore.h> #include <generic/memdbg32.h> #define MEMDBG32_MAXMEM 16 #define MEMDBG32_DATAPERLINE 128 #define MEMDBG32_LEFTMARGIN 8 typedef struct { UINT mode; int width; int height; int bpp; CMNPAL pal[MEMDBG32_PALS]; } MEMDBG32; static MEMDBG32 memdbg32; static const char _mode0[] = "Real Mode"; static const char _mode1[] = "Protected Mode"; static const char _mode2[] = "Virtual86"; static const char *modestr[3] = {_mode0, _mode1, _mode2}; static const RGB32 md32pal[MEMDBG32_PALS] = { RGB32D(0x33, 0x33, 0x33), RGB32D(0x00, 0x00, 0x00), RGB32D(0xff, 0xaa, 0x00), RGB32D(0xff, 0x00, 0x00), RGB32D(0x11, 0x88, 0x11), RGB32D(0x00, 0xff, 0x00), RGB32D(0xff, 0xff, 0xff)}; void memdbg32_initialize(void) { ZeroMemory(&memdbg32, sizeof(memdbg32)); memdbg32.width = (MEMDBG32_BLOCKW * MEMDBG32_DATAPERLINE) + MEMDBG32_LEFTMARGIN; memdbg32.height = (MEMDBG32_BLOCKH * 2 * MEMDBG32_MAXMEM) + 8; } void memdbg32_getsize(int *width, int *height) { if (width) { *width = memdbg32.width; } if (height) { *height = memdbg32.height; } } REG8 memdbg32_process(void) { return(MEMDBG32_FLAGDRAW); } BOOL memdbg32_paint(CMNVRAM *vram, CMNPALCNV cnv, BOOL redraw) { UINT mode; UINT8 use[MEMDBG32_MAXMEM*MEMDBG32_DATAPERLINE*2 + 256]; UINT32 pd[1024]; UINT pdmax; UINT i, j; UINT32 pde; UINT32 pdea; UINT32 pte; char str[4]; mode = 0; if (CPU_STAT_PM) { mode = 1; } if (CPU_STAT_VM86) { mode = 2; } if (memdbg32.mode != mode) { memdbg32.mode = mode; redraw = TRUE; } if ((!redraw) && (!CPU_STAT_PAGING)) { return(FALSE); } if (vram == NULL) { return(FALSE); } if ((memdbg32.bpp != vram->bpp) || (redraw)) { if (cnv == NULL) { return(FALSE); } (*cnv)(memdbg32.pal, md32pal, MEMDBG32_PALS, vram->bpp); memdbg32.bpp = vram->bpp; } cmndraw_fill(vram, 0, 0, memdbg32.width, memdbg32.height, memdbg32.pal[MEMDBG32_PALBDR]); ZeroMemory(use, sizeof(use)); if (CPU_STAT_PAGING) { pdmax = 0; for (i=0; i<1024; i++) { pde = cpu_memoryread_d(CPU_STAT_PDE_BASE + (i * 4)); if (pde & CPU_PDE_PRESENT) { for (j=0; j<pdmax; j++) { if (!((pde ^ pd[j]) & CPU_PDE_BASEADDR_MASK)) { break; } } if (j < pdmax) { pd[j] |= pde & CPU_PDE_ACCESS; } else { pd[pdmax++] = pde; } } } for (i=0; i<pdmax; i++) { pde = pd[i]; pdea = pde & CPU_PDE_BASEADDR_MASK; for (j=0; j<1024; j++) { pte = cpu_memoryread_d(pdea + (j * 4)); if ((pte & CPU_PTE_PRESENT) && (pte < 0x1000000/16*MEMDBG32_MAXMEM/128*MEMDBG32_DATAPERLINE)) { if ((pde & CPU_PDE_ACCESS) && (pte & CPU_PTE_ACCESS)) { use[pte >> 12] = MEMDBG32_PALPAGE1; } else if (!use[pte >> 12]) { use[pte >> 12] = MEMDBG32_PALPAGE0; } } } } } else { FillMemory(use, 256, MEMDBG32_PALREAL); FillMemory(use + (0xfa0000 >> 12), (0x60000 >> 12), MEMDBG32_PALREAL); if ((CPU_STAT_PM) && (pccore.extmem)) { FillMemory(use + 256, MIN(MEMDBG32_DATAPERLINE * 2 * pccore.extmem, sizeof(use) - 256), MEMDBG32_PALPM); } } for (i=0; i<MEMDBG32_MAXMEM*2; i++) { for (j=0; j<MEMDBG32_DATAPERLINE; j++) { cmndraw_fill(vram, MEMDBG32_LEFTMARGIN + j * MEMDBG32_BLOCKW, i * MEMDBG32_BLOCKH, MEMDBG32_BLOCKW - 1, MEMDBG32_BLOCKH - 1, memdbg32.pal[use[(i * MEMDBG32_DATAPERLINE) + j]]); } } for (i=0; i<MEMDBG32_MAXMEM; i++) { SPRINTF(str, "%x", i); cmddraw_text8(vram, 0, i * MEMDBG32_BLOCKH * 2, str, memdbg32.pal[MEMDBG32_PALTXT]); } cmddraw_text8(vram, 0, memdbg32.height - 8, modestr[mode], memdbg32.pal[MEMDBG32_PALTXT]); return(TRUE); } #endif
Java
// // opjlib.h // opjlib // // Created by Rich Stoner on 11/26/13. // Copyright (c) 2013 WholeSlide. All rights reserved. // #import <Foundation/Foundation.h> @interface opjlib : NSObject @end
Java
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-01 20:02 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('phone_numbers', '0001_initial'), ('sims', '0001_initial'), ] operations = [ migrations.AddField( model_name='phonenumber', name='related_sim', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='phone_numbers', to='sims.Sim'), ), ]
Java
package ch.spacebase.openclassic.api; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.security.SecureRandom; import java.util.HashMap; import java.util.Map; import ch.spacebase.openclassic.api.util.Constants; /** * Manages the server's web heartbeats. */ public final class HeartbeatManager { private static final long salt = new SecureRandom().nextLong(); private static final Map<String, Runnable> customBeats = new HashMap<String, Runnable>(); private static String url = ""; /** * Gets the server's current salt. * @return The server's salt. */ public static long getSalt() { return salt; } /** * Gets the server's minecraft.net url. * @return The url. */ public static String getURL() { return url; } /** * Sets the server's known minecraft.net url. * @param url The url. */ public static void setURL(String url) { HeartbeatManager.url = url; } /** * Triggers a heartbeat. */ public static void beat() { mineBeat(); womBeat(); for(String id : customBeats.keySet()) { try { customBeats.get(id).run(); } catch(Exception e) { OpenClassic.getLogger().severe("Exception while running a custom heartbeat with the ID \"" + id + "\"!"); e.printStackTrace(); } } } /** * Adds a custom heartbeat to run when {@link beat()} is called. * @param id ID of the custom heartbeat. * @param run Runnable to call when beating. */ public static void addBeat(String id, Runnable run) { customBeats.put(id, run); } /** * Removes a custom heartbeat. * @param id ID of the heartbeat. */ public static void removeBeat(String id) { customBeats.remove(id); } /** * Clears the custom heartbeat list. */ public static void clearBeats() { customBeats.clear(); } private static void mineBeat() { URL url = null; try { url = new URL("https://minecraft.net/heartbeat.jsp?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size()); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting minecraft.net heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); try { conn.setRequestMethod("GET"); } catch (ProtocolException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat: Connection doesn't support GET...?"); return; } conn.setDoOutput(false); conn.setDoInput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); InputStream input = conn.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String result = reader.readLine(); reader.close(); input.close(); if(!HeartbeatManager.url.equals(result)) { HeartbeatManager.url = result; OpenClassic.getLogger().info(Color.GREEN + "The server's URL is now \"" + getURL() + "\"."); try { File file = new File(OpenClassic.getGame().getDirectory(), "server-address.txt"); if(!file.exists()) file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); writer.write(result); writer.close(); } catch(IOException e) { OpenClassic.getLogger().severe("Failed to save server address!"); e.printStackTrace(); } } } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing minecraft.net heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } private static void womBeat() { URL url = null; try { url = new URL("http://direct.worldofminecraft.com/hb.php?port=" + OpenClassic.getServer().getPort() + "&max=" + OpenClassic.getServer().getMaxPlayers() + "&name=" + URLEncoder.encode(Color.stripColor(OpenClassic.getServer().getServerName()), "UTF-8") + "&public=" + OpenClassic.getServer().isPublic() + "&version=" + Constants.PROTOCOL_VERSION + "&salt=" + salt + "&users=" + OpenClassic.getServer().getPlayers().size() + "&noforward=1"); } catch(MalformedURLException e) { OpenClassic.getLogger().severe("Malformed URL while attempting WOM heartbeat?"); return; } catch(UnsupportedEncodingException e) { OpenClassic.getLogger().severe("UTF-8 URL encoding is unsupported on your system."); return; } HttpURLConnection conn = null; try { conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(false); conn.setDoInput(false); conn.setUseCaches(false); conn.setAllowUserInteraction(false); conn.setRequestProperty("Content-type", "text/xml; charset=" + "UTF-8"); } catch (IOException e) { OpenClassic.getLogger().severe("Exception while performing WOM heartbeat!"); e.printStackTrace(); } finally { if (conn != null) conn.disconnect(); } } }
Java
#! /bin/bash BASHRC="$HOME/.bashrc" echo "# java setting" >> $BASHRC echo "export JAVA_HOME=\$(/usr/libexec/java_home)" >> $BASHRC echo "" >> $BASHRC
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParkingRampSimulator { public class ParkingRamp : ParkingConstruct { [Newtonsoft.Json.JsonIgnore] public List<ParkingFloor> Floors { get; private set; } public override bool IsFull { get { return OpenLocations < 1; } } public override int OpenLocations { get { return Floors.Sum(r => r.OpenLocations) - InQueue.Count; } } public override int TotalLocations { get { return Floors.Sum(r => r.TotalLocations); } } public ParkingRamp(ParkingConstruct parent, string name, int floorCount, int locationCount) : base(parent, name) { Name = name; Floors = new List<ParkingFloor>(); for (int i = 0; i < floorCount; i++) { Floors.Add(new ParkingFloor(this, string.Format("{0}-{1}", Name, i.ToString()), locationCount)); } } public override void Tick() { var openCount = Floors.Count(r => !r.IsFull); if (openCount > 0) { var gateCapacity = (int)(Simulator.Interval.TotalSeconds / 10.0); for (int i = 0; i < gateCapacity; i++) { var floorsWithRoom = Floors.Where(r => !r.IsFull).ToList(); if (InQueue.Count > 0 && floorsWithRoom.Count > 0) { var floor = Simulator.Random.Next(floorsWithRoom.Count); floorsWithRoom[floor].InQueue.Enqueue(InQueue.Dequeue()); } } } foreach (var item in Floors) item.Tick(); base.Tick(); while (OutQueue.Count > 0) Parent.OutQueue.Enqueue(OutQueue.Dequeue()); } } }
Java
package org.gojul.gojulutils.data; /** * Class {@code GojulPair} is a simple stupid pair class. This class is notably necessary * when emulating JOIN in database and such a class does not exist natively in the JDK. * This object is immutable as long as the object it contains are immutable. Since * this object is not serializable it should not be stored in objects which could be serialized, * especially Java HttpSession objects. * * @param <S> the type of the first object of the pair. * @param <T> the type of the second object of the pair. * @author jaubin */ public final class GojulPair<S, T> { private final S first; private final T second; /** * Constructor. Both parameters are nullable. Note that this constructor * does not perform any defensive copy as it is not possible there. * * @param first the first object. * @param second the second object. */ public GojulPair(final S first, final T second) { this.first = first; this.second = second; } /** * Return the first object. * * @return the first object. */ public S getFirst() { return first; } /** * Return the second object. * * @return the second object. */ public T getSecond() { return second; } /** * {@inheritDoc} */ @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GojulPair<?, ?> pair = (GojulPair<?, ?>) o; if (getFirst() != null ? !getFirst().equals(pair.getFirst()) : pair.getFirst() != null) return false; return getSecond() != null ? getSecond().equals(pair.getSecond()) : pair.getSecond() == null; } /** * {@inheritDoc} */ @Override public int hashCode() { int result = getFirst() != null ? getFirst().hashCode() : 0; result = 31 * result + (getSecond() != null ? getSecond().hashCode() : 0); return result; } /** * {@inheritDoc} */ @Override public String toString() { return "GojulPair{" + "first=" + first + ", second=" + second + '}'; } }
Java
using System.Collections.Generic; using System.Diagnostics.Contracts; using Microsoft.CodeAnalysis; namespace ErrorProne.NET.Extensions { public static class SyntaxNodeExtensions { public static IEnumerable<SyntaxNode> EnumerateParents(this SyntaxNode node) { Contract.Requires(node != null); while (node.Parent != null) { yield return node.Parent; node = node.Parent; } } } }
Java
/*-------------------------------------------- Created by Sina on 06/05/13. Copyright (c) 2013 MIT. All rights reserved. --------------------------------------------*/ #include "elements.h" #include "mpi_compat.h" #include "gcmc.h" #include "memory.h" #include "random.h" #include "neighbor.h" #include "ff_md.h" #include "MAPP.h" #include "atoms_md.h" #include "comm.h" #include "dynamic_md.h" using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ GCMC::GCMC(AtomsMD*& __atoms,ForceFieldMD*&__ff,DynamicMD*& __dynamic,elem_type __gas_type,type0 __mu,type0 __T,int seed): gas_type(__gas_type), T(__T), mu(__mu), natms_lcl(__atoms->natms_lcl), natms_ph(__atoms->natms_ph), cut_sq(__ff->cut_sq), s_lo(__atoms->comm.s_lo), s_hi(__atoms->comm.s_hi), dynamic(__dynamic), world(__atoms->comm.world), atoms(__atoms), ff(__ff), ielem(gas_type) { random=new Random(seed); s_trials=new type0*[__dim__]; *s_trials=NULL; del_ids=NULL; del_ids_sz=del_ids_cpcty=0; vars=lcl_vars=NULL; } /*-------------------------------------------- destructor --------------------------------------------*/ GCMC::~GCMC() { delete [] del_ids; delete [] s_trials; delete random; } /*-------------------------------------------- --------------------------------------------*/ void GCMC::add_del_id(int* new_ids,int no) { if(del_ids_sz+no>del_ids_cpcty) { int* del_ids_=new int[del_ids_sz+no]; memcpy(del_ids_,del_ids,del_ids_sz*sizeof(int)); del_ids_cpcty=del_ids_sz+no; delete [] del_ids; del_ids=del_ids_; } memcpy(del_ids+del_ids_sz,new_ids,sizeof(int)*no); del_ids_sz+=no; } /*-------------------------------------------- --------------------------------------------*/ int GCMC::get_new_id() { if(del_ids_sz) { del_ids_sz--; return del_ids[del_ids_sz]; } else { max_id++; return max_id; } } /*-------------------------------------------- --------------------------------------------*/ void GCMC::init() { cut=ff->cut[ielem][0]; for(size_t i=1;i<atoms->elements.nelems;i++) cut=MAX(cut,ff->cut[ielem][i]); gas_mass=atoms->elements.masses[gas_type]; kbT=atoms->kB*T; beta=1.0/kbT; lambda=atoms->hP/sqrt(2.0*M_PI*kbT*gas_mass); sigma=sqrt(kbT/gas_mass); z_fac=1.0; for(int i=0;i<__dim__;i++) z_fac/=lambda; z_fac*=exp(beta*mu); vol=1.0; for(int i=0;i<__dim__;i++)vol*=atoms->H[i][i]; id_type max_id_=0; id_type* id=atoms->id->begin(); for(int i=0;i<natms_lcl;i++) max_id_=MAX(id[i],max_id_); MPI_Allreduce(&max_id_,&max_id,1,Vec<id_type>::MPI_T,MPI_MAX,world); for(int i=0;i<del_ids_sz;i++) max_id=MAX(max_id,del_ids[i]); ngas_lcl=0; elem_type* elem=atoms->elem->begin(); for(int i=0;i<natms_lcl;i++) if(elem[i]==gas_type) ngas_lcl++; MPI_Allreduce(&ngas_lcl,&ngas,1,MPI_INT,MPI_SUM,world); } /*-------------------------------------------- --------------------------------------------*/ void GCMC::fin() { } /*-------------------------------------------- --------------------------------------------*/ void GCMC::box_setup() { int sz=0; max_ntrial_atms=1; for(int i=0;i<__dim__;i++) { type0 tmp=0.0; for(int j=i;j<__dim__;j++) tmp+=atoms->B[j][i]*atoms->B[j][i]; cut_s[i]=sqrt(tmp)*cut; s_lo_ph[i]=s_lo[i]-cut_s[i]; s_hi_ph[i]=s_hi[i]+cut_s[i]; nimages_per_dim[i][0]=static_cast<int>(floor(s_hi_ph[i])); nimages_per_dim[i][1]=-static_cast<int>(floor(s_lo_ph[i])); max_ntrial_atms*=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; sz+=1+nimages_per_dim[i][0]+nimages_per_dim[i][1]; } *s_trials=new type0[sz]; for(int i=1;i<__dim__;i++) s_trials[i]=s_trials[i-1]+1+nimages_per_dim[i-1][0]+nimages_per_dim[i-1][1]; } /*-------------------------------------------- --------------------------------------------*/ void GCMC::box_dismantle() { delete [] *s_trials; *s_trials=NULL; }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); }, // Update DOM on a Received Event receivedEvent: function(id) { } }; app.initialize();
Java
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include "mqtt.h" // Connect to MQTT and set up subscriptions based on configuration void MQTT::connect() { // Connect to broker this->mqttClient.setServer(this->host, this->port); mqttClient.connect(this->clientId); Serial.print("Connected to MQTT, with server: "); Serial.print(this->host); Serial.print(", port: "); Serial.print(this->port); Serial.print(", with client ID: "); Serial.println(this->clientId); // Send ping ping(); } // Send ping to MQTT broker void MQTT::ping() { char payload[50]; sprintf(payload, "%s ok", this->clientId); this->mqttClient.publish("/status", payload); Serial.println("Sent ping to broker"); }
Java
using System.Collections.Generic; namespace SmartMeter.Business.Interface.Mapper { public interface IMapTelegram { Persistence.Interface.ITelegram Map(ITelegram businessTelegram); Business.Interface.ITelegram Map(Persistence.Interface.ITelegram persistenceTelegram); IEnumerable<ITelegram> Map(IEnumerable<Persistence.Interface.ITelegram> persistenceTelegrams); } }
Java
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>NTU D3js HW01</title> <link rel="stylesheet" type="text/css" href="main.css"> <script src="https://d3js.org/d3.v3.min.js"></script> </head> <body> <!-- page 4 --> 關&nbsp;&nbsp;關&nbsp;&nbsp;雎&nbsp;&nbsp;鳩<br> 在&nbsp;&nbsp;河&nbsp;&nbsp;之&nbsp;&nbsp;洲<br> <!-- 註 解 此 行 --> 窈&nbsp;&nbsp;窕&nbsp;&nbsp;淑&nbsp;&nbsp;女<br> 君&nbsp;&nbsp;子&nbsp;&nbsp;好&nbsp;&nbsp;逑<br><br> 詩.周南.關睢 <!-- page 8 --> <div> <hr> <h1>小王子</h1> <p>然後他又回到狐狸那裡。</p> <p>「再見了!」小王子說。</p> <p>「再見了!」狐狸說。</p> <blockquote> 「我的秘密很簡單:<strong>唯有心才能看得清楚,眼睛是看不到真正重要的東西的</strong>。」 </blockquote> <p>小王子複述一遍:「真正的東西不是用眼睛可以看得到的。」</p> </div> <hr> <!-- page 13 --> <table border="1"> <tr> <th colspan = "4">直轄市長辦公地址</th> </tr> <tr> <th>直轄市</th> <th>職稱</th> <th>姓名</th> <th>辦公地址</th> </tr> <tr> <td>臺北市</td> <td rowspan = "6">市長</td> <td>柯文哲</td> <td>臺北市信義區西村里市府路1號</td> </tr> <tr> <td>高雄市</td> <td>陳菊</td> <td>高雄市苓雅區晴朗里四維3路2號</td> </tr> <tr> <td>新北市</td> <td>朱立倫</td> <td>新北市板橋區中山路1段161號</td> </tr> <tr> <td>臺中市</td> <td>林佳龍</td> <td>臺中市西屯區臺灣大道3段99號</td> </tr> <tr> <td>臺南市</td> <td>賴清德</td> <td>臺南市安平區永華路2段6號</td> </tr> <tr> <td>桃園市</td> <td>鄭文燦</td> <td>桃園市桃園區光興里縣府路1號</td> </tr> </table> <hr> <!-- page 17 --> <a href="http://www.google.com/doodles/evidence-of-water-found-on-mars" target = "_new"> <img src="http://www.google.com/logos/doodles/2015/evidence-of-water-found-on-mars-5652760466817024.2-hp2x.gif" alt="在火星上發現水存在的證據" width = "400"> </a> <hr> <!--02 page 58 --> <h1>一個1911~2016之間的數字</h1> <p id='num1'></p> <input type="button" onclick="launch()" value="啟動"> <script> function launch(){ var number = Math.floor(Math.random()*106)+1911; d3.select('#num1').text(number); } </script> </body> </html>
Java
define("helios/Helios-Debugger", ["amber/boot", "amber_core/Kernel-Objects", "helios/Helios-Core", "helios/Helios-Workspace"], function($boot){ var smalltalk=$boot.vm,nil=$boot.nil,_st=$boot.asReceiver,globals=$boot.globals; smalltalk.addPackage('Helios-Debugger'); smalltalk.packages["Helios-Debugger"].transport = {"type":"amd","amdNamespace":"helios"}; smalltalk.addClass('HLContextInspectorDecorator', globals.Object, ['context'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "context", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@context"]; return $1; }, args: [], source: "context\x0a\x09^ context", messageSends: [], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:on:", protocol: 'evaluating', fn: function (aString,anEvaluator){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._context())._evaluate_on_(aString,anEvaluator); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:on:",{aString:aString,anEvaluator:anEvaluator},globals.HLContextInspectorDecorator)})}, args: ["aString", "anEvaluator"], source: "evaluate: aString on: anEvaluator\x0a\x09^ self context evaluate: aString on: anEvaluator", messageSends: ["evaluate:on:", "context"], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromContext:", protocol: 'initialization', fn: function (aContext){ var self=this; self["@context"]=aContext; return self}, args: ["aContext"], source: "initializeFromContext: aContext\x0a\x09context := aContext", messageSends: [], referencedClasses: [] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "inspectOn:", protocol: 'inspecting', fn: function (anInspector){ var self=this; var variables,inspectedContext; function $Dictionary(){return globals.Dictionary||(typeof Dictionary=="undefined"?nil:Dictionary)} return smalltalk.withContext(function($ctx1) { var $1,$2,$3,$4,$receiver; variables=_st($Dictionary())._new(); inspectedContext=self._context(); $1=variables; $2=_st(inspectedContext)._locals(); $ctx1.sendIdx["locals"]=1; _st($1)._addAll_($2); $ctx1.sendIdx["addAll:"]=1; _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(inspectedContext)._notNil())._and_((function(){ return smalltalk.withContext(function($ctx3) { return _st(inspectedContext)._isBlockContext(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { inspectedContext=_st(inspectedContext)._outerContext(); inspectedContext; $3=inspectedContext; if(($receiver = $3) == null || $receiver.isNil){ return $3; } else { return _st(variables)._addAll_(_st(inspectedContext)._locals()); }; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,3)})})); _st(anInspector)._setLabel_("Context"); $4=_st(anInspector)._setVariables_(variables); return self}, function($ctx1) {$ctx1.fill(self,"inspectOn:",{anInspector:anInspector,variables:variables,inspectedContext:inspectedContext},globals.HLContextInspectorDecorator)})}, args: ["anInspector"], source: "inspectOn: anInspector\x0a\x09| variables inspectedContext |\x0a\x09\x0a\x09variables := Dictionary new.\x0a\x09inspectedContext := self context.\x0a\x09\x0a\x09variables addAll: inspectedContext locals.\x0a\x09\x0a\x09[ inspectedContext notNil and: [ inspectedContext isBlockContext ] ] whileTrue: [\x0a\x09\x09inspectedContext := inspectedContext outerContext.\x0a\x09\x09inspectedContext ifNotNil: [\x0a\x09\x09\x09variables addAll: inspectedContext locals ] ].\x0a\x09\x0a\x09anInspector\x0a\x09\x09setLabel: 'Context';\x0a\x09\x09setVariables: variables", messageSends: ["new", "context", "addAll:", "locals", "whileTrue:", "and:", "notNil", "isBlockContext", "outerContext", "ifNotNil:", "setLabel:", "setVariables:"], referencedClasses: ["Dictionary"] }), globals.HLContextInspectorDecorator); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromContext_(aContext); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{aContext:aContext},globals.HLContextInspectorDecorator.klass)})}, args: ["aContext"], source: "on: aContext\x0a\x09^ self new\x0a\x09\x09initializeFromContext: aContext;\x0a\x09\x09yourself", messageSends: ["initializeFromContext:", "new", "yourself"], referencedClasses: [] }), globals.HLContextInspectorDecorator.klass); smalltalk.addClass('HLDebugger', globals.HLFocusableWidget, ['model', 'stackListWidget', 'codeWidget', 'inspectorWidget'], 'Helios-Debugger'); globals.HLDebugger.comment="I am the main widget for the Helios debugger."; smalltalk.addMethod( smalltalk.method({ selector: "codeWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLDebuggerCodeWidget(){return globals.HLDebuggerCodeWidget||(typeof HLDebuggerCodeWidget=="undefined"?nil:HLDebuggerCodeWidget)} function $HLDebuggerCodeModel(){return globals.HLDebuggerCodeModel||(typeof HLDebuggerCodeModel=="undefined"?nil:HLDebuggerCodeModel)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$6,$7,$8,$9,$5,$10,$1,$receiver; $2=self["@codeWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($HLDebuggerCodeWidget())._new(); $ctx1.sendIdx["new"]=1; $4=$3; $6=_st($HLDebuggerCodeModel())._new(); $7=$6; $8=self._model(); $ctx1.sendIdx["model"]=1; _st($7)._debuggerModel_($8); $9=_st($6)._yourself(); $ctx1.sendIdx["yourself"]=1; $5=$9; _st($4)._model_($5); _st($3)._browserModel_(self._model()); $10=_st($3)._yourself(); self["@codeWidget"]=$10; $1=self["@codeWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"codeWidget",{},globals.HLDebugger)})}, args: [], source: "codeWidget\x0a\x09^ codeWidget ifNil: [ codeWidget := HLDebuggerCodeWidget new\x0a\x09\x09model: (HLDebuggerCodeModel new\x0a\x09\x09\x09debuggerModel: self model;\x0a\x09\x09\x09yourself);\x0a\x09\x09browserModel: self model;\x0a\x09\x09yourself ]", messageSends: ["ifNil:", "model:", "new", "debuggerModel:", "model", "yourself", "browserModel:"], referencedClasses: ["HLDebuggerCodeWidget", "HLDebuggerCodeModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "cssClass", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$1; $2=($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._cssClass.apply(_st(self), [])); $ctx1.supercall = false; $1=_st($2).__comma(" hl_debugger"); return $1; }, function($ctx1) {$ctx1.fill(self,"cssClass",{},globals.HLDebugger)})}, args: [], source: "cssClass\x0a\x09^ super cssClass, ' hl_debugger'", messageSends: [",", "cssClass"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "focus", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._stackListWidget())._focus(); return self}, function($ctx1) {$ctx1.fill(self,"focus",{},globals.HLDebugger)})}, args: [], source: "focus\x0a\x09self stackListWidget focus", messageSends: ["focus", "stackListWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { self["@model"]=_st($HLDebuggerModel())._on_(anError); self._observeModel(); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError},globals.HLDebugger)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09model := HLDebuggerModel on: anError.\x0a\x09self observeModel", messageSends: ["on:", "observeModel"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "inspectorWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLInspectorWidget(){return globals.HLInspectorWidget||(typeof HLInspectorWidget=="undefined"?nil:HLInspectorWidget)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@inspectorWidget"]; if(($receiver = $2) == null || $receiver.isNil){ self["@inspectorWidget"]=_st($HLInspectorWidget())._new(); $1=self["@inspectorWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"inspectorWidget",{},globals.HLDebugger)})}, args: [], source: "inspectorWidget\x0a\x09^ inspectorWidget ifNil: [ \x0a\x09\x09inspectorWidget := HLInspectorWidget new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLInspectorWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "model", protocol: 'accessing', fn: function (){ var self=this; function $HLDebuggerModel(){return globals.HLDebuggerModel||(typeof HLDebuggerModel=="undefined"?nil:HLDebuggerModel)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@model"]; if(($receiver = $2) == null || $receiver.isNil){ self["@model"]=_st($HLDebuggerModel())._new(); $1=self["@model"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"model",{},globals.HLDebugger)})}, args: [], source: "model\x0a\x09^ model ifNil: [ model := HLDebuggerModel new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["HLDebuggerModel"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(self._model())._announcer(); _st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected:",self); $ctx1.sendIdx["on:send:to:"]=1; _st($1)._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); $ctx1.sendIdx["on:send:to:"]=2; $2=_st($1)._on_send_to_($HLDebuggerProceeded(),"onDebuggerProceeded",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLDebugger)})}, args: [], source: "observeModel\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self;\x0a\x09\x09\x0a\x09\x09on: HLDebuggerProceeded\x0a\x09\x09send: #onDebuggerProceeded\x0a\x09\x09to: self", messageSends: ["on:send:to:", "announcer", "model"], referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerProceeded"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)} return smalltalk.withContext(function($ctx1) { _st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context())); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onContextSelected: anAnnouncement\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context)", messageSends: ["inspect:", "inspectorWidget", "on:", "context"], referencedClasses: ["HLContextInspectorDecorator"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerProceeded", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._removeTab(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerProceeded",{},globals.HLDebugger)})}, args: [], source: "onDebuggerProceeded\x0a\x09self removeTab", messageSends: ["removeTab"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; function $HLContextInspectorDecorator(){return globals.HLContextInspectorDecorator||(typeof HLContextInspectorDecorator=="undefined"?nil:HLContextInspectorDecorator)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._atEnd(); if(smalltalk.assert($1)){ self._removeTab(); }; _st(self._inspectorWidget())._inspect_(_st($HLContextInspectorDecorator())._on_(_st(anAnnouncement)._context())); _st(self._stackListWidget())._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLDebugger)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09self model atEnd ifTrue: [ self removeTab ].\x0a\x09\x0a\x09self inspectorWidget inspect: (HLContextInspectorDecorator on: anAnnouncement context).\x0a\x09self stackListWidget refresh", messageSends: ["ifTrue:", "atEnd", "model", "removeTab", "inspect:", "inspectorWidget", "on:", "context", "refresh", "stackListWidget"], referencedClasses: ["HLContextInspectorDecorator"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "registerBindingsOn:", protocol: 'keybindings', fn: function (aBindingGroup){ var self=this; function $HLToolCommand(){return globals.HLToolCommand||(typeof HLToolCommand=="undefined"?nil:HLToolCommand)} return smalltalk.withContext(function($ctx1) { _st($HLToolCommand())._registerConcreteClassesOn_for_(aBindingGroup,self._model()); return self}, function($ctx1) {$ctx1.fill(self,"registerBindingsOn:",{aBindingGroup:aBindingGroup},globals.HLDebugger)})}, args: ["aBindingGroup"], source: "registerBindingsOn: aBindingGroup\x0a\x09HLToolCommand \x0a\x09\x09registerConcreteClassesOn: aBindingGroup \x0a\x09\x09for: self model", messageSends: ["registerConcreteClassesOn:for:", "model"], referencedClasses: ["HLToolCommand"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderContentOn:", protocol: 'rendering', fn: function (html){ var self=this; function $HLContainer(){return globals.HLContainer||(typeof HLContainer=="undefined"?nil:HLContainer)} function $HLVerticalSplitter(){return globals.HLVerticalSplitter||(typeof HLVerticalSplitter=="undefined"?nil:HLVerticalSplitter)} function $HLHorizontalSplitter(){return globals.HLHorizontalSplitter||(typeof HLHorizontalSplitter=="undefined"?nil:HLHorizontalSplitter)} return smalltalk.withContext(function($ctx1) { var $2,$1; self._renderHeadOn_(html); $2=_st($HLVerticalSplitter())._with_with_(self._codeWidget(),_st($HLHorizontalSplitter())._with_with_(self._stackListWidget(),self._inspectorWidget())); $ctx1.sendIdx["with:with:"]=1; $1=_st($HLContainer())._with_($2); _st(html)._with_($1); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderContentOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderContentOn: html\x0a\x09self renderHeadOn: html.\x0a\x09html with: (HLContainer with: (HLVerticalSplitter\x0a\x09\x09with: self codeWidget\x0a\x09\x09with: (HLHorizontalSplitter\x0a\x09\x09\x09with: self stackListWidget\x0a\x09\x09\x09with: self inspectorWidget)))", messageSends: ["renderHeadOn:", "with:", "with:with:", "codeWidget", "stackListWidget", "inspectorWidget"], referencedClasses: ["HLContainer", "HLVerticalSplitter", "HLHorizontalSplitter"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "renderHeadOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st(html)._div(); _st($1)._class_("head"); $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st(html)._h2())._with_(_st(_st(self._model())._error())._messageText()); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderHeadOn:",{html:html},globals.HLDebugger)})}, args: ["html"], source: "renderHeadOn: html\x0a\x09html div \x0a\x09\x09class: 'head'; \x0a\x09\x09with: [ html h2 with: self model error messageText ]", messageSends: ["class:", "div", "with:", "h2", "messageText", "error", "model"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "stackListWidget", protocol: 'widgets', fn: function (){ var self=this; function $HLStackListWidget(){return globals.HLStackListWidget||(typeof HLStackListWidget=="undefined"?nil:HLStackListWidget)} return smalltalk.withContext(function($ctx1) { var $2,$3,$4,$1,$receiver; $2=self["@stackListWidget"]; if(($receiver = $2) == null || $receiver.isNil){ $3=_st($HLStackListWidget())._on_(self._model()); _st($3)._next_(self._codeWidget()); $4=_st($3)._yourself(); self["@stackListWidget"]=$4; $1=self["@stackListWidget"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"stackListWidget",{},globals.HLDebugger)})}, args: [], source: "stackListWidget\x0a\x09^ stackListWidget ifNil: [ \x0a\x09\x09stackListWidget := (HLStackListWidget on: self model)\x0a\x09\x09\x09next: self codeWidget;\x0a\x09\x09\x09yourself ]", messageSends: ["ifNil:", "next:", "on:", "model", "codeWidget", "yourself"], referencedClasses: ["HLStackListWidget"] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "unregister", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLDebugger.superclass.fn.prototype._unregister.apply(_st(self), [])); $ctx1.supercall = false; $ctx1.sendIdx["unregister"]=1; _st(self._inspectorWidget())._unregister(); return self}, function($ctx1) {$ctx1.fill(self,"unregister",{},globals.HLDebugger)})}, args: [], source: "unregister\x0a\x09super unregister.\x0a\x09self inspectorWidget unregister", messageSends: ["unregister", "inspectorWidget"], referencedClasses: [] }), globals.HLDebugger); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromError_(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebugger.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabClass", protocol: 'accessing', fn: function (){ var self=this; return "debugger"; }, args: [], source: "tabClass\x0a\x09^ 'debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addMethod( smalltalk.method({ selector: "tabLabel", protocol: 'accessing', fn: function (){ var self=this; return "Debugger"; }, args: [], source: "tabLabel\x0a\x09^ 'Debugger'", messageSends: [], referencedClasses: [] }), globals.HLDebugger.klass); smalltalk.addClass('HLDebuggerCodeModel', globals.HLCodeModel, ['debuggerModel'], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@debuggerModel"]; return $1; }, args: [], source: "debuggerModel\x0a\x09^ debuggerModel", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "debuggerModel:", protocol: 'accessing', fn: function (anObject){ var self=this; self["@debuggerModel"]=anObject; return self}, args: ["anObject"], source: "debuggerModel: anObject\x0a\x09debuggerModel := anObject", messageSends: [], referencedClasses: [] }), globals.HLDebuggerCodeModel); smalltalk.addMethod( smalltalk.method({ selector: "doIt:", protocol: 'actions', fn: function (aString){ var self=this; function $ErrorHandler(){return globals.ErrorHandler||(typeof ErrorHandler=="undefined"?nil:ErrorHandler)} return smalltalk.withContext(function($ctx1) { var $1; $1=_st((function(){ return smalltalk.withContext(function($ctx2) { return _st(self._debuggerModel())._evaluate_(aString); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._tryCatch_((function(e){ return smalltalk.withContext(function($ctx2) { _st($ErrorHandler())._handleError_(e); return nil; }, function($ctx2) {$ctx2.fillBlock({e:e},$ctx1,2)})})); return $1; }, function($ctx1) {$ctx1.fill(self,"doIt:",{aString:aString},globals.HLDebuggerCodeModel)})}, args: ["aString"], source: "doIt: aString\x0a\x09^ [ self debuggerModel evaluate: aString ]\x0a\x09\x09tryCatch: [ :e | \x0a\x09\x09\x09ErrorHandler handleError: e.\x0a\x09\x09\x09nil ]", messageSends: ["tryCatch:", "evaluate:", "debuggerModel", "handleError:"], referencedClasses: ["ErrorHandler"] }), globals.HLDebuggerCodeModel); smalltalk.addClass('HLDebuggerCodeWidget', globals.HLBrowserCodeWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "addStopAt:", protocol: 'actions', fn: function (anInteger){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self["@editor"])._setGutterMarker_gutter_value_(anInteger,"stops",_st(_st("<div class=\x22stop\x22></stop>"._asJQuery())._toArray())._first()); return self}, function($ctx1) {$ctx1.fill(self,"addStopAt:",{anInteger:anInteger},globals.HLDebuggerCodeWidget)})}, args: ["anInteger"], source: "addStopAt: anInteger\x0a\x09editor\x0a\x09\x09setGutterMarker: anInteger\x0a\x09\x09gutter: 'stops'\x0a\x09\x09value: '<div class=\x22stop\x22></stop>' asJQuery toArray first", messageSends: ["setGutterMarker:gutter:value:", "first", "toArray", "asJQuery"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "clearHighlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._editor())._clearGutter_("stops"); return self}, function($ctx1) {$ctx1.fill(self,"clearHighlight",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "clearHighlight\x0a\x09self editor clearGutter: 'stops'", messageSends: ["clearGutter:", "editor"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "contents:", protocol: 'accessing', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { self._clearHighlight(); ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._contents_.apply(_st(self), [aString])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"contents:",{aString:aString},globals.HLDebuggerCodeWidget)})}, args: ["aString"], source: "contents: aString\x0a\x09self clearHighlight.\x0a\x09super contents: aString", messageSends: ["clearHighlight", "contents:"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "editorOptions", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._editorOptions.apply(_st(self), [])); $ctx1.supercall = false; _st($2)._at_put_("gutters",["CodeMirror-linenumbers", "stops"]); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"editorOptions",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "editorOptions\x0a\x09^ super editorOptions\x0a\x09\x09at: 'gutters' put: #('CodeMirror-linenumbers' 'stops');\x0a\x09\x09yourself", messageSends: ["at:put:", "editorOptions", "yourself"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "highlight", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$receiver; $1=_st(self._browserModel())._nextNode(); if(($receiver = $1) == null || $receiver.isNil){ $1; } else { var node; node=$receiver; self._highlightNode_(node); }; return self}, function($ctx1) {$ctx1.fill(self,"highlight",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "highlight\x0a\x09self browserModel nextNode ifNotNil: [ :node |\x0a\x09\x09self highlightNode: node ]", messageSends: ["ifNotNil:", "nextNode", "browserModel", "highlightNode:"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "highlightNode:", protocol: 'actions', fn: function (aNode){ var self=this; var token; return smalltalk.withContext(function($ctx1) { var $4,$3,$2,$1,$5,$9,$8,$7,$11,$10,$6,$15,$14,$13,$12,$receiver; if(($receiver = aNode) == null || $receiver.isNil){ aNode; } else { self._clearHighlight(); $4=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=1; $3=_st($4)._x(); $ctx1.sendIdx["x"]=1; $2=_st($3).__minus((1)); $ctx1.sendIdx["-"]=1; $1=self._addStopAt_($2); $1; $5=self._editor(); $9=_st(aNode)._positionStart(); $ctx1.sendIdx["positionStart"]=2; $8=_st($9)._x(); $ctx1.sendIdx["x"]=2; $7=_st($8).__minus((1)); $ctx1.sendIdx["-"]=2; $11=_st(_st(aNode)._positionStart())._y(); $ctx1.sendIdx["y"]=1; $10=_st($11).__minus((1)); $ctx1.sendIdx["-"]=3; $6=globals.HashedCollection._newFromPairs_(["line",$7,"ch",$10]); $15=_st(aNode)._positionEnd(); $ctx1.sendIdx["positionEnd"]=1; $14=_st($15)._x(); $13=_st($14).__minus((1)); $12=globals.HashedCollection._newFromPairs_(["line",$13,"ch",_st(_st(aNode)._positionEnd())._y()]); _st($5)._setSelection_to_($6,$12); }; return self}, function($ctx1) {$ctx1.fill(self,"highlightNode:",{aNode:aNode,token:token},globals.HLDebuggerCodeWidget)})}, args: ["aNode"], source: "highlightNode: aNode\x0a\x09| token |\x0a\x09\x0a\x09aNode ifNotNil: [\x0a\x09\x09self\x0a\x09\x09\x09clearHighlight;\x0a\x09\x09\x09addStopAt: aNode positionStart x - 1.\x0a\x0a\x09\x09self editor \x0a\x09\x09\x09setSelection: #{ 'line' -> (aNode positionStart x - 1). 'ch' -> (aNode positionStart y - 1) }\x0a\x09\x09\x09to: #{ 'line' -> (aNode positionEnd x - 1). 'ch' -> (aNode positionEnd y) } ]", messageSends: ["ifNotNil:", "clearHighlight", "addStopAt:", "-", "x", "positionStart", "setSelection:to:", "editor", "y", "positionEnd"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "observeBrowserModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { var $2,$1,$4,$3; ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._observeBrowserModel.apply(_st(self), [])); $ctx1.supercall = false; $2=self._browserModel(); $ctx1.sendIdx["browserModel"]=1; $1=_st($2)._announcer(); $ctx1.sendIdx["announcer"]=1; _st($1)._on_send_to_($HLDebuggerContextSelected(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=1; $4=self._browserModel(); $ctx1.sendIdx["browserModel"]=2; $3=_st($4)._announcer(); $ctx1.sendIdx["announcer"]=2; _st($3)._on_send_to_($HLDebuggerStepped(),"onContextSelected",self); $ctx1.sendIdx["on:send:to:"]=2; _st(_st(self._browserModel())._announcer())._on_send_to_($HLDebuggerWhere(),"onContextSelected",self); return self}, function($ctx1) {$ctx1.fill(self,"observeBrowserModel",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "observeBrowserModel\x0a\x09super observeBrowserModel.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerContextSelected\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self.\x0a\x09\x0a\x09self browserModel announcer \x0a\x09\x09on: HLDebuggerWhere\x0a\x09\x09send: #onContextSelected\x0a\x09\x09to: self", messageSends: ["observeBrowserModel", "on:send:to:", "announcer", "browserModel"], referencedClasses: ["HLDebuggerContextSelected", "HLDebuggerStepped", "HLDebuggerWhere"] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "onContextSelected", protocol: 'reactions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { self._highlight(); return self}, function($ctx1) {$ctx1.fill(self,"onContextSelected",{},globals.HLDebuggerCodeWidget)})}, args: [], source: "onContextSelected\x0a\x09self highlight", messageSends: ["highlight"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addMethod( smalltalk.method({ selector: "renderOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLDebuggerCodeWidget.superclass.fn.prototype._renderOn_.apply(_st(self), [html])); $ctx1.supercall = false; self._contents_(_st(_st(self._browserModel())._selectedMethod())._source()); return self}, function($ctx1) {$ctx1.fill(self,"renderOn:",{html:html},globals.HLDebuggerCodeWidget)})}, args: ["html"], source: "renderOn: html\x0a\x09super renderOn: html.\x0a\x09self contents: self browserModel selectedMethod source", messageSends: ["renderOn:", "contents:", "source", "selectedMethod", "browserModel"], referencedClasses: [] }), globals.HLDebuggerCodeWidget); smalltalk.addClass('HLDebuggerModel', globals.HLToolModel, ['rootContext', 'debugger', 'error'], 'Helios-Debugger'); globals.HLDebuggerModel.comment="I am a model for debugging Amber code in Helios.\x0a\x0aMy instances hold a reference to an `ASTDebugger` instance, itself referencing the current `context`. The context should be the root of the context stack."; smalltalk.addMethod( smalltalk.method({ selector: "atEnd", protocol: 'testing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._atEnd(); return $1; }, function($ctx1) {$ctx1.fill(self,"atEnd",{},globals.HLDebuggerModel)})}, args: [], source: "atEnd\x0a\x09^ self debugger atEnd", messageSends: ["atEnd", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "contexts", protocol: 'accessing', fn: function (){ var self=this; var contexts,context; function $OrderedCollection(){return globals.OrderedCollection||(typeof OrderedCollection=="undefined"?nil:OrderedCollection)} return smalltalk.withContext(function($ctx1) { var $1; contexts=_st($OrderedCollection())._new(); context=self._rootContext(); _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(context)._notNil(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._whileTrue_((function(){ return smalltalk.withContext(function($ctx2) { _st(contexts)._add_(context); context=_st(context)._outerContext(); return context; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,2)})})); $1=contexts; return $1; }, function($ctx1) {$ctx1.fill(self,"contexts",{contexts:contexts,context:context},globals.HLDebuggerModel)})}, args: [], source: "contexts\x0a\x09| contexts context |\x0a\x09\x0a\x09contexts := OrderedCollection new.\x0a\x09context := self rootContext.\x0a\x09\x0a\x09[ context notNil ] whileTrue: [\x0a\x09\x09contexts add: context.\x0a\x09\x09context := context outerContext ].\x0a\x09\x09\x0a\x09^ contexts", messageSends: ["new", "rootContext", "whileTrue:", "notNil", "add:", "outerContext"], referencedClasses: ["OrderedCollection"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._context(); return $1; }, function($ctx1) {$ctx1.fill(self,"currentContext",{},globals.HLDebuggerModel)})}, args: [], source: "currentContext\x0a\x09^ self debugger context", messageSends: ["context", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "currentContext:", protocol: 'accessing', fn: function (aContext){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} return smalltalk.withContext(function($ctx1) { var $1,$2; self._withChangesDo_((function(){ return smalltalk.withContext(function($ctx2) { self._selectedMethod_(_st(aContext)._method()); _st(self._debugger())._context_(aContext); $ctx2.sendIdx["context:"]=1; $1=_st($HLDebuggerContextSelected())._new(); _st($1)._context_(aContext); $2=_st($1)._yourself(); return _st(self._announcer())._announce_($2); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); return self}, function($ctx1) {$ctx1.fill(self,"currentContext:",{aContext:aContext},globals.HLDebuggerModel)})}, args: ["aContext"], source: "currentContext: aContext\x0a\x09self withChangesDo: [ \x0a\x09\x09self selectedMethod: aContext method.\x0a\x09\x09self debugger context: aContext.\x0a\x09\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09\x09context: aContext;\x0a\x09\x09\x09yourself) ]", messageSends: ["withChangesDo:", "selectedMethod:", "method", "context:", "debugger", "announce:", "announcer", "new", "yourself"], referencedClasses: ["HLDebuggerContextSelected"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "debugger", protocol: 'accessing', fn: function (){ var self=this; function $ASTDebugger(){return globals.ASTDebugger||(typeof ASTDebugger=="undefined"?nil:ASTDebugger)} return smalltalk.withContext(function($ctx1) { var $2,$1,$receiver; $2=self["@debugger"]; if(($receiver = $2) == null || $receiver.isNil){ self["@debugger"]=_st($ASTDebugger())._new(); $1=self["@debugger"]; } else { $1=$2; }; return $1; }, function($ctx1) {$ctx1.fill(self,"debugger",{},globals.HLDebuggerModel)})}, args: [], source: "debugger\x0a\x09^ debugger ifNil: [ debugger := ASTDebugger new ]", messageSends: ["ifNil:", "new"], referencedClasses: ["ASTDebugger"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "error", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@error"]; return $1; }, args: [], source: "error\x0a\x09^ error", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "evaluate:", protocol: 'evaluating', fn: function (aString){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._environment())._evaluate_for_(aString,self._currentContext()); return $1; }, function($ctx1) {$ctx1.fill(self,"evaluate:",{aString:aString},globals.HLDebuggerModel)})}, args: ["aString"], source: "evaluate: aString\x0a\x09^ self environment \x0a\x09\x09evaluate: aString \x0a\x09\x09for: self currentContext", messageSends: ["evaluate:for:", "environment", "currentContext"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "flushInnerContexts", protocol: 'private', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; _st($1)._innerContext_(nil); self["@rootContext"]=self._currentContext(); self._initializeContexts(); return self}, function($ctx1) {$ctx1.fill(self,"flushInnerContexts",{},globals.HLDebuggerModel)})}, args: [], source: "flushInnerContexts\x0a\x09\x22When stepping, the inner contexts are not relevent anymore,\x0a\x09and can be flushed\x22\x0a\x09\x0a\x09self currentContext innerContext: nil.\x0a\x09rootContext := self currentContext.\x0a\x09self initializeContexts", messageSends: ["innerContext:", "currentContext", "initializeContexts"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "initializeFromError:", protocol: 'initialization', fn: function (anError){ var self=this; var errorContext; function $AIContext(){return globals.AIContext||(typeof AIContext=="undefined"?nil:AIContext)} return smalltalk.withContext(function($ctx1) { self["@error"]=anError; errorContext=_st($AIContext())._fromMethodContext_(_st(self["@error"])._context()); self["@rootContext"]=_st(self["@error"])._signalerContextFrom_(errorContext); self._selectedMethod_(_st(self["@rootContext"])._method()); return self}, function($ctx1) {$ctx1.fill(self,"initializeFromError:",{anError:anError,errorContext:errorContext},globals.HLDebuggerModel)})}, args: ["anError"], source: "initializeFromError: anError\x0a\x09| errorContext |\x0a\x09\x0a\x09error := anError.\x0a\x09errorContext := (AIContext fromMethodContext: error context).\x0a\x09rootContext := error signalerContextFrom: errorContext.\x0a\x09self selectedMethod: rootContext method", messageSends: ["fromMethodContext:", "context", "signalerContextFrom:", "selectedMethod:", "method"], referencedClasses: ["AIContext"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "nextNode", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._debugger())._node(); return $1; }, function($ctx1) {$ctx1.fill(self,"nextNode",{},globals.HLDebuggerModel)})}, args: [], source: "nextNode\x0a\x09^ self debugger node", messageSends: ["node", "debugger"], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "onStep", protocol: 'reactions', fn: function (){ var self=this; function $HLDebuggerContextSelected(){return globals.HLDebuggerContextSelected||(typeof HLDebuggerContextSelected=="undefined"?nil:HLDebuggerContextSelected)} return smalltalk.withContext(function($ctx1) { var $2,$1,$3,$4; self["@rootContext"]=self._currentContext(); $ctx1.sendIdx["currentContext"]=1; $2=self._currentContext(); $ctx1.sendIdx["currentContext"]=2; $1=_st($2)._method(); self._selectedMethod_($1); $3=_st($HLDebuggerContextSelected())._new(); _st($3)._context_(self._currentContext()); $4=_st($3)._yourself(); _st(self._announcer())._announce_($4); return self}, function($ctx1) {$ctx1.fill(self,"onStep",{},globals.HLDebuggerModel)})}, args: [], source: "onStep\x0a\x09rootContext := self currentContext.\x0a\x09\x0a\x09\x22Force a refresh of the context list and code widget\x22\x0a\x09self selectedMethod: self currentContext method.\x0a\x09self announcer announce: (HLDebuggerContextSelected new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["currentContext", "selectedMethod:", "method", "announce:", "announcer", "context:", "new", "yourself"], referencedClasses: ["HLDebuggerContextSelected"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerProceeded(){return globals.HLDebuggerProceeded||(typeof HLDebuggerProceeded=="undefined"?nil:HLDebuggerProceeded)} return smalltalk.withContext(function($ctx1) { _st(self._debugger())._proceed(); _st(self._announcer())._announce_(_st($HLDebuggerProceeded())._new()); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLDebuggerModel)})}, args: [], source: "proceed\x0a\x09self debugger proceed.\x0a\x09\x0a\x09self announcer announce: HLDebuggerProceeded new", messageSends: ["proceed", "debugger", "announce:", "announcer", "new"], referencedClasses: ["HLDebuggerProceeded"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._restart(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLDebuggerModel)})}, args: [], source: "restart\x0a\x09self debugger restart.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["restart", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "rootContext", protocol: 'accessing', fn: function (){ var self=this; var $1; $1=self["@rootContext"]; return $1; }, args: [], source: "rootContext\x0a\x09^ rootContext", messageSends: [], referencedClasses: [] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { var $1,$2; _st(self._debugger())._stepOver(); self._onStep(); $1=_st($HLDebuggerStepped())._new(); _st($1)._context_(self._currentContext()); $2=_st($1)._yourself(); _st(self._announcer())._announce_($2); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLDebuggerModel)})}, args: [], source: "stepOver\x0a\x09self debugger stepOver.\x0a\x09self onStep.\x0a\x09\x0a\x09self announcer announce: (HLDebuggerStepped new\x0a\x09\x09context: self currentContext;\x0a\x09\x09yourself)", messageSends: ["stepOver", "debugger", "onStep", "announce:", "announcer", "context:", "new", "currentContext", "yourself"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerWhere(){return globals.HLDebuggerWhere||(typeof HLDebuggerWhere=="undefined"?nil:HLDebuggerWhere)} return smalltalk.withContext(function($ctx1) { _st(self._announcer())._announce_(_st($HLDebuggerWhere())._new()); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLDebuggerModel)})}, args: [], source: "where\x0a\x09self announcer announce: HLDebuggerWhere new", messageSends: ["announce:", "announcer", "new"], referencedClasses: ["HLDebuggerWhere"] }), globals.HLDebuggerModel); smalltalk.addMethod( smalltalk.method({ selector: "on:", protocol: 'instance creation', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { var $2,$3,$1; $2=self._new(); _st($2)._initializeFromError_(anError); $3=_st($2)._yourself(); $1=$3; return $1; }, function($ctx1) {$ctx1.fill(self,"on:",{anError:anError},globals.HLDebuggerModel.klass)})}, args: ["anError"], source: "on: anError\x0a\x09^ self new\x0a\x09\x09initializeFromError: anError;\x0a\x09\x09yourself", messageSends: ["initializeFromError:", "new", "yourself"], referencedClasses: [] }), globals.HLDebuggerModel.klass); smalltalk.addClass('HLErrorHandler', globals.Object, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "confirmDebugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $HLConfirmationWidget(){return globals.HLConfirmationWidget||(typeof HLConfirmationWidget=="undefined"?nil:HLConfirmationWidget)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($HLConfirmationWidget())._new(); _st($1)._confirmationString_(_st(anError)._messageText()); _st($1)._actionBlock_((function(){ return smalltalk.withContext(function($ctx2) { return self._debugError_(anError); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); _st($1)._cancelButtonLabel_("Abandon"); _st($1)._confirmButtonLabel_("Debug"); $2=_st($1)._show(); return self}, function($ctx1) {$ctx1.fill(self,"confirmDebugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "confirmDebugError: anError\x0a\x09HLConfirmationWidget new\x0a\x09\x09confirmationString: anError messageText;\x0a\x09\x09actionBlock: [ self debugError: anError ];\x0a\x09\x09cancelButtonLabel: 'Abandon';\x0a\x09\x09confirmButtonLabel: 'Debug';\x0a\x09\x09show", messageSends: ["confirmationString:", "new", "messageText", "actionBlock:", "debugError:", "cancelButtonLabel:", "confirmButtonLabel:", "show"], referencedClasses: ["HLConfirmationWidget"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "debugError:", protocol: 'error handling', fn: function (anError){ var self=this; function $HLDebugger(){return globals.HLDebugger||(typeof HLDebugger=="undefined"?nil:HLDebugger)} function $Error(){return globals.Error||(typeof Error=="undefined"?nil:Error)} function $ConsoleErrorHandler(){return globals.ConsoleErrorHandler||(typeof ConsoleErrorHandler=="undefined"?nil:ConsoleErrorHandler)} return smalltalk.withContext(function($ctx1) { _st((function(){ return smalltalk.withContext(function($ctx2) { return _st(_st($HLDebugger())._on_(anError))._openAsTab(); }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})}))._on_do_($Error(),(function(error){ return smalltalk.withContext(function($ctx2) { return _st(_st($ConsoleErrorHandler())._new())._handleError_(error); }, function($ctx2) {$ctx2.fillBlock({error:error},$ctx1,2)})})); return self}, function($ctx1) {$ctx1.fill(self,"debugError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "debugError: anError\x0a\x0a\x09[ \x0a\x09\x09(HLDebugger on: anError) openAsTab \x0a\x09] \x0a\x09\x09on: Error \x0a\x09\x09do: [ :error | ConsoleErrorHandler new handleError: error ]", messageSends: ["on:do:", "openAsTab", "on:", "handleError:", "new"], referencedClasses: ["HLDebugger", "Error", "ConsoleErrorHandler"] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "handleError:", protocol: 'error handling', fn: function (anError){ var self=this; return smalltalk.withContext(function($ctx1) { self._confirmDebugError_(anError); return self}, function($ctx1) {$ctx1.fill(self,"handleError:",{anError:anError},globals.HLErrorHandler)})}, args: ["anError"], source: "handleError: anError\x0a\x09self confirmDebugError: anError", messageSends: ["confirmDebugError:"], referencedClasses: [] }), globals.HLErrorHandler); smalltalk.addMethod( smalltalk.method({ selector: "onErrorHandled", protocol: 'error handling', fn: function (){ var self=this; function $HLProgressWidget(){return globals.HLProgressWidget||(typeof HLProgressWidget=="undefined"?nil:HLProgressWidget)} return smalltalk.withContext(function($ctx1) { var $1,$2; $1=_st($HLProgressWidget())._default(); _st($1)._flush(); $2=_st($1)._remove(); return self}, function($ctx1) {$ctx1.fill(self,"onErrorHandled",{},globals.HLErrorHandler)})}, args: [], source: "onErrorHandled\x0a\x09\x22when an error is handled, we need to make sure that\x0a\x09any progress bar widget gets removed. Because HLProgressBarWidget is asynchronous,\x0a\x09it has to be done here.\x22\x0a\x09\x0a\x09HLProgressWidget default \x0a\x09\x09flush; \x0a\x09\x09remove", messageSends: ["flush", "default", "remove"], referencedClasses: ["HLProgressWidget"] }), globals.HLErrorHandler); smalltalk.addClass('HLStackListWidget', globals.HLToolListWidget, [], 'Helios-Debugger'); smalltalk.addMethod( smalltalk.method({ selector: "items", protocol: 'accessing', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._contexts(); return $1; }, function($ctx1) {$ctx1.fill(self,"items",{},globals.HLStackListWidget)})}, args: [], source: "items\x0a\x09^ self model contexts", messageSends: ["contexts", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "label", protocol: 'accessing', fn: function (){ var self=this; return "Call stack"; }, args: [], source: "label\x0a\x09^ 'Call stack'", messageSends: [], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "observeModel", protocol: 'actions', fn: function (){ var self=this; function $HLDebuggerStepped(){return globals.HLDebuggerStepped||(typeof HLDebuggerStepped=="undefined"?nil:HLDebuggerStepped)} return smalltalk.withContext(function($ctx1) { ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._observeModel.apply(_st(self), [])); $ctx1.supercall = false; _st(_st(self._model())._announcer())._on_send_to_($HLDebuggerStepped(),"onDebuggerStepped:",self); return self}, function($ctx1) {$ctx1.fill(self,"observeModel",{},globals.HLStackListWidget)})}, args: [], source: "observeModel\x0a\x09super observeModel.\x0a\x09\x0a\x09self model announcer \x0a\x09\x09on: HLDebuggerStepped\x0a\x09\x09send: #onDebuggerStepped:\x0a\x09\x09to: self", messageSends: ["observeModel", "on:send:to:", "announcer", "model"], referencedClasses: ["HLDebuggerStepped"] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "onDebuggerStepped:", protocol: 'reactions', fn: function (anAnnouncement){ var self=this; return smalltalk.withContext(function($ctx1) { self["@items"]=nil; self._refresh(); return self}, function($ctx1) {$ctx1.fill(self,"onDebuggerStepped:",{anAnnouncement:anAnnouncement},globals.HLStackListWidget)})}, args: ["anAnnouncement"], source: "onDebuggerStepped: anAnnouncement\x0a\x09items := nil.\x0a\x09self refresh", messageSends: ["refresh"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "proceed", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._proceed(); return self}, function($ctx1) {$ctx1.fill(self,"proceed",{},globals.HLStackListWidget)})}, args: [], source: "proceed\x0a\x09self model proceed", messageSends: ["proceed", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "renderButtonsOn:", protocol: 'rendering', fn: function (html){ var self=this; return smalltalk.withContext(function($ctx1) { var $1,$3,$4,$5,$6,$7,$8,$9,$10,$2; $1=_st(html)._div(); _st($1)._class_("debugger_bar"); $ctx1.sendIdx["class:"]=1; $2=_st($1)._with_((function(){ return smalltalk.withContext(function($ctx2) { $3=_st(html)._button(); $ctx2.sendIdx["button"]=1; _st($3)._class_("btn restart"); $ctx2.sendIdx["class:"]=2; _st($3)._with_("Restart"); $ctx2.sendIdx["with:"]=2; $4=_st($3)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._restart(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,2)})})); $ctx2.sendIdx["onClick:"]=1; $4; $5=_st(html)._button(); $ctx2.sendIdx["button"]=2; _st($5)._class_("btn where"); $ctx2.sendIdx["class:"]=3; _st($5)._with_("Where"); $ctx2.sendIdx["with:"]=3; $6=_st($5)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._where(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,3)})})); $ctx2.sendIdx["onClick:"]=2; $6; $7=_st(html)._button(); $ctx2.sendIdx["button"]=3; _st($7)._class_("btn stepOver"); $ctx2.sendIdx["class:"]=4; _st($7)._with_("Step over"); $ctx2.sendIdx["with:"]=4; $8=_st($7)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._stepOver(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,4)})})); $ctx2.sendIdx["onClick:"]=3; $8; $9=_st(html)._button(); _st($9)._class_("btn proceed"); _st($9)._with_("Proceed"); $10=_st($9)._onClick_((function(){ return smalltalk.withContext(function($ctx3) { return self._proceed(); }, function($ctx3) {$ctx3.fillBlock({},$ctx2,5)})})); return $10; }, function($ctx2) {$ctx2.fillBlock({},$ctx1,1)})})); $ctx1.sendIdx["with:"]=1; return self}, function($ctx1) {$ctx1.fill(self,"renderButtonsOn:",{html:html},globals.HLStackListWidget)})}, args: ["html"], source: "renderButtonsOn: html\x0a\x09html div \x0a\x09\x09class: 'debugger_bar'; \x0a\x09\x09with: [\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn restart';\x0a\x09\x09\x09\x09with: 'Restart';\x0a\x09\x09\x09\x09onClick: [ self restart ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn where';\x0a\x09\x09\x09\x09with: 'Where';\x0a\x09\x09\x09\x09onClick: [ self where ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn stepOver';\x0a\x09\x09\x09\x09with: 'Step over';\x0a\x09\x09\x09\x09onClick: [ self stepOver ].\x0a\x09\x09\x09html button \x0a\x09\x09\x09\x09class: 'btn proceed';\x0a\x09\x09\x09\x09with: 'Proceed';\x0a\x09\x09\x09\x09onClick: [ self proceed ] ]", messageSends: ["class:", "div", "with:", "button", "onClick:", "restart", "where", "stepOver", "proceed"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "restart", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._restart(); return self}, function($ctx1) {$ctx1.fill(self,"restart",{},globals.HLStackListWidget)})}, args: [], source: "restart\x0a\x09self model restart", messageSends: ["restart", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectItem:", protocol: 'actions', fn: function (aContext){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._currentContext_(aContext); ($ctx1.supercall = true, globals.HLStackListWidget.superclass.fn.prototype._selectItem_.apply(_st(self), [aContext])); $ctx1.supercall = false; return self}, function($ctx1) {$ctx1.fill(self,"selectItem:",{aContext:aContext},globals.HLStackListWidget)})}, args: ["aContext"], source: "selectItem: aContext\x0a \x09self model currentContext: aContext.\x0a\x09super selectItem: aContext", messageSends: ["currentContext:", "model", "selectItem:"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "selectedItem", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { var $1; $1=_st(self._model())._currentContext(); return $1; }, function($ctx1) {$ctx1.fill(self,"selectedItem",{},globals.HLStackListWidget)})}, args: [], source: "selectedItem\x0a \x09^ self model currentContext", messageSends: ["currentContext", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "stepOver", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._stepOver(); return self}, function($ctx1) {$ctx1.fill(self,"stepOver",{},globals.HLStackListWidget)})}, args: [], source: "stepOver\x0a\x09self model stepOver", messageSends: ["stepOver", "model"], referencedClasses: [] }), globals.HLStackListWidget); smalltalk.addMethod( smalltalk.method({ selector: "where", protocol: 'actions', fn: function (){ var self=this; return smalltalk.withContext(function($ctx1) { _st(self._model())._where(); return self}, function($ctx1) {$ctx1.fill(self,"where",{},globals.HLStackListWidget)})}, args: [], source: "where\x0a\x09self model where", messageSends: ["where", "model"], referencedClasses: [] }), globals.HLStackListWidget); });
Java
MIME-Version: 1.0 Server: CERN/3.0 Date: Monday, 16-Dec-96 23:33:46 GMT Content-Type: text/html Content-Length: 3390 Last-Modified: Tuesday, 20-Feb-96 22:21:50 GMT <html> <head> <title> CodeWarrior for CS100 </title> </head> <body> <h2> Setting Up CodeWarrior for CS100 </h2> CodeWarrior can be run on your own personal Macintosh. Copies of CodeWarrior 8 can be purchased from the Campus Store. The CodeWarrior installed in the CIT labs is just like the one you would install on your Mac, except for a few things we have added -- the CSLib library and the CS100 Basic project stationery. <p> <strong>Note:</strong> These additions were built using CodeWarrior version 8, so it is possible that they will not work with earlier versions of CodeWarrior (although we have heard from people that they do). <p> Once you have retrieved the CS100 Additions folder, install the additions as follows: <ul> <li> Open the CS100 Additions folder. Inside it there is a SimpleText file containing instructions similar to these. There are two folders called INTO MacOS Support and INTO (Project Stationery). The folder structure in the CS100 Additions folder is meant to mirror the folder structure inside the Metrowerks CodeWarrior folder of your copy of CodeWarrior, to make it easy to follow these instructions. <p> <li> Open your CodeWarrior8 or CW 8 Gold folder. Open the Metrowerks CodeWarrior folder inside it. <p> <li> Open the INTO MacOS Support folder in the CS100 additions. Move the CS100 Support folder into the MacOS Support folder in your Metrowerks CodeWarrior folder. <p> <li> Open the INTO (Project Stationery) folder. Move the CS100 Basic 68K.mu file into the (Project Stationery) folder in your Metrowerks CodeWarrior folder. <p> <li> Open the INTO Proj. Stat. Support folder in the INTO (Project Stationery) folder. Move the <replace me CS100>.c file into the Project Stationery Support folder in the (Project Stationery) folder of your CodeWarrior. <p> </ul> When you open a new project with CodeWarrior, you should now be able to select the CS100 Basic 68K stationery. This will include the CSLib library, which should also now be available to you. <hr> Click here to get the CS100 Additions folder. <p> <a href = "ftp://ftp.cs.cornell.edu/pub/courses/cs100-s96/CS100Additions.sea.hqx"> CS100 Additions Folder </a> <hr> <h3>Other Machines</h3> If you have a copy of CodeWarrior for a computer other than the Mac, you may still be able to set up the CS100 environment. However, the course staff will not be able support this. <ol> <li> Build the CSLib library. Get the source code for by anonymous FTP from Addison-Wesley. Follow the instructions on page 670 in the Roberts textbook (Appendix B, Library Sources). Compile the source code on your machine using CodeWarrior. (To create the CSLib library for CS100 we only compiled the <code>genlib</code>, <code>simpio</code>, <code>string</code>, <code>random</code>, and <code>exception</code> parts of the library; we left out the graphics stuff. If everything seems to work for your machine, feel free to compile all of it.) Put the compiled library and the library header files into the support directory for your CodeWarrior. <p> <li> Make the CS100 Basic project stationery. Our project stationery is based on the ANSI project stationery, with the CSLib library added. Put your project stationery in the project stationery directory of your CodeWarrior. </ol> </body> <hr> <address> CS100 Spring 1996 <br> pierce@cs.cornell.edu </address> </html>
Java
<div ng-class="{ invalid: !ngDisabled && !valid }"> <div class="form-group"> <label ng-show="ngLabel" class="control-label">{{ngLabel}}<small ng-show="ngTip">({{ngTip}})</small></label> <div class="row coordinates-container"> <div class="col-sm-6 form-control-feedback-container" ng-class="{ 'has-error': !ngDisabled && !valid && coordinates.longitude === '', 'has-feedback': !ngDisabled && !valid && coordinates.longitude === '' }"> <input type="text" class="form-control" ng-disabled="ngDisabled" ng-class="{ 'coordinates-invalid': !ngDisabled && !valid && coordinates.longitude === '' }" ng-model="coordinates.longitude" ng-change="changed()" placeholder="longitude" ng-keypress="preventInvalidCharaters($event)" /> <span ng-show="!ngDisabled && !valid && coordinates.longitude === ''" tooltip="value is required" class="glyphicon glyphicon-ban-circle form-control-feedback"></span> </div> <div class="col-sm-6 form-control-feedback-container" ng-class="{ 'has-error': !ngDisabled && !valid && coordinates.latitude === '', 'has-feedback': !ngDisabled && !valid.latitude === '' }"> <input type="text" class="form-control" ng-disabled="ngDisabled" ng-class="{ 'coordinates-invalid': !ngDisabled && !valid && coordinates.latitude === '' }" ng-model="coordinates.latitude" ng-change="changed()" placeholder="latitude" ng-keypress="preventInvalidCharaters($event)" /> <span ng-show="!ngDisabled && !valid && coordinates.latitude === ''" tooltip="value is required" class="glyphicon glyphicon-ban-circle form-control-feedback"></span> </div> </div> <div class="map-container" ng-class="{ 'map-disabled': ngDisabled }"> <div id="map{{id}}" class="form-map" ng-style="{ 'height': height }"></div> </div> </div> </div>
Java
def calc(): h, l = input().split(' ') mapa = [] for i_row in range(int(h)): mapa.append(input().split(' ')) maior_num = 0 for row in mapa: for col in row: n = int(col) if (n > maior_num): maior_num = n qtd = [0 for i in range(maior_num + 1)] for row in mapa: for col in row: n = int(col) qtd[n] = qtd[n] + 1 menor = 1 for i in range(1, len(qtd)): if (qtd[i] <= qtd[menor]): menor = i print(menor) calc()
Java
package com.stulsoft.ysps.pduration import scala.concurrent.duration._ /** * @author Yuriy Stul. * Created on 9/15/2016. */ object PDuration { def main(args: Array[String]): Unit = { println("==>main") var fiveSec = 5.seconds println(s"fiveSec=$fiveSec") fiveSec = 15.seconds println(s"fiveSec=$fiveSec") println("<==main") } }
Java
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QApplication> #include <QMainWindow> #include <QTextEdit> #include <QMenu> #include <QMenuBar> #include <QAction> #include <QDialog> #include <QDesktopWidget> #include <QMdiArea> #include <QMdiSubWindow> #include <QDockWidget> #include <QTreeWidget> #include <QProcess> #include <QTimer> #include <vector> #include <cassert> #include "CodeArea.h" #include "Console.h" #include "FnSelectDialog.h" #include "Outline.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); QSize sizeHint() const; void flattenedOutline(FlattenedOutline *outline) const; signals: public slots: void fnSelect(); void toggleSimple(); void openFileDialog(); void saveFile(); void saveFileAsDialog(); void setActiveCodeArea(QMdiSubWindow *area); void runProgram(); void runPythonParser(); void updateConsoleFromProcess(); void updateCodeOutlineFromProcess(int exitCode, QProcess::ExitStatus exitStatus); void jumpToFunction(QTreeWidgetItem* item, int column); private: QMdiArea *mainArea; // process QProcess *programProcess; QProcess *pythonParserProcess; // console Console *console; QDockWidget *consoleDock; // editor CodeArea *activeCodeArea; std::vector<CodeArea*> codeAreas; FnSelectDialog *fnSelectDialog; // code outline QTreeWidget *codeOutline; QDockWidget *codeOutlineDock; std::vector<OutlineClass> outlineClasses; QTreeWidgetItem *functionsHeader; // timer QTimer *parseTimer; // console actions QAction *runProgramAction; // menus QMenu *fileMenu; QMenu *helpMenu; // menu actions QAction *openFileAction; QAction *saveFileAction; QAction *saveFileAsAction; // code actions QAction *fnSelectAction; // ui actions QAction *toggleSimpleAction; bool usingSimple; // project actions QAction *addFileToProjectAction; QAction *removeFileFromProjectAction; // git actions QAction *openGitDialogAction; // program actions QAction *exitProgramAction; // meta QString lastUsedDirectory; }; #endif
Java
/** * Error for services to through when they encounter a problem with the request. * Distinguishes between a bad service request and a general error */ function ServiceError(message) { this.name = "ServiceError"; this.message = (message || ""); } ServiceError.prototype = Object.create(Error.prototype, { constructor: {value: ServiceError} }); /** * Error for when an item is not found */ function NotFoundError(message) { this.name = "NotFoundError"; this.message = (message || "Not found"); } NotFoundError.prototype = Object.create(ServiceError.prototype, { constructor: { value: NotFoundError} }); exports.ServiceError = ServiceError; exports.NotFoundError = NotFoundError;
Java
import shaven from 'shaven' const svgNS = 'http://www.w3.org/2000/svg' export default function (svg, config) { const yDensity = 0.1 const yRange = config.max.value - config.min.value const graphHeight = config.height * 0.8 const graphWidth = config.width * 0.95 const coSysHeight = config.height * 0.6 const coSysWidth = config.width * 0.85 const barchart = shaven( ['g', { transform: 'translate(' + [graphWidth * 0.1, graphHeight].join() + ')', }], svgNS, )[0] const coordinateSystem = shaven(['g'], svgNS)[0] const bars = shaven(['g'], svgNS)[0] function buildCoordinateSystem () { function ordinates () { let cssClass let index for (index = 0; index < config.size; index++) { cssClass = index === 0 ? 'vectual_coordinate_axis_y' : 'vectual_coordinate_lines_y' shaven( [coordinateSystem, ['line', { class: cssClass, x1: (coSysWidth / config.size) * index, y1: '5', x2: (coSysWidth / config.size) * index, y2: -coSysHeight, }], ['text', config.keys[index], { class: 'vectual_coordinate_labels_x', transform: 'rotate(40 ' + ((coSysWidth / config.size) * index) + ', 10)', // eslint-disable-next-line id-length x: (coSysWidth / config.size) * index, y: 10, // eslint-disable-line id-length }], ], svgNS, ) } } function abscissas () { let styleClass let index for (index = 0; index <= (yRange * yDensity); index++) { styleClass = index === 0 ? 'vectual_coordinate_axis_x' : 'vectual_coordinate_lines_x' shaven( [coordinateSystem, ['line', { class: styleClass, x1: -5, y1: -(coSysHeight / yRange) * (index / yDensity), x2: coSysWidth, y2: -(coSysHeight / yRange) * (index / yDensity), }], ['text', String(index / yDensity + config.min.value), { class: 'vectual_coordinate_labels_y', x: -coSysWidth * 0.05, // eslint-disable-line id-length // eslint-disable-next-line id-length y: -(coSysHeight / yRange) * (index / yDensity), }], ], svgNS, ) } } abscissas() ordinates() } function buildBars () { function drawBar (element, index) { const height = config.animations ? 0 : (config.values[index] - config.min.value) * (coSysHeight / yRange) const bar = shaven( ['rect', { class: 'vectual_bar_bar', // eslint-disable-next-line id-length x: index * (coSysWidth / config.size), // eslint-disable-next-line id-length y: -(config.values[index] - config.min.value) * (coSysHeight / yRange), height: height, width: 0.7 * (coSysWidth / config.size), }, ['title', config.keys[index] + ': ' + config.values[index]], ], svgNS, )[0] function localSetAnimations () { shaven( [bar, ['animate', { attributeName: 'height', to: (config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'y', from: 0, to: -(config.values[index] - config.min.value) * (coSysHeight / yRange), begin: '0s', dur: '1s', fill: 'freeze', }], ['animate', { attributeName: 'fill', to: 'rgb(100,210,255)', begin: 'mouseover', dur: '100ms', fill: 'freeze', additive: 'replace', }], ['animate', { attributeName: 'fill', to: 'rgb(0,150,250)', begin: 'mouseout', dur: '200ms', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function localInject () { shaven([bars, [bar]]) } if (config.animations) localSetAnimations() localInject() } config.data.forEach(drawBar) } function setAnimations () { shaven( [bars, ['animate', { attributeName: 'opacity', from: 0, to: 0.8, begin: '0s', dur: '1s', fill: 'freeze', additive: 'replace', }], ], svgNS, ) } function inject () { shaven( [svg, [barchart, [coordinateSystem], [bars], ], ], ) } buildCoordinateSystem() buildBars() if (config.animations) setAnimations() inject() return svg }
Java
require File.dirname(__FILE__) + '/spec' class Object class << self # Lookup missing generators using const_missing. This allows any # generator to reference another without having to know its location: # RubyGems, ~/.rubigen/generators, and APP_ROOT/generators. def lookup_missing_generator(class_id) if md = /(.+)Generator$/.match(class_id.to_s) name = md.captures.first.demodulize.underscore RubiGen::Base.active.lookup(name).klass else const_missing_before_generators(class_id) end end unless respond_to?(:const_missing_before_generators) alias_method :const_missing_before_generators, :const_missing alias_method :const_missing, :lookup_missing_generator end end end # User home directory lookup adapted from RubyGems. def Dir.user_home if ENV['HOME'] ENV['HOME'] elsif ENV['USERPROFILE'] ENV['USERPROFILE'] elsif ENV['HOMEDRIVE'] and ENV['HOMEPATH'] "#{ENV['HOMEDRIVE']}:#{ENV['HOMEPATH']}" else File.expand_path '~' end end module RubiGen # Generator lookup is managed by a list of sources which return specs # describing where to find and how to create generators. This module # provides class methods for manipulating the source list and looking up # generator specs, and an #instance wrapper for quickly instantiating # generators by name. # # A spec is not a generator: it's a description of where to find # the generator and how to create it. A source is anything that # yields generators from #each. PathSource and GemGeneratorSource are provided. module Lookup def self.included(base) base.extend(ClassMethods) # base.use_component_sources! # TODO is this required since it has no scope/source context end # Convenience method to instantiate another generator. def instance(generator_name, args, runtime_options = {}) self.class.active.instance(generator_name, args, runtime_options) end module ClassMethods # The list of sources where we look, in order, for generators. def sources if read_inheritable_attribute(:sources).blank? if superclass == RubiGen::Base superclass_sources = superclass.sources diff = superclass_sources.inject([]) do |mem, source| found = false application_sources.each { |app_source| found ||= true if app_source == source} mem << source unless found mem end write_inheritable_attribute(:sources, diff) end active.use_component_sources! if read_inheritable_attribute(:sources).blank? end read_inheritable_attribute(:sources) end # Add a source to the end of the list. def append_sources(*args) sources.concat(args.flatten) invalidate_cache! end # Add a source to the beginning of the list. def prepend_sources(*args) sources = self.sources reset_sources write_inheritable_array(:sources, args.flatten + sources) invalidate_cache! end # Reset the source list. def reset_sources write_inheritable_attribute(:sources, []) invalidate_cache! end # Use application generators (app, ?). def use_application_sources!(*filters) reset_sources write_inheritable_attribute(:sources, application_sources(filters)) end def application_sources(filters = []) filters.unshift 'app' app_sources = [] app_sources << PathSource.new(:builtin, File.join(File.dirname(__FILE__), %w[.. .. app_generators])) app_sources << filtered_sources(filters) app_sources.flatten end # Use component generators (test_unit, etc). # 1. Current application. If APP_ROOT is defined we know we're # generating in the context of this application, so search # APP_ROOT/generators. # 2. User home directory. Search ~/.rubigen/generators. # 3. RubyGems. Search for gems containing /{scope}_generators folder. # 4. Builtins. None currently. # # Search can be filtered by passing one or more prefixes. # e.g. use_component_sources!(:rubygems) means it will also search in the following # folders: # 5. User home directory. Search ~/.rubigen/rubygems_generators. # 6. RubyGems. Search for gems containing /rubygems_generators folder. def use_component_sources!(*filters) reset_sources new_sources = [] if defined? ::APP_ROOT new_sources << PathSource.new(:root, "#{::APP_ROOT}/generators") new_sources << PathSource.new(:vendor, "#{::APP_ROOT}/vendor/generators") new_sources << PathSource.new(:plugins, "#{::APP_ROOT}/vendor/plugins/*/**/generators") end new_sources << filtered_sources(filters) write_inheritable_attribute(:sources, new_sources.flatten) end def filtered_sources(filters) new_sources = [] new_sources << PathFilteredSource.new(:user, "#{Dir.user_home}/.rubigen/", *filters) if Object.const_defined?(:Gem) new_sources << GemPathSource.new(*filters) end new_sources end # Lookup knows how to find generators' Specs from a list of Sources. # Searches the sources, in order, for the first matching name. def lookup(generator_name) @found ||= {} generator_name = generator_name.to_s.downcase @found[generator_name] ||= cache.find { |spec| spec.name == generator_name } unless @found[generator_name] chars = generator_name.scan(/./).map{|c|"#{c}.*?"} rx = /^#{chars}$/ gns = cache.select {|spec| spec.name =~ rx } @found[generator_name] ||= gns.first if gns.length == 1 raise GeneratorError, "Pattern '#{generator_name}' matches more than one generator: #{gns.map{|sp|sp.name}.join(', ')}" if gns.length > 1 end @found[generator_name] or raise GeneratorError, "Couldn't find '#{generator_name}' generator" end # Convenience method to lookup and instantiate a generator. def instance(generator_name, args = [], runtime_options = {}) active.lookup(generator_name).klass.new(args, full_options(runtime_options)) end private # Lookup and cache every generator from the source list. def cache @cache ||= sources.inject([]) { |cache, source| cache + source.to_a } end # Clear the cache whenever the source list changes. def invalidate_cache! @cache = nil end end end # Sources enumerate (yield from #each) generator specs which describe # where to find and how to create generators. Enumerable is mixed in so, # for example, source.collect will retrieve every generator. # Sources may be assigned a label to distinguish them. class Source include Enumerable attr_reader :label def initialize(label) @label = label end # The each method must be implemented in subclasses. # The base implementation raises an error. def each raise NotImplementedError end # Return a convenient sorted list of all generator names. def names(filter = nil) inject([]) do |mem, spec| case filter when :visible mem << spec.name if spec.visible? end mem end.sort end end # PathSource looks for generators in a filesystem directory. class PathSource < Source attr_reader :path def initialize(label, path) super label @path = File.expand_path path end # Yield each eligible subdirectory. def each Dir["#{path}/[a-z]*"].each do |dir| if File.directory?(dir) yield Spec.new(File.basename(dir), dir, label) end end end def ==(source) self.class == source.class && path == source.path end end class PathFilteredSource < PathSource attr_reader :filters def initialize(label, path, *filters) super label, File.join(path, "#{filter_str(filters)}generators") end def filter_str(filters) @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if @filters.blank? filter_str = @filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end def ==(source) self.class == source.class && path == source.path && filters == source.filters && label == source.label end end class AbstractGemSource < Source def initialize super :RubyGems end end # GemPathSource looks for generators within any RubyGem's /{filter_}generators/**/<generator_name>_generator.rb file. class GemPathSource < AbstractGemSource attr_accessor :filters def initialize(*filters) super() @filters = filters end # Yield each generator within rails_generator subdirectories. def each generator_full_paths.each do |generator| yield Spec.new(File.basename(generator).sub(/_generator.rb$/, ''), File.dirname(generator), label) end end def ==(source) self.class == source.class && filters == source.filters end private def generator_full_paths @generator_full_paths ||= Gem::cache.inject({}) do |latest, name_gem| name, gem = name_gem hem = latest[gem.name] latest[gem.name] = gem if hem.nil? or gem.version > hem.version latest end.values.inject([]) do |mem, gem| Dir[gem.full_gem_path + "/#{filter_str}generators/**/*_generator.rb"].each do |generator| mem << generator end mem end.reverse end def filter_str @filters = filters.first.is_a?(Array) ? filters.first : filters return "" if filters.blank? filter_str = filters.map {|filter| "#{filter}_"}.join(",") filter_str += "," "{#{filter_str}}" end end end
Java
--- layout: post_n title: 《Rust权威指南》笔记 date: 2021-11-20 categories: - Reading description: 陆陆续续将《Rust权威指南》看完了,文中的例子全部按自己的理解重新实现了一遍。回望来途,可谓困难坎坷,步履艰辛;即是如此,也收获满满。Rust语言的学习给我耳目一新的感觉,上一次对学习语言有这种感觉还是在Haskell的学习中。他完全颠覆我理解的语言设计,在除了垃圾回收语言和内存自主控制语言,竟然还有如此方式来保证内存安全。震撼的同时,也感觉整体学习非常吃力,学习曲线异常陡峭。虽然把整本书都看完了,但还有非常多的细节似懂非懂,也无法完全不参照例子自行写出相对复杂的程序;一些语言中很容易实现的代码在Rust中也无法自行实现出来。所以目前只是第一阶段,即入门,以此为记。后面需要通过开源项目学习练手,通过了解常用的写法去深刻体验Rust的设计精髓。 image: /assets/images/rust_programer_cover.jpeg image-sm: /assets/images/rust_programer_cover.jpeg --- * ignore but need {:toc} ## 前言 陆陆续续将《Rust权威指南》(即英文版的[《The Rust Programming Language》](https://doc.rust-lang.org/book/))看完了,文中的例子全部按自己的理解重新实现了一遍(代码在[github](https://github.com/xiaochai/batman/tree/master/RustProject)上)。回望来途,可谓困难坎坷,步履艰辛;即是如此,也收获满满。 Rust语言的学习给我耳目一新的感觉,上一次对学习语言有这种感觉还是在Haskell的学习中。他完全颠覆我理解的语言设计,在除了垃圾回收语言和内存自主控制语言,竟然还有如此方式来保证内存安全。震撼的同时,也感觉整体学习非常吃力,学习曲线异常陡峭。虽然把整本书都看完了,但还有非常多的细节似懂非懂,也无法完全不参照例子自行写出相对复杂的程序;一些语言中很容易实现的代码在Rust中也无法自行实现出来。所以目前只是第一阶段,即入门,以此为记。后面需要通过开源项目学习练手,通过了解常用的写法去深刻体验Rust的设计精髓。 ## 学习与参考资料汇总 | 标题 | 说明|链接 | | ------------- |:----||:-------------| |The Rust Reference| 官方文档,也是本文的英文版 |[https://doc.rust-lang.org/reference/introduction.html](https://doc.rust-lang.org/reference/introduction.html) | |Rust Primer |gitlab上的学习笔记|[https://hardocs.com/d/rustprimer/](https://hardocs.com/d/rustprimer/) | |Rust Magazine |Rust月刊|[https://rustmagazine.github.io/rust_magazine_2021/chapter_1/rustc_part1.html](https://rustmagazine.github.io/rust_magazine_2021/chapter_1/rustc_part1.html) | |Rust数据内存布局| 内存布局|[https://juejin.cn/post/6987960007245430797](https://juejin.cn/post/6987960007245430797) | |The Rustonomicon |官方文档,说明一些语言的灰暗角落|[https://doc.rust-lang.org/nomicon/intro.html#the-rustonomicon](https://doc.rust-lang.org/nomicon/intro.html#the-rustonomicon) | |The Unstable Book|官方文档,不稳定特性说明 |[https://doc.rust-lang.org/beta/unstable-book/the-unstable-book.html](https://doc.rust-lang.org/beta/unstable-book/the-unstable-book.html) | |Std Lib Document|标准库文档|[https://doc.rust-lang.org/std/](https://doc.rust-lang.org/std/)| ## 安装与示例 如[官网](https://www.rust-lang.org/tools/install)所说,运行以下命令即可安装: ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` Rust相关的工具会被安装到```/Users/bytedance/.cargo/bin```这个目录下,如果没有把这个目录加到PATH下,添加即可使用。 ### 创建Hello World程序 位于hello_world/main.rs ```rust fn main(){ println!("Hello world"); } ``` 编译运行: ``` ➜ hello_world git:(master) ✗ rustc main.rs ➜ hello_world git:(master) ✗ ./main Hello world ``` 我们注意到以上程序的几点,细节在后续章节中说明:缩进以4个空格为准;println!为宏,普通函数调用不需要```!```;你会发现去掉println最后的分号也能运行。 ### 使用cargo Cargo是Rust工具链中内置的构建系统及包管理器,常见的命令汇总如下: | 命令 | 说明 | | ------------- |:-------------| | cargo new \<path\> | 创建一个新的cargo项目,会生成Cargo.toml和src/main.rs| | cargo new \-\-lib \<path\> | 创建一个新的库项目,会生成Cargo.toml和src/lib.rs| | cargo build |编译本项目,生成的可执行文件位于./target/debug/下;<br/>如果添加\-\-release,则会生成到./target/release/下;<br/>\-\-release参数将花费更多的时间来编译以优化代码,一般用于发布生产环境时使用 | | cargo run | 编译并运行本项目,也支持\-\-release参数,常用于运行压测; <br/>-p 用于工作空间下有多个二进制包时指定运行哪个包 | | cargo run \-\-bin \<target\> | 编译并运行指定的bin文件,一般位于src/bin目录下,target不带.rs后缀 | | cargo check | 仅检查是否通过编译,由于不生成二进制文件,速度快于cargo build | | cargo doc | 在当前项目的target/doc目录生成使用到的库的文档,可以使用\-\-open选项直接打开浏览器 | | cargo update | 忽略Cargo.lock文件中的版本信息,并更新为语义化版本所表示的最新版本,用于升级依赖包 | | cargo test | 运行测试用例,默认情况下是多个测试case并行运行;<br/> cargo test接收两种参数,第一种传递给cargo test使用,第二种是传递给编译出来的测试二进制使用的;<br/>这两种参数中间使用\-\-分开;<br/>例如 cargo test -q tests::it_works -- --test-threads=1;<br/> 这一命令,会以安静模式(-q)运行tests::it_works下的测试,并且只使用一个线程串行运行(--test-threads=1) | |cargo publish | 发布项目到crate.io上,添加\-\-allow-dirty可以跳过本地git未提交的错误| |cargo yank \-\-vers 0.0.1| 撤回某个版本,添加\-\-undo取消撤回操作| Cargo.toml说明: | 段名 | 说明 | | ------------- |:-------------| | package | 本包(crate)的信息说明| | dependencies |依赖的外部包,版本是语义化的版本,用于update时判断最新的可用版本 | | profile.dev | 在非\-\-release模式下的编译参数,例如opt-level优化等级配置等,覆盖默认值,要省略 | |profile.release| 在\-\-release模式下的编译参数,覆盖默认值,可省略 crate是Rust中最小的编译单元,package是单个或多个crate的集合;crate和package都可以被叫作包,因为单个crate也是一个package,但package通常倾向于多个crate的组合。 Rust中的包(crate)代表了一系列源代码文件的集合。用于生成可执行程序的称为二进制包(binary crate),而用于复用功能的称为库包(library crate,代码包),例如rand库等。 创建项目:(hello_cargo项目) ``` ➜ RustProject git:(master) ✗ cargo new hello_cargo Created binary (application) `hello_cargo` package ➜ RustProject git:(master) ✗ cd hello_cargo ➜ hello_cargo git:(master) ✗ tree . . ├── Cargo.toml └── src └── main.rs 1 directory, 2 files ``` Cargo.toml ```ini [package] name = "hello_cargo" version = "0.1.0" edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] rand = "0.8.0" # 手动添加的,默认没有这一行,用于说明 ``` src/main.rs ``` fn main() { println!("Hello, world!"); } ``` 运行: ``` ➜ hello_cargo git:(master) ✗ cargo build Compiling hello_cargo v0.1.0 (/Users/bytedance/xiaochai/batman/RustProject/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 1.22s ➜ hello_cargo git:(master) ✗ ./target/debug/hello_cargo Hello, world! ➜ hello_cargo git:(master) ✗ cargo run Compiling hello_cargo v0.1.0 (/Users/bytedance/xiaochai/batman/RustProject/hello_cargo) Finished dev [unoptimized + debuginfo] target(s) in 0.27s Running `target/debug/hello_cargo` Hello, world ``` ## 猜数字例子 位于guessing_game中 ```rust // 标准库中定义的比较结果的枚举 use std::cmp::Ordering; // 使用use语句进行包导入;rust默认会预导入(prelude)一部分常用的类型,而std::io不在此范围,需要使用use语句 use std::io; // 首先使用了rand包,需要在Cargo.toml中添加rand = "0.8.0" // 在run或者build的时候,会根据crates.io上的最新版本、依赖关系下载所需要的包 // rand::Rng为trait(后面解析),gen_range定义于此Trait中 // 如果不导入,调用gen_range将报错,因为ThreadRng的对应实现定义于Rng trait中 use rand::Rng; fn main() { // rand::thread_rng()将返回位于本地线程空间的随机数生成器ThreadRng,实现了rand::Rng这一trait // gen_range的参数签名在0.7.0的包和0.8.x的包上不一样,在旧版中支持两个参数,而新版本中只支持一个参数 // 1..101的用法后面介绍,这一行表示生成[1,101)的随机数 let secret_num = rand::thread_rng().gen_range(1..101); println!("secret number is {}", secret_num); // 死循环 loop { // let关键字用于创建变量 // 默认变量都是不可变的,使用mut关键字修饰可以使变量可变 // String是标准库中的字符串类型,内部我问个他UTF-8编码并可动态扩展 // new是String的一个关联函数(静态方法),用于创建一个空的字段串 let mut guess = String::new(); println!("Guess the number!\nPlease input your guess:"); // std::io::stdin()会返回标准输入的句柄 // 参数&mut guess表示read_line接收一个可变字符串的引用(后面介绍),将读取到的值存入其中 // read_line返回io::Result枚举类型,有Ok和Err两个变体(枚举类型的值列表称为变体) // 返回Ok时表示正常并通过expect提取附带的值(字节数);返回Err时expect将中断程序,并将参数显示出来 // 不带expect时也能通过编译,但会收到Result没有被处理的警告(warning: unused `Result` that must be used) io::stdin().read_line(&mut guess).expect("Failed to read line"); // Rust中允许使用同名新变量来隐藏(shadow)旧值 // guess:u32是明确guess的类型,以此来使得让编译器推到出parse要返回包含u32的值 // parse的返回值是一个Result枚举,有Ok和Err两个变体(枚举值),用match来判断两种情况 let guess: u32 = match guess.trim().parse() { Ok(num) => num, Err(e) => { println!("Please type a number!"); // continue回到loop开头继续 continue; } }; // {}为println!的占位符,第1个花括号表示格式化字符串后的第一个参数的值,以此类推 println!("You guessed:{}", guess); // 模式匹配,由match表达式和多个分支组成,Rust可以保证使用match时不会漏掉任何一种情况 // Rust会将secret_num也推导成u32与guess比较 match guess.cmp(&secret_num) { Ordering::Less => println!("Too small!"), Ordering::Equal => { println!("You WIN!"); // 退出循环 break; } Ordering::Greater => { println!("Too big!") } } } } ``` ## 通用编程概念 本章节例子位于example/src/bin/main.rs中。 ### 变量与可变性 变量默认是不可变的,这意味着一但赋值,再也无法改变: ```rust let x: i32; x = 5; let y: i32 = 10; // 以下行报错:Cannot assign twice to immutable variable [E0384] // y=9 ``` 可以变量名前添加mut使得此变量可变: ```rust let mut x = 10; x = 100; x = 1000; ``` 常量使用const修饰,名称全部大写,并用下划线分隔;常量可以是全局的(例如main函数之外),也可以是局部的;常量必须显示指定类型: ```rust const MAX_SCORE: i32 = 199; fn main() { // some other code const MY_SCORE: i32 = 200; const MAX_SCORE: i32 = 299; // 200,299 println!("{},{} ", MY_SCORE, MAX_SCORE); } ``` 隐藏变量是指使用相同名称来定义变量,重新定义后,之前的变量值和类型被隐藏了: ```rust let space = " "; let space = space.len(); ``` ### 数据类型 Rust是一门静态语言,所以变量在编译时就确定了其数据类型。Rust的数据类型分为标量类型(scalar)和复合类型(compound)。 一般情况下,在编译器可以推断出类型的场景中,可以省略类型标注,但在无法推断的情况下,就必须显示的声明类型了。 ```rust // 以下报错:type annotations needed // let k = ("32").parse().expect("not ok"); let k: i32 = ("32").parse().expect("not ok"); ``` 标量类型是单个值类型的统称,有4种标量类型:整数、浮点数、布尔值及字符。 整数类型:i8、u8、i16、u16、i32、u32、isize、usize;以上除了isize和usize所占的字节数是根据平台(32位/64位)来确定的,其它的的类型都有明确的大小。 整数类型的默认推导是i32: ```rust // 整数类型字面量 // 10进制,可以用下划分分隔 let x: u32 = 98_000; let x: u32 = 0xff; // 十六进制 let x: u32 = 0o77; // 八进制 let x: u32 = 0b1111_0000; // 二进制 let x = b'A'; // u8 ``` 对于整数溢出,编译期会尽可能的检查溢出可能,如果检测到,则直接编译报错。 如果使用debug编译,则在运行时发生溢出时,会触发panic;如果是release,则会执行数值环绕,从最小的重新开始记录。 ```rust // 整数溢出 let x: u8 = 252; let y: u8 = ("32").parse().expect("not ok"); // 以下行在debug模式下,会在运行时报错 // thread 'main' panicked at 'attempt to add with overflow', src/main.rs:41:26 // note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace // 在release模式下,则不会报错,输出28 println!("{},see!", x + y); ``` 浮点数类型:f32,f64;默认推导为f64。 数值运算:加(+)、减(-)、乘(x)、除(/)、取余(%);只有相同类型间才能进行操作: ```rust // 类型不一样,无法操作 // let x:u8 = 10; // let y:u32 = 100; // let z = y+x; ``` 布尔值,只拥有true和false,占据一个字节大小,常用于if的判断: ```rust let x:bool = false; ``` 字符类型,单引号指定,是Unicode标量值,占4个字符: ```rust // 字符类型 let x = 'c'; let y = '李'; let z:char = '李'; ``` 将多个不同类型的值合成一个类型,称为复合类型;Rust有两种内置复合类型:元组(tunple)和数组(array); 元组类型,在括号内放置一系列以逗号分隔的值,即可组成元组: ```rust // 元组 // 也可以省略类型,让编译器推断 let x:(i64,f64,char) = (2,3.4, 'c'); // 使用模式匹配来解构元组 let (a,b,c) = x; // 通过点来访问元组 println!("{},{},{}", x.0, x.1, x.2); ``` 数组类型: 每一个元素必须类型一致,数组大小不可改变,在栈上分配: ```rust // 数组 // 声明一个长度为5,元素为int32类型的数组;类型[i32;5]也可以省略,由编译器推断 let x: [i32; 5] = [1, 2, 3, 4, 5]; // 定义了一个由7个1组成的数组,即[1,1,1,1,1,1,1] let y = [1; 7]; // 通过下标来访问,从0开始;以下输出3,1;下标的类型是usize的 println!("{},{}", x[2], y[6]); // 越界时将发生严重错误 // 编译时报错:index out of bounds: the length is 5 but the index is 10 // 如果下标是运行时才确定的值,则这块的报错将在运行时报错 // let k:usize = "10".parse().expect("not a number"); // println!("{}", x[k]); ``` ### 函数 函数的命名由下划线分隔的多个小写单词组成: ```rust fn my_sum(x: i32, y: i32) -> i32 { // 可以直接是return,也可以直接写表达式x+y,函数中将最后一个表达式的值做为返回值 return x + y; } ``` 语句和表达式: 语句指执行操作,但不返回值的指令;表达式指进行计算并且产生结果的指令。 表达式是语句的一部分;字面量、函数调用、宏调用、新作用域的花括号都是表达式。 ```rust // 语句,没有返回值 let x = 6; // 所以不能将语句赋值给变量 // let y = (let x = 7); // 以下也不行 // let a = b = 6; // 花括号的代码块也是表达式,以下表达式的值为11 let x = { let y = 10; // 注意这一行不能有分号,添加了分号后,这个代码块的值就是空元组了() y+1 }; ``` ### 控制流 if的条件表达式必须是bool值;if表达式可以用于赋值: ```rust // if的用法,多分支判断,条件表达式的值只能是bool类型 let num = 100; if num % 4 == 0 { println!("number is divisible by 4") } else if num % 3 == 0 { println!("number is divisible by 3") } else { println!("number is not divisible by 3,4") } // if为表达式,所以可以使用if来赋值 // 此处要注意各个分支返回的数据类型要一样,否则编译期直接报错 let condition = true; let x = if condition { 10 }else { 20 }; ``` loop 循环: ```rust // loop表达式的值,可以从break返回 let mut i = 1; let count = loop{ i+=1; if i > 10 { break i } // 两个break的值类型要一样,所以以下这一行无法通过编译 // break 'a' }; ``` while表达式的值一直都是空值: ```rust // while表达式的值一直是空值,如果使用break,后面不能跟返回值 let mut i = 1; let count:() = while i > 10 { i += 1; }; ``` for: ```rust // y是一个Range<i32>类型,本身是一个迭代器;值为1,2(不包括3) // rev是从后往前遍历,所以这块打印的是2,1, let y = 1..3; for e in y.rev() { print!("{},", e) } ``` 结尾习题: ```rust // 摄氏温度与华氏温度的相互转换 // println!("celsius_2_fahrenheit(1):expect{}, actual:{}", 33.8, celsius_2_fahrenheit(1.0)); fn celsius_2_fahrenheit(celsius: f64) -> f64 { celsius * 1.8 + 32.0 } // 生成一个n阶的斐波那契数列 // println!("fibonacci(10):expect{}, actual:{}", 34, fibonacci(10)); fn fibonacci(n: i64) -> i64 { if n == 1 { 0 } else if n == 2 { 1 } else { fibonacci(n - 1) + fibonacci(n - 2) } } // 打印圣诞颂歌The Twelve Days of Christmas的歌词,并利用循环处理其中重复的内容。 // 太长了,改成The Six Days of Christmas // the_six_days_of_christmas(); fn the_six_days_of_christmas() { let num_map = ["first", "second", "third", "forth", "fifth", "sixth"]; let gifts = ["a partridge in a pear tree", "two turtle doves", "three French hens", "four calling birds", "five golden rings", "six geese a-laying", ]; for i in 0..6 { print!("On the {} day of Christmas, my true love sent to me:", num_map[i]); let mut j = i; while j > 0 { print!("{},", gifts[j]); j -= 1; } // 最后一个礼物不需要逗号 println!("{}.", gifts[0]); } } ``` ## 所有权 不同语言管理内存的方式: * Java:通过垃圾回收来管理内存; * C/C++:开发者手动地分配和释放; * Rust:通过应用所有权系统规则,在编译期间检查,来保证内容安全。 所有权系统使得Rust在没有垃圾回收的情况下,保证内存安全。其所有权规则包含以下三个规则: 1. <strong>Rust中每一个值都有一个变量作为他的所有者;</strong> 2. <strong>在同一个时间内,值有且仅有一个所有者;</strong> 3. <strong>当所有者离开他的作用域时,他所持有的值将被释放。</strong> 使用域的概念与其它语言类似,不再赘诉。 以下例子位于example/src/bin/main.rs中。 ### String类型介绍 字符串的字面量是编译进二进制文件中,但运行时可动态变化的字符串类型则需要存储到堆上。 ```rust // 字符串类型在堆上分配 // String::from方法,使用字符串字面量来创建String类型,这里s必须是可变的 let mut s = String::from("Hello"); s.push_str(", world"); println!("{}", s) ``` 下面以例子的方式来说明所有权的动作规则: ```rust let s1 = String::from("Hello"); let s2 = s1; println!("{}", s1) ``` String类型由两大部分组成,存储于栈上的元信息(ptr, len, cap),即指向堆上的指针,字符串长度,分配容量;而实际的内容保存在ptr所指的堆上,如下图: ![字符串类型内存部局](/assets/images/string_mem_1.jpeg) 将s1赋值给s2时,由于Rust不会对堆上值也进行拷贝,只会将栈上的元数据进行拷贝,所以目前的状态有可能是s1,s2所指向的String元数据中的指针都指向了同一片堆区域。 ![字符串类型内存部局](/assets/images/string_mem_2.jpeg) 在s1和s2变量离开作用域后,Rust会自动执行对应类型上的drop方法,释放对应的内存,问题就产生了,这将产生二次释放问题。 为了解决这个问题,Rust在种情况下,会将s1的变得无效,这就是之前例子中第三行无法通过编译的原因。 这种只有拷贝了栈上的数据而没有拷贝堆上的数据的浅拷贝,在Rust中称为移动(move),上面例子中,s1被移动到s2了 Rust永远不会自动地创建数据的深度拷贝。因此在Rust中,任何自动的赋值操作都可以被视为高效的。 如果确实需要使用深拷贝,可以使用clone函数,如下例子可以通过编译 ```rust // 对s1进行深拷贝,即将堆上的内容也进行了拷贝 let s1 = String::from("Hello"); let s2 = s1.clone(); println!("{}, {}", s1, s2); ``` 对于完全存储在栈上的数据,赋值本身已经将全部数据都拷贝,所以不用调用clone方法。**在Rust中,实现了Copy trait的类型,都可以在将变量赋值给其它变量时原变量保持可用**。 所有的标量类型都实现了Copy trait;元组或者数组中包含的元素是Copy的,则元组或者数组就是Copy的: ```rust // 如果这个元组加了String类型,如下,则不能通过编译 let x = (1,2,3.0); // let x = (1, 2, 3.0, String::from("Hello")); let y = x; println!("{}", x.1); let x = [1, 2, 3]; let y = x; println!("{}", x[1]); ``` **注意Copy和Drop是互斥的,如果一个类型本身或者成员变量实现了Copy,则这个类型就无法实现Drop**。 ### 函数与所有权 函数参数与赋值是一样的,返回值也是一样的: ```rust fn take_owner(s: String) {} let s = String::from("hello"); take_owner(s); // 将发生编译错误,因为s的所有权移进了take_owner中 // println!("{}", s); fn take_owner_and_return(s: String)->String{ // 函数又将s的所有权转移到返回值,所以s不会被drop掉 return s; } let s1 = String::from("hellow"); let s2 = s1;// 到这里,s1已经失效 let s3 = take_owner_and_return(s2); // 到这里s2已经失效 // 这里只有s3可用,其它的s1,s2失效 ``` ### 引用与借用 ```rust // 引用传递时,并不取得所有权,但可以使用值 fn get_len(s: &String) -> usize { // s是一个不可变引用,所以无法对s的值进行改变 // 以下无法通过编译 // s.push_str(", world"); return s.len(); } let s1 = String::from("hello"); // s2为可变引用,默认的引用不可变 let mut s2: &String = &s1; let mut s3 = String::from("hello"); // 注意s2为可变引用的意思是可以改变s2引用到哪个值,而不能改变s2引用的值 // 以下无法通过编译, 报错: cannot borrow `*s2` as mutable, as it is behind a `&` reference // s2.push_str(", world"); // 因为两行可以运行,因为s2是可变引用,而且s3是可变String s2 = &mut s3; // 虽然s2引用了可变的s3,但由于s2的类型是&String不是&mut String,所以到下这一行还是无法通过编译 // s2.push_str(", world"); // 获取s1的长度,而不取得s1的所有权 let size = get_len(&s1); { let s4 = String::from("you"); // 由于s4的生命周期比s2短,所以s2无法引用s4,这避免了悬垂指针的出现 // s2 = &s4; } // 在这里s1还是能用 println!("{},{},{},{}", s1, s2, size, s1); ``` 通过引用,可以在不取得所有权的情况下,使用对应值。当引用离开作用域时,由于不持有所有权,所以也不会释放所指向的值。 引用分成可变引用和不可变引用,但这块的可变是指可以改变指向哪个值,而无法改变值本身,注意以下两组的区别: ```rust let mut s:String = String::from("hello"); let s1:&mut String = &mut s; s1.push_str(",world"); let mut s:String = String::from("hello"); let mut s2:&String = &mut s; // 以下无法通过编译,因为s2是&String不可变类型 s2.push_str(", world"); ``` 另外,只能申明一个可变引用,如果某个变量已经被可变引用了,也不允许再被不可变引用。这可以很好的避免数据竞争: ```rust let mut s = String::from("hello"); let s1 = &mut s; // cannot borrow `s` as mutable more than once at a time // let s2 = &mut s; // cannot borrow `s` as immutable because it is also borrowed as mutable // let s3 = &s; println!("{},{}, {}", s1, s2, s3); ``` 总结出来以下规则: 1. **在任何一段给定的时间里,要么只能拥有一个可变引用,要么只能拥有任意数量的不可变引用**。 2. **引用总是有效的**。 ### 切片 ```rust // 字符串切片,类似与go,获取[begin,end)之间的内容,注意end最大是字符串的长度,超过后会报错 let s = String::from("0123456789"); // 以下两个hello和world等价 let hello = &s[0..5]; let hello: &str = &s[..5]; let world = &s[5..10]; let world = &s[5..]; // 01234,56789 println!("{},{}", hello, world); // 获取第一个单词,返回字符串切片 // 这里的函数参数也可以使用&str,可以更通用 fn first_world(s: &String) -> &str { // s.as_bytes()将字符串转成字节数组&[u8] // iter返回迭代器,enumerate将每一个元素按元组的形式返回 for (i, &item) in s.as_bytes().iter().enumerate() { // 判断是空格,直接返回切片 if item == b' ' { return &s[0..i]; } } &s[..] // 使用&s也可以 } // 输出hello println!("{}", first_world(&String::from("hello world"))); let mut s = String::from("0123456789"); let t = first_world(&s); // 以下无法通过编译,因为s已经是不可变引用了,s.clear又使用了可变引用 // cannot borrow `s` as mutable because it is also borrowed as immutable // s.clear(); println!("{},{}", s, t); ``` 字符串字面量就是字符串切片,切片包括指向值的指针和长度。 其它类型的切片: ```rust // 其它切片 let ia = [1, 2, 3, 4, 5, 6]; let sia: &[i32] = &ia[1..3]; ``` ## 结构体 结构体的一些规则:(以下例子位于example/src/bin/main.rs中) 1. 一个结构体的实例是可变的,则这个结构体的所有成员变量都是可变的; 2. 在创建结构体实例时,如果变量名与字段名同名时,可以省略字段名,直接写变量名; 3. 可以使用```..old```这种语法来快速从old创建一个只有部分值改变的新变量; 4. 支持不带字段名的元组结构体; 5. 支持空结构体; 6. 如果结构体的成员是引用时,需要带上生命周期的标识。 ```rust // 结构体定义 struct User { username: String, email: String, sign_in_count: u64, active: bool, } // 创建实例 let mut user1 = User { username: String::from("xiaochai"), email: "soso2501@mgail.comxxx".to_string(), sign_in_count: 1, active: true, }; println!("{}", user1.email); // soso2501@mgail.comxxx // 访问和修改,注意一旦实例可变,则实例的所有成员都可变 user1.email = String::from("soso2501@mgail.com"); println!("{}", user1.email); // soso2501@mgail.com fn build_user(email: String, username: String) -> User { User { username, // 由于变量名了字段同名,所以可以省略掉字段名 email, sign_in_count: 1, active: true, } } let mut user1 = build_user("soso2501@mgail.com".to_string(), "xiaochai".to_string()); let mut user2 = User { username: "xiaochai2".to_string(), // 可以使用以下语法从user1复制剩下的字段 ..user1 }; user1.email = "sosoxm@163.com".to_string(); // soso2501@mgail.com,sosoxm@163.com println!("{},{}", user2.email, user1.email); // 元组结构体 // 当成员变量没有名字时,结构体与元组类似,称为元组结构体 struct Point(u32, u32, u32); let origin = Point(0, 0, 0); // 可以使用数字下标来访问 println!("{},{},{}", origin.0, origin.1, origin.2); // 也可以通过模式匹配来结构 let Point(x, y, z) = origin; println!("{},{},{}", x, y, z); // 空结构体,一般用于trait struct Empty{} // 如果结构体的成员是引用时,需要带上生命周期的标识 struct User2<'a> { username: &'a str, } ``` ### 实例 结构体的应用举例: 1. 通过结构体来更清晰表达字段含义; 2. 使用注解来快速实现trait,使得可以在println!中使用```{:?}```和`{:#?}`来输出自定义结构体; 3. 使用impl关键字为结构体实现方法; 4. 方法第一个参数如果是self,可以是获得所有权(self),也可以是借用(&self),还可以是可变的(&mut self或者是mut self); 5. 同一个结构体,可以写多个impl,但不能多次定义同一个方法,即使参数不一样也不行; 6. 如果方法的第一个参数不为self,则称为关联函数,类似与静态方法。 ```rust // 使用结构的例子,说明trait的使用 #[derive(Debug)] // 添加注解来派生Debug trait struct Rectangle { width: u32, height: u32, } fn area(rect: &Rectangle) -> u32 { rect.width * rect.height } let rect1 = Rectangle { width: 10, height: 20 }; // {:?}需要结构体实现Debug这一trait,也可以使用{:#?}来分行打印 // the area of rectangle Rectangle { width: 10, height: 20 } is 200 println!("the area of rectangle {:?} is {}", rect1, area(&rect1)) // 为结构体定义方法 impl Rectangle { // 方法的第一个参数永远是self fn area(&self) -> u32 { self.height * self.width } } println!("the area of rectangle {:?} is {}", rect1, rect1.area()); impl Rectangle { // 以下无法通过编译,因为area重复定义了 // fn area(&self, i: i32) -> u32 { // self.height * self.width // } fn can_hold(&self, rect2: &Rectangle) -> bool { self.width > rect2.width && self.height > rect2.height } // 关联函数 fn new(width: u32, height: u32) -> Rectangle { Rectangle { width, height, } } } println!("the area of rectangle {:?} is {}", Rectangle::new(3, 2), Rectangle::new(2, 3).area()); ``` ## 枚举 1. 枚举使用enum关键字定义,每一个枚举值称之为变体(variant); 2. 每一个变体可以有不同的数据类型和数量的数据关联; 3. 枚举相校与结构体不同的地方在于,如果对变体的不数数据定义各自的结构,则他们属于不同类型,而使用枚举则可以使用一种类型来描述不同的数据结构; 4. 同样可以为枚举实现方法; 5. 使用match模式匹配处理每一种变体,必须处理所有的变体,否则编译不通过;当然可以使用通配符来匹配任意值/类型; 6. match还可以绑定匹配对应的部分值。 以下例子位于example/src/bin/main.rs中: ```rust enum IPAddr { // 变体中可以保存数值 IPV4(u32, u32, u32, u32), IPV6(String), } // 可以为枚举定义函数 impl IPAddr { fn print(&self) { // 使用match来处理每一种变体,注意需要处理所有变体,否则编译保险错 match self { // 模式匹配可以直接解构变体内的数值 IPAddr::IPV4(u1, u2, u3, u4) => println!("{}.{}.{}.{}", u1, u2, u3, u4), IPAddr::IPV6(s) => println!("{}", s), } } } let ipv4 = IPAddr::IPV4(1, 2, 3, 4); let ipv6 = IPAddr::IPV6("::1".to_string()); ipv4.print(); ipv6.print(); ``` 预导入库中的非常常用的Option类型,用在需要表示空值的场景,其定义为(省略了注解): ```rust pub enum Option<T> { None, Some(T), } ``` 这里的\<T\>为泛型参数,None表示空值,Some表示有值,并持有值: ```rust // 标准库中的Option类型 // 为一个Option值加1 fn plus_one(c: Option<i32>) -> Option<i32> { match c { None => None, Some(i) => Some(i + 1) } } let five = plus_one(Some(4)); let none = plus_one(None); match five { None => println!("none"), Some(i) => println!("val is {}", i) }; match none { None => println!("none"), Some(i) => println!("val is {}", i) }; // 必须匹配每一个可能的值 let c = 2; match c { 1 => println!("is 1"), 2 => println!("is 2"), // 如果没有以下这一行,则编译报错 // non-exhaustive patterns: `i32::MIN..=0_i32` and `3_i32..=i32::MAX` not covered _ => println!("other") } ``` 在只关心某一种匹配而忽略其它匹配的时候,可以使用if let来简化代码: ```rust // 使用if let来简化处理 let five: Option<i32> = Some(5); if let Some(i) = five { println!("has value {}", i) } ``` ## 包管理 * 包(package:一个用于构建、测试并分享单元包的Cargo功能; * 单元包(crate):一个用于生成库或可执行文件的树形模块结构; * 模块(module)及use关键字:它们被用于控制文件结构、作用域及路径的私有性; * 路径(path):一种用于命名条目的方法,这些条目包括结构体、函数和模块等。 以下为关于包的一些定义和规则: * 用于生成可执行程序的的单元包称为二进制单元包; * 用于生成库的单元包称为库单元包; * 一个包至少要有一个单元包,并且最多只能包含一个库单元包,但可以包含多个二进制单元包; * Rust编译时所使用的入口文件被称为根节点,例如src/main.rs; * src/main.rs和src/lib.rs做为默认的二进制单元包和库单元包的根节点,无需在cargo.toml中指定; * mod关键字可以定义模块,模块内可以嵌套定义子模块; * 可以使用两模式定位到模块内的函数/枚举等:1. 使用单元包名或字面量crate从根节点开始的绝对路径;2. 使用单元包名或字面量crate从根节点开始的绝对路径; * Rust中所有的条目包括函数、方法、结构体、枚举、模块、常量默认都是私有的; * 对于模块来说,父级模块无法使用其子模块中的私有的条目,而子模块可以使用所有祖先模块中的条目; * 公开的结构体其成员默认还是私有的,公开枚举时,其变体自动变成公开。 以下例子位于restaurant项目中: ```rust // 定义模块,可以嵌套子模块 mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} pub fn seat_at_table() {} } pub mod serving { fn take_order() {} fn serve_order() {} fn take_payment() {} mod back_of_house { fn fix_incorrect_order() { // 使用super关键字引用父模块的,由于子模块可以使用父模块的所有条目,包括私有 super::serve_order(); cook_order(); } fn cook_order() {} pub struct Breakfast { pub toast: String, // 虽然结构体是公有的,但字段默认还是私有的,需要用pub指定 season_fruit: String, } impl Breakfast { pub fn summer(toast: &str) -> Breakfast { Breakfast { toast: String::from(toast), season_fruit: String::from("peaches"), } } } pub enum Appetizer { // 以下两个变体是公开的 Soup, Salad, } } } } pub fn eat_at_restaurant() { // 以下两种调用是等价的 // 使用绝对路径,从crate关键字(即根节点)开始 crate::front_of_house::hosting::add_to_waitlist(); // 使用相对路径,从当前模块开始 front_of_house::hosting::add_to_waitlist(); } ``` * 使用use关键字可以简化引用路径; * 使用as关键字使用新的名称,可以解决重名的问题; * 使用pub use重导出名称,使用pub use的名称不仅在本作用域内可以使用,外部也可以通过引入本作用域来调用到pub use导出的包。可以用于重新组织包结构; * 使用外部包与使用std包类似,只是需要在cargo.toml文件中的dependencies小节中添加包名以及对应的版本; * 如果要导入一个树型包中的几个包,可以使用嵌套的语法来减少use语句的使用。 ```rust // 使用use关键字可以简化路径 // 以下两行等价,self关键字可能在后续版本中去掉 use front_of_house::hosting; // use self::front_of_house::hosting; pub fn eat_at_restaurant2() { hosting::add_to_waitlist(); } // 为防止重名,使用as来重命名 use std::fmt::Result; use std::io::Result as IOResult; // 等价于导入std::cmp::Ordering和std::io这两个包 use std::{cmp::Ordering, fs}; // 等价于导入std::io和std::io::Write这两个包 use std::io::{self, Write}; // 导入std::collections下的所有包,一般不推荐,容易造成命名冲突 use std::collections::*; pub fn test(){ Result::Ok(()); IOResult::Ok("FD"); } ``` 可以将模块的层级关系使用目录关系来组织起来,例如原例子中在libs下面创建如下关系的包: ```rust mod front_of_house { pub mod hosting { pub fn add_to_waitlist() {} pub fn seat_at_table() {} } ``` 可以将front_of_house移到front_of_house.rs中,则以下两个文件变成: ```rust // 以下是位于lib.rs mod front_of_house; ``` ```rust // 以下位于front_of_house.rs中 pub mod hosting { pub fn add_to_waitlist() {} pub fn seat_at_table() {} } ``` 也可以将front_of_house.rs再拆分: ```rust // libs.rs mod front_of_house; ``` ```rust // front_of_house.rs mod hosting; ``` ```rust // front_of_house/hosting.rs pub fn add_to_waitlist() {} pub fn seat_at_table() {} ``` ## 集合 以下例子位于example/src/bin/collection.rs中: ### 动态数组 * 动态数组Vec是范型,在无法推断类型时,必须显示指定类型; * 使用vec!宏可以快速构建有初始值的数组; * 数组中的元素会在动态数组销毁时跟着销毁; * 数组元素的引用会对整个数组造成影响,即不可以在有只读引用的情况下push元素; * 结合枚举,可以间接地在Vec中存储多种不同的类型。 ```rust // 创建一个动态数组 let v: Vec<i32> = Vec::new(); // 使用vec!宏来快速创建一个带有初始值的数组 let v = vec![1, 2, 3]; // 必须是mut的动态数组才能push进数据 let mut v: Vec<i32> = Vec::new(); // 往动态数组里添加数据 v.push(5); v.push(6); // 获取数组元素的引用,如果数组越界将发生panic let e1: &i32 = &v[0]; // 返回Option<&T>类型,如果不越界将返回Option let e2: Option<&i32> = v.get(0); // 注意数组元素的引用会对整个数组造成影响,这就导致了在只读引用存在的情况下无法往数组中push元素 // 以下行无法通过编译:cannot borrow `v` as mutable because it is also borrowed as immutable // v.push(7); println!("{}", e1); // 使用for来遍历所有元素,这里的i为&i32 for i in &v { // 5 6 println!("{}", i) } // 这里的i值为&mut i32 for i in &mut v { // 将i解引用,指向对应的值,并修改 *i *= 2; } for i in &v { // 10 12 println!("{}", i) } ``` ### 字符串 * 字符串本身是基于字节的集合,通过功能性的方法将字节解析为文本; * Rust语言核心部分只有一种字符串类型,即字符串切片str,通常以引用形式出现(&str),它是指向存储在别处的一些UTF8编码字符串的引用,例如字符串字面量; * String类型定义在标准库中,不是语言核心的一部分,提供UTF8编码; * 标准库还提供了OsString,OsStr,CString和CStr,一般以Str结尾的是借用版本,String结尾是所有权版本。这些类型提供了不同的编码或者不同内存布局的字符串类型; * String类型实际使用Vec\<u8\>进行封装; * 为了避免出现多字节情景下你拿到半个字符,所以Rust不允许使用下标访问获取字符串的字符。而是通过特定的功能函数指定对字节,字符,字形簇进行处理; * 但是Rust却允许字符串切片的使用,但使用时要格外小心,因为如果截取的范围不是有效的字符串,将发生panic。 ```rust // 字符串字面量是&str类型 let c: &str = "ab"; println!("{}", c); // 创建一个新空字符串 let s: String = String::new(); // 从字面量创建一个字符串的两种方法,String::from的静态方法,&str的to_string方法 let s = String::from("hello"); let s = "hello".to_string(); // 修改字符串 let mut s = String::from("abc"); // 往后添加字符串,push_str的参数是引用的形式&str s.push_str("def"); // 插入单个字符,单个字符使用单引号 s.push('g'); // 使用+号拼接字符串,加号的左边是String类型,右边是&str类型,左边的变量的所有权将被加号获取而不再有效 let s1 = String::from("hello"); let s2 = String::from(", world"); // s1 的所有权将被转移,不再可用,而s2由于使用引用,所以可以继续使用 // 加号的第二个签名是&str,而我们传入的是&String也是合法的,因为Rust使用使用解引用强制转换的技术,将&s2转化为&s2[..] // &s2[..] 是&str类型 let s = s1 + &s2; println!("{},{}", s, s2); let k:&str = &s[2..]; // 使用format!宏来拼接字符串,format!不会夺取任何参数的所有权 let s = format!("{}, {}! {}.", "hello", "world", "lee"); println!("{}", s); // String采用utf-8编码,所以一个中文占用3个字节;以下输出3 println!("{}", "我".to_string().len()); // 虽然字符串不允许使用下标直接访问,但可以使用切片获取某个范围的字符串 println!("{}", &s[0..1]); let s = "我是中国人".to_string(); // 需要注意如果切片的范围不是一个合法的字符串,则会直接panic // 以下将发生运行时panic:thread 'main' panicked at 'byte index 1 is not a char boundary; it is inside '我' (bytes 0..3) of `我`', src/main.rs:69:21 // println!("{}", &s[0..1]); // 使用chars函数,可以获取根据编码获取字符串中的字符值 for i in s.chars(){ println!("{}", i); } // 与此相对,使用bytes,则获取每一个字节的内容 for i in s.bytes(){ println!("{}", i); } ``` ### HashMap HashMap并没有在预加载库中,所以需要使用`use std::collections::HashMap;`进行导入。 HashMap如果键和值实现了CopyTrait,则会复制一份。如果持有所有权的类型,则会将所有权转移到HashMap中。如果是引用类型,则不会取得所有权,由生命周期保证引用的有效性。 ```rust use std::collections::HashMap; // 初始化一个hashmap,不指定类型,编译器可以从h.insert里推断出类型来为HashMap<&str,i32> let mut h = HashMap::new(); h.insert("lee", 1220); // 使用Vec来构建HashMap let teams = vec![String::from("blue"), String::from("yellow")]; let scores = vec![10, 50]; // h的类型声明是必须的,因为collect可以返回多种类型,需要明确这里需要返回的类型,但是泛型可以使用_代替,由编译器来推断 // h的类型为HashMap<&String, &i32> let mut h: HashMap<_, _> = teams.iter().zip(scores.iter()).collect(); // 获取HashMap中的值,注意这里的值是&String,不能直接使用&str let blue = String::from("blue"); // get函数获取的值为Option,如果不存在,则返回None // get取得的结果是value的引用值,在这个场景中为&&i32 let blue_team_score = match h.get(&blue) { // 由于值是&&i32,所以需要两次解引用成i32值,否则与None的返回值不匹配 Some(i) => **i, None => 0, }; println!("{}", blue_team_score); // 使用for循环获取HashMap里的值,由于使用&h,所以这里的key为&&String,value为&&i32 for (key, value) in &h { println!("key:{}, value:{}", key, value); } let k = String::from("blue"); // 更新值,如果是直接覆盖,使用insert即可 h.insert(&k, &20); // 通过entry函数返回Entry枚举类型,其or_insert方法可以判断值是否存在,不存在则插入,存在则不处理 // 其返回HashMap中value的可变引用,在此为&mut &i32,可以对其进行修改 let e = h.entry(&k).or_insert(&30); *e = &11; // {"blue": 11, "yellow": 50} println!("{:?}", h); // 例子,查看一个字符串中每一个字符出现的次数 let text = "hello world hello lee ok"; let mut map = HashMap::new(); for i in text.split_whitespace() { let count = map.entry(i).or_insert(0); *count += 1; } // {"ok": 1, "world": 1, "lee": 1, "hello": 2} println!("{:?}", map); ``` ## 错误处理 * 不可恢复错误:使用panic!宏,其参数与println!类似,支持占位符; * 访问Vec越界也会产生panic; * 在cargo.toml中的profile.release节添加`panic= 'abort'`来减少bin文件的大小(因为减少了栈展开所需要的信息); * 添加`RUST_BACKTRACE=1`可以输出更加详细的panic信息,例如`cargo run --bin error --release`; * 如果是可恢复错误,使用Result<T, E>做为返回值来处理包含正常情况和异常情况,正常情况下返回Ok(T),异常时返回Err(E)。 ```rust enum Result<T, E>{ Ok(T), Err(E), } ``` 以下例子位于example/src/bin/error.rs: ```rust let file_name = "Cargo.toml"; // 对于有可能出错的函数可以返回Result,Ok表示正常返回,Err表示异常 let mut f = match File::open(file_name) { Ok(file) => file, Err(e) => panic!("open file error:{:?}", e), }; // 读取文件的内容,并输出 let mut c = String::new(); f.read_to_string(&mut c); println!("{}", c); let file_name = "hello.txt"; let f = match File::open(file_name) { Ok(file) => file, // 使用e.kind()为区别不一样的类型 Err(e) => match e.kind() { // 不存在的时候就创建,返回成功创建的句柄 ErrorKind::NotFound => match File::create(file_name) { Ok(file) => file, Err(e) => panic!("create file error:{:?}", e), }, // 其它错误统一命中这个分支,报错panic other_error => panic!("open file error:{:?}", other_error), } }; // 使用Result.unwrap()函数来快速获取Ok的值,如果是Err,则直接panic let f: File = File::open(file_name).unwrap(); // 与unwrap一样,只是传入了一个字符串做为panic时的信息 let f: File = File::open(file_name).expect("Fail to open file"); // 传播错误 // 以下函数的功能等同于std::fs::read_to_string(file_name) fn get_content_by_file_name(name: &str) -> Result<String, io::Error> { let mut f = match File::open(name) { Ok(file) => file, Err(e) => return Err(e), }; // 读取文件的内容,并输出 let mut c = String::new(); return match f.read_to_string(&mut c) { Ok(_) => Ok(c), Err(e) => Err(e), }; } // 使用?运算符简化写法 // 注意使用?运算符与match不一样的地方是在Err类型不匹配的时候,会自动调用from函数进行隐式转换(需要实现From trait) fn get_content_by_file_name2(name: &str) -> Result<String, io::Error> { // 如果需要将Result的Err返回,则在最后使用?表达式来达到目的 let mut f = File::open(name)?; // 读取文件的内容,并输出 let mut c = String::new(); f.read_to_string(&mut c)?; Ok(c) } // 使用链式调用更加简化写法 fn get_content_by_file_name3(name: &str) -> Result<String, io::Error> { let mut c = String::new(); File::open(name)?.read_to_string(&mut c)?; Ok(c) } ``` ## 泛型、Trait、生命周期 ### 泛型 泛型代码的性能问题:Rust在编译期间将泛型代码单态化(monomorphization),即将泛型代码根据调用时的类型生成对应的代码。所以不会对运行时造成性能影响。例如 Option\<T\>类型在应用到i32和i64上时,生成了以下两种类型Option_i32,Option_i64。 以下例子位于example/src/bin/generic.rs: ```rust fn main() { // 在方法中使用泛型,在函数名称后添加尖括号,并在括号中添加类型说明, // <T:PartialOrd + Copy>表示这个类型必须实现PartialOrd和Copy这两个Trait // 参数为对应类型的数组切片,返回对应类型的值 // 由于对元素使用了大于比较计算符,所以类型T必须实现std::cmp::PartialOrd // 由于需要从list[0]中取出数据,所以需要实现Copy;也可以使用引用来处理 fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { let mut max = list[0]; for &item in list.iter() { if item > max { max = item } } max } // 使用引用的版本,不需要实现Copy fn largest2<T: PartialOrd>(list: &[T]) -> &T { let mut max = &list[0]; for item in list.iter() { if *item > *max { max = item } } max } println!( "{},{},{}, {}", largest(&[1, 2, 3, 4, 5, 6, 9, 3, 4, 6]), largest(&[1.0, 3.0, 1.1, 5.5, -1.0, -2.4]), // 动态数组可以转化为数组切片 largest(&vec![1, 2, 3, 4, 5, 4, 3, 2, 1]), largest(&vec!['a', 'b', 'e', 'd', 'k', 'i', 'g']), ); // 在结构体中使用泛型,在结构体名之后使用尖括号来声明 struct Point<T> { x: T, y: T, } impl<T> Point<T> { fn x(&self) -> &T { &self.x } // 在泛型的结构里定义泛型的方法 fn other<U>(&self, other: Point<U>) -> Point<U> { other } } // 在枚举中使用泛型,我们之前看到的Option和Result都有使用,不再举例 enum Option<T> { Some(T), None, } enum Result<T, E> { Ok(T), Err(E), } } ``` ### Trait * trait是指某些特定类型拥有的,而且可以被其它类型所共享的功能集合,类似于其它语言的interface。 * **实现trait的代码要么位于trait定义的包中,要么位于结构体定义的包中,而不能在这两个包外的其它包中,这个规则称之为孤儿规则,是程序一致性的组成部分**。 以下例子位于example/src/bin/trait.rs: ```rust // 定义多种文章共有的摘要功能trait pub trait Summary { fn summarize(&self) -> String; // trait也可以提供一个默认实现,这样实现了这一trait的结构体,如果没有提供实现,则以默认实现为准 fn summarize2(&self) -> String { String::from("Read more") } } pub struct NewsArticle { pub headline: String, pub location: String, pub author: String, pub content: String, } // 为某一个结构实现trait,使用关键字impl和for // 实现的trait跟普通函数一样,可以被调用 impl Summary for NewsArticle { fn summarize(&self) -> String { format!("{},{},{}", self.headline, self.author, self.location) } } pub struct Tweet { pub username: String, pub content: String, pub reply: bool, pub retweet: bool, } impl Summary for Tweet { fn summarize(&self) -> String { format!("{},{}", self.username, self.content) } // 重载了默认实现,这样就无法调用到默认实现了 fn summarize2(&self) -> String { format!("summarize2....") } } let tweet = Tweet { username: "lee".to_string(), content: "content".to_string(), reply: false, retweet: false, }; // trait实现的函数,可以像普通函数一样调用,summarize2调用则是默认的实现 println!("tweet: {}, summary2:{}", tweet.summarize(), tweet.summarize2()); // 将trait作为参数 // 这个函数接收实现了Summary trait的结构体类型,在这里可传入Tweet和NewsArticle pub fn notify<T: Summary>(item: &T) { println!("breaking news1:{}", item.summarize()) } notify(&tweet); // 可以使用impl形式的语法糖来简化写法,与之前的一致 // 是否简化也区别于实际场景,例如多个函数使用同一个约束时,使用泛型表达式则更加方便 pub fn notify2(item: &impl Summary) { println!("breaking news2:{}", item.summarize()) } notify2(&tweet); // 使用多个约束时使用+号来处理,这里的item必须实现Display和Summary两个trait pub fn notify3<T: Display + Summary>(item: T) {} // 在复杂情况下使用where语句可以使得函数签名更清晰,以下两种方式是等价的 fn some_func<T: Display + Clone, U: Clone + Debug>(t: T, u: U) -> i32 { 1 } fn some_func2<T, U>(t: T, u: U) -> i32 where T: Display + Clone, U: Clone + Debug { 1 } // 可以返回可以使用impl形式,但只能返回一中类型,要么是Tweet,要么是NewsArticle,不能在不同的分支返回两种类型 fn return_summarizable() -> impl Summary { Tweet { username: "".to_string(), content: "".to_string(), reply: false, retweet: false, } } // 以下无法通过编译,对于泛型,需要深入研究一下机制,为什么以下函数无法通过编译 // fn return_summarizable2<T: Summary>(item:T) -> T { // Tweet { // username: "".to_string(), // content: "".to_string(), // reply: false, // retweet: false, // } // } // 使用trait约束来有条件地实现方法 struct Point<T> { x: T, y: T, } // 为所有类型的T的Point实现new方法 impl<T> Point<T> { // 大写的Self与小写的self区别 fn new(x: T, y: T) -> Self { Point { x, y } } } // 只为实现了PartialOrd和Display的Point实现cmp方法 impl<T: PartialOrd + Display> Point<T> { fn cmp(&self) { if self.x > self.y { println!("x>y") } else { println!("x<=y") } } } // 也可以使用一个trait约束来实现另外一个trait,称之为覆盖实现(blanket implementation) // 例如以下的例子,为了实现了Display的类型实现Summary方法 impl<T: Display> Summary for T { fn summarize(&self) -> String { format!("read more:{}", self) } } // 以下例子无法通过编译,因为Display不在此包中,T这一也不在此包中,受孤儿规则限制,将报错 // 报错:Only traits defined in the current crate can be implemented for arbitrary types [E0117] // impl<T: Summary> Display for T { // fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { // write!(f, "({}, {})", self.x, self.y) // } // } // 因为上面为实现Display的类型实现了Summary,而i32实现了Display,所以i32实现了Summary // 输出read more:2 println!("{}", 2.summarize()); ``` ### 生命周期 * 生命周期大部分情况下可以推导出来,当无法推导时,就必须手动标注生命周期; * 生命周期最主要的目的是避免悬垂引用,进而避免程序引用到非预期的数据; * Rust中不允许空值的存在; * 借用检查器(borrow checker):用于检查各个变量的生命周期长短,以判断引用是否合法。 生命周期的标注: * 生命周期的标注以单引号开始,后跟小写字母(通常情况下),通常非常简短,例如```'a```; * 标注跟在&之后,并使用空格与引用类型区分开,例如`&'a i32`、`&'a mut i32`等。 每一个引用都有生命周期,而函数在满足一定条件下,可以省略生命周期声明,称为生命周期省略规则。 使用以下三条规则计算出生命周期后,如果仍然有无法计算出生命周期的引用时,则编译出错: 1. 每一个引用参数都有自己的生命周期,这一条用于计算输入生命周期; 2. 只存在一个输入生命周期时,这个生命周期将赋值给所有的输出生命周期参数,这一条用于计算输出生命周期; 3. 当拥有多个输入生命周期参数,而其中一个是&self或&mut self时,self的生命周期会被赋予给所有的输出生命周期参数。这条规则使方法更加易于阅读和编写,因为它省略了一些不必要的符号。 以下例子位于example/src/bin/live_time.rs: ```rust let mut r = &2; { let x = 5; // 以下无法通过编译,因为x在内部作用域内,而r在main作用域,r的生命周期大于x,无法使用x的引用。 // `x` does not live long enough // r = &x } println!("{}", r); // 如果不加生命周期标注的话,无法确定返回值的生命周期,无法通过编译 // 由于x,y两个参数都用于做为引用返回,所以x,y必须都要标明生命周期 // 这里的'a会被具体化为x,y的生命周期中重叠的那一部分 fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { if x.len() > y.len() { x } else { y } } let s1 = String::from("s11"); let mut s4 = ""; { let s2 = String::from("s2"); // longest返回值的生命周期是s1和s2中生命周期较短的那个,即s2的生命周期 // s3的生命周期与s2一样,所以能通过编译 let s3 = longest(&s1, &s2); println!("{}", s3); // 以下无法通过编译,因为s4的生命周期大于s2 // s4 = longest(&s1, &s2); } println!("{}", s4); // 以下这个函数不满足生命周期省略规则,所以必须手动标注 // fn longest(x:&str, y:&str)->&str{} // 以下函数应用规则1和规则2后,所有的输入输出引用参数周期都确定,所以可以省略 // fn first_word(x:&str)->&str{} // 结构体中引用字段的生命周期标 struct ImportantExcerpt<'a> { part: &'a str, } impl<'a> ImportantExcerpt<'a> { fn level(&self) -> i32 { 2 } // 应用第一条规则和第三条规则,可以得出正确的生命周期,所以以下这个可以周期可以省略 fn announce_and_return_part(&self, announcement: &str) -> &str { self.part } // 应用第一条和第三条规则,得出的生命周期不正确,所以在没有生命周期房间里时编译报错 fn display_part_and_return<'b>(&self, announcement: &'b str) -> &'b str { announcement } } // 'static是固定写法,表示生命周期是整个程序的执行周期 // 所有字符串字面量都拥有'static生命周期 let s: &'static str = "abc"; use std::fmt::Display; // 同时使用生命周期,泛型,trait约束的例子 // 生命周期必须在泛型类型声明之前,也可以使用where进行trait约束 // 生命周期也是泛型的一种?? fn longest_with_announcement<'a, T:Display>(x: &'a str, y: &'a str, anno: T) -> &'a str { println!("{}", anno); if x.len() > y.len() { x } else { y } } ``` ## 编写自动化测试 Rust中的单元测试一般与要测试的代码放在同一个文件中,使用的模块名称为tests,通过```#[cfg(test)]```来标记,让编译器只在cargo test时才编译和运行这一部分代码,在cargo build等场景会剔除这些代码。 在函数上使用```#[test]```称为属性(attribute),与C#的attribute以及Java的annotation一样,用于给编译器提供更多的信息。 cargo test参数说明之\-\-之后的参数: * \-\-test-threads=1:运行的并发数,默认是多个case并行执行,可以设置成1为串行执行; * \-\-nocapture:将测试用例中打印出来内容输出显示出来。默认情况下这些内容会被捕获并丢弃; * \-\-ignored:专门运行被```#[ignore]```标记的case。 cargo test参数说明之\-\-之前的参数: * \-q:静默情况下运行测试用例,输出的信息比较有限; * \-\-test file_name:用于指定运行集成测试的文件,注意不用跟.rs后缀名。 cargo test允许我们指定需要运行的用例名,例如cargo test adder,则所有case名中包含有adder的case都会被运行(例如:tests::adder_test),这种方法只能指定一个匹配字符串,无法指定多个。 在```#[test]```标记之后,跟上```#[ignore]```的测试函数,默认情况下不会运行,只有使用\-\-ignored时,才会专门运行这些case,例如```cargo test -- --ignored```。 本单元的例子位于adder项目中: ```rust //! # Adder //! //! 测试做为包的注释,包含有一些小组件 use std::ops::Add; /// 定义一个泛型加法 /// /// # Example /// /// 例子,一般是测试用例 /// ``` /// assert_eq!(5, adder::adder(3,2)); /// assert_eq!(9.8, adder::adder(3.3, 6.5)); /// ``` /// # Panics /// /// 可能Panic的场景 /// /// # Errors /// 如果返回Result时,这里写明Error返回的场景,以及返回的Error值 /// /// # Safety /// /// 当使用了unsafe关键字时,这里可以说明使用unsafe的原因,以及调用者的注意事项 /// pub fn adder<T: Add + Add<Output=T>>(a: T, b: T) -> T { return a + b; } #[cfg(test)] mod tests { // 引入所有父模块的所有包,这样可以直接使用adder方法,否则adder需要指定完整路径才能使用 use super::*; use std::fs::File; use std::io::Read; // 标记以下函数是一个测试函数,如果没有这个标记,cargo test的时候不会运行 #[test] fn it_works() { // 相等断言 assert_eq!(2 + 2, 4); } #[test] fn adder_test() { // 注意使用了assert_eq和assert_ne这两个断言时,两个参数必须实现了PartialEq和Debug这两个trait,一个用于判断相等,一个用于出错时输出信息 // 以下两个写法等价,推荐使用第一个写法,因为在失败时可以打印出两个参数的值,方便分析原因 assert_eq!(adder(2, 2), 4); assert!(adder(2, 2) == 4); // assert!接收一个bool类型的参数,只有为true时测试才通过 // assert_ne!用于断言两个值不相等 assert_ne!(adder(2.0, 3.0), 6.0); // 这些断言在必要参数之后的信息都会被用于format!输出额外的信息 assert_eq!(adder(3, 4), 7, "{}+{} is not equal 7", 3, 4); } #[test] // should_panic属性用于表示这个函数会发生panic // 参数expected会比较panic的信息是否与此相匹配,注意中人包含expected的内容即可 #[should_panic(expected = "panicked")] fn check_panic() { panic!("i panicked") } #[test] // 使用Result做为测试用例的返回值时,只要有Err返回,就测试失败 // 这种情况下可以使用?表达式来简化测试用例的编写 fn use_result() -> Result<(), std::io::Error> { let mut f = File::open("./cargo.toml")?; let mut s = String::new(); let _ = f.read_to_string(&mut s)?; return Ok(()); } #[test] #[ignore] // 默认情况下忽略此case,可以通过--ignored来专门运行这种case fn long_time_test() {} } ``` 集成测试: * 在src同级别建立tests目录,在这个目录下可以创建任意的集成测试用例;tests目录只在cargo test时进行编译和执行,其它情况会忽略; * tests目录下每一个文件都是独立包名,所以不用担心测试函数会重名; * 可以在tests目录下建立子目录,做为公共使用的部分,或者隐藏测试中的细节等等,子目录中的函数也可以标记为```#[test]```,但他只在tests目录下的文件引用到时执行; * 如果将子目录做为公共部分使用,一般不在里面设置测试用例,因为如果多个测试模块引用的话,这个case将被运行多次; * 无法在集成测试中引用main.rs,所以一般我们将复杂的操作移到lib.rs中,而main.rs中只保留简单的胶水代码逻辑。 ```rust // src/tests/integation.rs #[test] fn adder_test() { assert_eq!(adder::adder(9.0, 10.0), 19.0); } #[test] fn my_note() { assert_eq!(adder::adder(9.0, 10.0), 19.0); } mod sub; ``` ```rust // src/tests/sub/mod.rs #[test] pub fn setup() {} ``` ## minigrep例子 * `std::env::args()`获取命令行参数,格式与其它语言一样; * `std::process::exit(1)`退出进程,这个函数签名为`pub fn exit(code: i32) -> !`,`!`表示从来不会返回; * `std::fs::read_to_string()`读取文件内容; * `std::env::var("CASE_INSENSITIVE")`获取环境变量值; * `eprintln!`将错误信息打印到标准错误输出。 代码位于minigrep项目中: ```rust // main.rs use minigrep::*; // main函数里的代码无法进行单元测试和集成测试,所以main函数这块保持简单,把逻辑移到lib.rs下 fn main() { // std::env::args()返回的是Args实现了Iterator,使用collect转化为Vec<String> // 因为collect返回的也是泛型,编译器无法自动推断需要返回的类型,所以给args的类型标注不可省略 let args: Vec<String> = std::env::args().collect(); // Result结构的unwrap_or_else方法接收一个函数来做错误处理 // 处理函数包含一个闭包参数,使用竖线包起来,获取到的值为Result的E中的值 // 处理函数必须返回Result的T值(正确的值),但std::process::exit(1)直接退出进程,所以可以编译通过 // exit的返回值为->!,表示从不会返回:pub fn exit(code: i32) -> ! let config = Config::new(&args).unwrap_or_else(|err| { // 使用eprintln!将错误信息输出到标准错误输出 eprintln!("Problem parsing arguments: {}", err); std::process::exit(1); }); // // 使用迭代器的版本 // let config = Config::new2(std::env::args()).unwrap_or_else(|err| { // eprintln!("Problem parsing arguments: {}", err); // std::process::exit(1); // }); // 使用if let语法,只处理关心的变体 if let Err(e) = run(&config) { eprintln!("Application error: {}", e); std::process::exit(1); } } ``` ```rust // lib.rs // 返回Result中的E为Box<dyn std::error::Error>,表示为实现了Error这一trait的类型 // 具体的类型需要在具体的场景中才能确定,这里的dyn关键字也说明了是一个动态的类型 pub fn run(config: &Config) -> Result<(), Box<dyn std::error::Error>> { let contents = std::fs::read_to_string(&config.filename)?; let result = if config.case_sensitive { search(&config.query, &contents) } else { search_case_insensitive(&config.query, &contents) }; for l in result { println!("{}", l); } Ok(()) } pub struct Config { query: String, filename: String, case_sensitive: bool, } impl Config { // 使用命令行参数来构造Config结构,返回Result结构,在出错时返回str // 返回值中的str中声明了生命周期为全局的,因为字面量常量可以是全局的,此处不设置其实也没有问题,生命周期与输入一致 pub fn new(args: &[String]) -> Result<Config, &'static str> { if args.len() < 3 { return Err("not enough arguments!"); } let query = args[1].clone(); let filename = args[2].clone(); // 读取环境变量来确定是否需要大小写敏感,读取到无error则case_sensitive=false,不区分大小写,如下 // CASE_INSENSITIVE=1 cargo run Nobody poem.txt let case_sensitive = std::env::var("CASE_INSENSITIVE").is_err(); // 变量与结构体字段重名时,可以使用此种方式快速构建 Ok(Config { query, filename, case_sensitive }) } // 使用迭代器版本 pub fn new2(mut args: std::env::Args) -> Result<Config, &'static str> { args.next(); let query = match args.next() { Some(q) => q, None => return Err("no query") }; let filename = match args.next() { Some(f) => f, None => return Err("no filename") }; let case_sensitive = std::env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename, case_sensitive }) } } // 这块需要指定生命周期,表明Vec返回的&str,与contents的生命周期绑定 // 如果contents失败了,那么返回值也将没有意义了 fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut ret: Vec<&str> = Vec::new(); for line in contents.lines() { if line.contains(query) { ret.push(line) } } ret // 使用迭代器版本 // contents.lines().filter(|line| line.contains(query)).collect() } fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { let mut ret: Vec<&str> = Vec::new(); let q = query.to_lowercase(); for l in contents.lines() { if l.to_lowercase().contains(&q) { ret.push(l) } } ret } #[cfg(test)] mod tests { use super::*; #[test] fn one_result() { let query = "duct"; let contents = "\ Rust: safe, fast, productive. Pick three. "; assert_eq!( vec!["safe, fast, productive."], search(query, contents), ); } #[test] fn case_insensitive() { let query = "rust"; let contents = "\ Rust: safe, fast, productive. Pick three. "; assert_eq!( vec!["Rust:"], search_case_insensitive(query, contents), ); } } ``` ## 函数式语言特性:迭代器与闭包 ### 闭包 与闭包相关的三种trait: Fn, FnMut, FnOnce,所有闭包至少实现其中的一个。 这三个trait代表了函数接收参数的三种方式:不可变引用(Fn),可变引用(FnMut),获取所有权(FnOnce)。 rust自动从闭包的定义中推导出其所实现的trait。 所有函数都实现了这三个trait,所以要求传闭包的地方都可以传函数。 这三个trait的区别: * 实现了FnOnce的闭包可以从环境中获取变量的所有权,所以这个类型的闭包只能被调用一次; * 实现了FnMut的闭包从环境中可变地借用值; * 实现了Fn的闭包从环境中不可变地借用值; * 所有闭包都实现了FnOnce,实现了Fn的闭包也实现了FnMut。 以下例子位于example/src/bin/functional.rs中: ```rust fn main() { // 闭包当作匿名函数的一般写法,参数和返回值的类型,由编译器推断出来 let add_one = |x| { x + 1 }; // 如果无法推断,则需要写成这种详细的形式,与函数定义非常类似 let add_one2 = |x: i32| -> i32{ x + 1 }; // 在匿名函数没有捕获环境变量的情况下,与函数一样 fn add_one_fn(x: i32) -> i32 { x + 1 } fn use_fn(x: i32, f: fn(i32) -> i32) -> i32 { f(x) } // 输出2,2,2 // 可见无捕获上下文的闭包与函数一样 println!("{},{},{}", use_fn(1, add_one), use_fn(1, add_one2), use_fn(1, add_one_fn)); // 如果捕获了环境变量,则闭包与函数就不能通用了 let k = 1; let add_one_closure = |x: i32| { x + k + 1 }; // 这里报错,expected fn pointer, found closure // closures can only be coerced to `fn` types if they do not capture any variables // println!("{}", use_fn(1, add_one_closure)); // 函数无法捕获上下文:can't capture dynamic environment in a fn item // use the `|| { ... }` closure form instead // fn f_error(x: i32) -> i32 { // x + k + 1; // } // 以下正常运行,输出12 println!("{}", add_one_closure(10)); // 多个参数时,使用逗号隔离开 let sum = |x, y| { x + y }; // 如果只有一行,可以省略掉大括号 let sum2 = |x, y| x + y; println!("{},{}", sum(1, 2), sum2(2, 3)); // 在不指定类型的闭包,只能推断出一种类型 let closure = |x| x; println!("{}", closure(10)); // 以下将报错,办为之前的调用已经推断closure为(i32)->i32的闭包,不能再使用&str类型了 // expected integer, found `&str` // println!("{}", closure("10")); // 与闭包相关的三种trait: Fn, FnMut, FnOnce,所有闭包至少实现其中的一个 // 这三个trait代表了函数接收参数的三种方式:不可变引用(Fn),可变引用(FnMut),获取所有权(FnOnce) // rust自动从闭包的定义中推导出其所实现的trait // 所有函数都实现了这三个trait,所以要求传闭包的地方都可以传函数 // 这三个trait的区别: // 实现了FnOnce的闭包可以从环境中获取变量的所有权,所以这个类型的闭包只能被调用一次 // 实现了FnMut的闭包从环境中可变地借用值 // 实现了Fn的闭包从环境中不可变地借用值 // 所有闭包都实现了FnOnce,实现了Fn的闭包也实现了FnMut // 接收Fn trait做为参数的函数 fn do_1<T: Fn(i32) -> i32>(x: i32, f: T) -> i32 { f(x) } let k = vec![1, 2]; let c_1 = |x| x + k[0] + 1; fn f_1(x: i32) -> i32 { x + 1 } // // 输出5,3 println!("{},{}", do_1(1, c_1), do_1(1, f_1)); println!("{}", c_1(1)); // 使用move关键可以获取变量的所有权 let c_1 = move |x| x + k[0] + 1; // ???很奇怪的现象,如果加上下面这一行,则后面的两次调用将报错: borrow of moved value: `c_1` // 但如果没有下面这一行,则后面的两次调用则可以通过 // do_1(1, c_1); println!("{}", c_1(1)); println!("{}", c_1(1)); // FnOnce的例子 fn do_2<T: Fn() -> String>(f: T) { f(); } let a = "aa".to_string(); // c_2因为返回了a变量,而String没有实现Copy trait,所以相当于c_2获取了a的所有权并返回了a,所以c_2只实现了FnOnce trait,无法被传递到Fn作为参数的函数中 let c_2 = || a; // 以下一行将报错: this closure implements `FnOnce`, not `Fn` // do_2(c_2); fn do_3<T: FnOnce() -> String>(f: T) { f(); } // 运行正常 do_3(c_2); // 以下编译报错: use of moved value: `c_2` // 因为c_2是FnOnce没有实现Copy,所以无法被使用两次 // do_3(c_2); // FnMut的例子 let mut k = 3; let mut c_3 = || { k = k + 1; k }; println!("{}", c_3()); // 以下将无法通过编译,因为c_3使用k的可变引用,不能再拥有k的其它引用了 // println!("{},{}", k, c_3()); } ``` ### 迭代器 比起使用for循环的原始实现,Rust更倾向于使用迭代器风格;迭代器可以让开发者专注于高层的业务逻辑,而不必陷入编写循环、维护中间变量这些具体的细节中。通过高层抽象去消除一些惯例化的模板代码,也可以让代码的重点逻辑(例如filter方法的过滤条件)更加突出。 **迭代器是Rust语言中的一种零开销抽象(zero-cost abstraction)**,这个词意味着我们在使用这些抽象时不会引入额外的运行时开销。 以下例子位于example/src/bin/iterator.rs中: ```rust fn main() { // 迭代器允许你依次为序列中的每一个元素执行某些任务 // 迭代器是惰性的,除非主动调用方法来消耗,否则不会有任何作用 // 迭代器实现了Iterator 这一trait,Iterator有多个方法,但大多都提供了默认的实现 // 要实现Iterator只需要实现next方法即可 trait Iterator1 { // 关联类型,用于存储next返回值的类型 type Item; // Self::Item表示返回的Option存储的是Item的类型 // next返回被包裹在Some中的元素,在遍历结束时返回None fn next(&mut self) -> Option<Self::Item>; // 省略默认实现的方法 // ... } let mut v = vec![1, 2, 3]; // 必须将iter标识成mut的,因为调用next会改变iter内部的状态 // iter()方法返回的是一个不可变引用迭代器,next的返回值是数组中元素的不可变引用 let mut iter = v.iter(); // 1,2,3,true println!("{},{},{},{}", iter.next().unwrap(), iter.next().unwrap(), iter.next().unwrap(), iter.next() == None); // 返回可变引用 for i in v.iter_mut() { *i += 1; } // [2,3,4] println!("{:?}", v); // 使用into_iter获取其所有权,后续v不再可用 println!("{}", v.into_iter().next().unwrap()); // 迭代适配器,以及与闭包共同实现 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let add2: Vec<i32> = v.iter().map(|x| x + 2).collect(); let min = 5; // 这里使用filter的给到的闭包参数为&&x,要么使用**x解引用,要么在参数中使用&&x来表示x是一个i32 let big: Vec<&i32> = v.iter().filter(|&&x| x + 2 > min).collect(); // [3, 4, 5, 6, 7, 8, 9, 10, 11],[6, 7, 8, 9] println!("{:?},{:?}", add2, big); // 创建自定义的迭代器 struct Counter { count: i32, } impl Counter { fn new() -> Counter { Counter { count: 0 } } } impl std::iter::Iterator for Counter { type Item = i32; fn next(&mut self) -> Option<Self::Item> { self.count += 1; if self.count > 5 { None } else { Some(self.count) } } } for i in Counter::new() { println!("{}", i) } // 一些迭代器复杂的用法 // Iterator这个trait有很多方法的默认实现,依赖于next方法,我们可以直接使用完成复杂的功能 // 以下有一个特殊的语法,在方法后面添加::<typeHint>,可以给编译器提示返回的值类型为typeHint,用于无法推断类型的场景时使用 // Counter::new() is [1, 2, 3, 4, 5] // Counter::new().skip(1) is [2, 3, 4, 5] // Counter::new().zip(Counter::new().skip(1)) is [(1, 2), (2, 3), (3, 4), (4, 5)] // .map(|(a,b)| a*b) is [2, 6, 12, 20] // .filter(|x| x % 3 == 0) [6, 12] // .sum() is 18 let c: i32 = Counter::new().zip(Counter::new().skip(1)) .map(|(a, b)| a * b) .filter(|x| x % 3 == 0) .sum(); println!("Counter::new() is {:?}", Counter::new().collect::<Vec<i32>>()); println!("Counter::new().skip(1) is {:?}", Counter::new().skip(1).collect::<Vec<i32>>()); println!("Counter::new().zip(Counter::new().skip(1)) is {:?}", Counter::new().zip(Counter::new().skip(1)).collect::<Vec<(i32, i32)>>()); println!(" .map(|(a,b)| a*b) is {:?}", Counter::new().zip(Counter::new().skip(1)).map(|(a, b)| a * b).collect::<Vec<i32>>()); println!(" .filter(|x| x % 3 == 0) {:?}", Counter::new().zip(Counter::new().skip(1)).map(|(a, b)| a * b).filter(|x| x % 3 == 0).collect::<Vec<i32>>()); println!(" .sum() is {:?}", c); } ``` ## 进一步认识Cargo及crates.io Rust中的发布配置是一系列定义好的配置方案,例如cargo build时使用dev配置方案,添加`--release`后,使用release配置方案。 在Cargo.toml中添加`[profile.dev]`和`[profile.release]`配置段可以对这两个方案进行配置。 在没有配置时,有一套默认的配置,当自定义了配置时,会使用自定义配置的子集覆盖默认的配置。 提到的配置: * `opt-level=1`:编译优化程序,0~3优化递增,release默认是3,dev为0。 ### 文档注释 Rust中使用三斜线做为文档注释,支持markdown语法;被包在markdown里的代码片段会被当成测试case,在运行cargo test的时候运行。 ```rust // 位于adder项目中 /// 定义一个泛型加法 /// /// # Example /// /// 例子,一般是测试用例 /// ``` /// assert_eq!(5, adder::adder(3,2)); /// assert_eq!(9.8, adder::adder(3.3, 6.5)); /// ``` /// # Panics /// /// 可能Panic的场景 /// /// # Errors /// 如果返回Result时,这里写明Error返回的场景,以及返回的Error值 /// /// # Safety /// /// 当使用了unsafe关键字时,这里可以说明使用unsafe的原因,以及调用者的注意事项 /// pub fn adder<T: Add + Add<Output=T>>(a: T, b: T) -> T { return a + b; } ``` 可以使用```cargo doc --open```来打开文档查看。 使用```//!```开头的注释,不像```///```为紧跟的代码提供注释,而是为整个包,或者整个模块提供注释; 这种类型的注释,只能放在文件最开头。 ### 使用pub use重新组织结构 ```rust // example/src/lib.rs //! # Art //! //! 测试用于艺术建模的库 // 使用pub use 重新组织API结构 pub use crate::kinds::PrimaryColor; pub use crate::kinds::SecondaryColor; pub use crate::utils::mixed; pub mod kinds { pub enum PrimaryColor { Red, Yellow, Blue, } pub enum SecondaryColor { Orange, Green, Purple, } } pub mod utils{ use crate::kinds::*; pub fn mixed(c1:PrimaryColor, c2:PrimaryColor) -> SecondaryColor{ SecondaryColor::Orange } } ``` ```rust // example/src/bin/pub_use_example.rs // use example::kinds::PrimaryColor; // use example::utils::mixed; // 使用pub use重新导出包结构后,就可以使用直接使用一级目录的结构,不用关心原包中的结构了 use example::PrimaryColor; use example::mixed; fn main(){ let red = PrimaryColor::Red; let yellow = PrimaryColor::Yellow; mixed(red, yellow); } ``` ### 使用crates.io分享代码 创建步骤: 1. 使用github账号登录[https://crates.io/](https://crates.io/); 2. 在账号设置中绑定邮箱,并验证; 3. 在账号设置中生成New Token; 4. 在本地使用cargo login xxxx(your token)来保存token到本地(~/.cargo/credentials); 5. 在项目中填写足够的信息(Cargo.toml): ```ini [package] name = "guessing_game_xiaochai" version = "0.1.0" authors = "[xiaochai<soso2501@gmail.com>]" edition = "2018" description = "a game demo" license = "MIT" ``` 6. 在命令行中运行cargo publish,此时,会将代码提交到远程:https://crates.io/crates/guessing_game_xiaochai。如果本地是git,并且有未提交的文件,将会生成错误,可以使用``` cargo publish --allow-dirty```忽略git信息。<br/> 更新版本: 1. 修改Cargo.toml,增加版本号; 2. 运行```cargo publish```即可提交新版本。 撤回某个版本: * ```cargo yank --vers 0.1.0```可以撤回某个版本,虽然还能在crate.io上看到对应版本,但新的项目无法引用这个版本了; * 使用```cargo yank --vers 0.1.0 --undo```可以取消撤回操作。 如果你分享的是一个二进制包,可以使用`cargo install guessing_game_xiaochai`来下载安装,会安装到~/.cargo/bin目录下。 ### 工作空间 同一个工作空间下的项目使用同一个Cargo.lock文件,使用以下步骤新建一个工作空间: 1. 新起目录,例如workspace_example,cd workspace_example; 2. 创建Cargo.toml文件,内容为: ```ini [workspace] members = [ "adder" ] ``` 3. 在目录下使用cargo new来创建adder二进制包; 4. 此时不管在workspace_example目录下运行cargo run 还是在workspace_example/adder下,最终的target都会在workspace_example/target目录下;换种说法,adder项目目前已经不是一个独立的项目了,要么1. 在workspace_example/Cargo.toml添加exclude来排除adder项目;2. 或者是在workspace_example/adder/Cargo.toml中添加空的[workspace]段,这样才能将adder单独编译: ```ini [workspace] members = [ ] exclude = [ "adder", ] ``` 5. 添加add-one这个代码包```cargo new add-one --lib```; 6. adder的二进制文件需要依赖adder-one包,需要在adder/Cargo.toml的dependencies段添加```add-one = { path = "../add-one" }```; 7. 在main函数中使用。 ```rust fn main() { println!("Hello, world!"); println!("{}", add_one::add_one(10)); } ``` 8. 在workspace_example下运行```cargo run```,则运行了adder包中的二进制文件;如果一个工作空间下有多个二进制项目的话,可以使用\-p参数来指定项目 ```cargo run -p adder``` ### 扩展cargo 如果在$PATH中包含有cargo-something的可执行文件,那么可以使用cargo something来运行此文件。 例如刚安装的guessing_game_xiaochai程序: ```shell ➜ workspace_example git:(master) ✗ echo $PATH /usr/local/bin:/usr/bin:/bin:/usr/sbin:/Users/bytedance/.cargo/bin ➜ workspace_example git:(master) ✗ mv ~/.cargo/bin/guessing_game_xiaochai ~/.cargo/bin/cargo-guessing_game_xiaochai ➜ workspace_example git:(master) ✗ cargo guessing_game_xiaochai secret number is 86 Guess the number! Please input your guess: ... ``` ## 智能指针 * 指针是指包含内存地址的变量; * 引用是最常用的指针,没有额外的开销; * 智能指针是一些数据结构,他们的功能类似于指针,但拥有额外的元数据和附加功能; * 引用只是借用数据指针,而智能指针一般拥有数据所有权; * String和`Vec<T>`是智能指针,他们拥有一片内存区域并允许进行操作,他们还拥有元数据(如容量),并提供额外的功能或保障; * 智能指针一般使用结构体来实现,需要实现Drop和Deref两个trait: > Deref trait使得此结构体的实例可以拥有与引用一致的行为;<br/> > Drop trait使得在离开作用域时运行一段自定义代码。 常用智能指针: * `Box<T>`: 可用于在堆上分配值; * `Rc<T>`: 允许多重所有权的引用计数智能指针; * `Ref<T>`,`RefMut<T>`:可以通过`RefCell<T>`访问,是一种可以在运行时而非编译时执行借用规则的类型。 内部可变性:不可变对象可以暴露出能够改变内部值的API。 规避循环引用导致的内存泄露。 ### 使用`Box<T>`在堆上分配内存 使用场景: * 在需要固定尺寸变量的上下文中使用编译期无法确定大小的类型; * 需要传递大量数据的所有权,但又不希望对数据进行复制; * 当希望使用实现了某个trait的类型,而又不关心具体类型时。 基本使用方法: 1. 使用Box::new(T)在堆上空间,将T保存于这一空间内,并返回指向堆上这一空间的指针; 2. 在变量前加*(解引用运算符)来获取堆上真正的值,称为解引用。 以下代码位于example/src/bin/smart_pointer.rs中: ```rust // Box的基本使用方法 // a和b都是Box<i32>类型,与i32不同的是,Box<i32>类似于指向堆上两个i32类型的指针 let a = Box::new(128); let b = Box::new(256); // 所以a和b无法直接进行操作,因为Box实现了Deref这一trait,所以可以使用*来解引用 let c: i64 = *a + *b; println!("{}", c); // 384 ``` 定义递归类型时需要使用Box,因为不能在编译期确定内存空间的大小 ```rust // 递归类型必须使用Box enum List { Cons(i32, Box<List>), // 使用Cons(i32, List)将无法通过编译:recursive type `List` has infinite size Nil, } use List::{Nil, Cons}; let list = Cons( 1, Box::new(Cons( 2, Box::new(Cons( 3, Box::new( Nil ), )), )), ); fn print_list(l: List) { match l { Cons(i, nl) => { print!("{}=>", i); print_list(*nl); } Nil => { println!("end"); } } } print_list(list); ``` ### 自定义智能指针 ```rust // 自定义类似于Box的智能指针(但数据存在在栈上) struct MyBox<T> (T); // 元组结构体 impl<T> MyBox<T> { // 提供一个参数,并将此存入结构体中 fn new(x: T) -> MyBox<T> { MyBox(x) } } ``` 涉及到两个trait: Deref 和Drop。 #### Deref Deref解引用trait,一个类型实现了Deref trait时,可以使用解引用运算符: ```rust // 为MyBox实现Deref,这样就可以使用解引用运算符 impl<T> Deref for MyBox<T> { // 关联类型 type Target = T; // 也可以写成fn deref(&self) -> &T { fn deref(&self) -> &Self::Target { // 以下等价于self.0 match self { MyBox(i) => i } } } let a = MyBox(10); // 这里的*a类似于*(a.deref()),称之为隐式展开 println!("{}", *a + 10) ``` 隐式解引用转换:当函数参数为某个类型的引用时,如果传入的参数与此不匹配,则编译器会自动进行解引用转换,直到类型满足要求。 解可变引用:实现DerefMut trait,要实现这一trait,必须首先实现Deref trait。 可变性转换有三条: 1. 当T: Deref<Target=U>时,允许&T转换为&U; 2. 当T: DerefMut<Target=U>时,允许&mut T转换为&mut U; 3. 当T: Deref<Target=U>时,允许&mut T转换为&U; 这三条规则不会破坏借用规则。 ```rust // 隐式解引用转换 fn hello(name: &str) { println!("hello, {}", name); } let mb: MyBox<String> = MyBox::new("lee".to_string()); // 正常的写法如下,其发生的步骤1. 需要将MyBox解引用转化为String,2. 使用[..]将String转化为切片&str,这样才符合参数要求 hello(&(*mb)[..]); // 使用自动解引用也能满足这个要求,mb实现了Deref,所以可以获取到String,String也实现了deref,其返回为&str,所以编译器进行了两次解引用转换 // 以上是编译期完成,不会有任何运行时开销 hello(&mb); // 实现可变解引用运算符,实现DerefMut之前必须实现Deref impl<T> DerefMut for MyBox<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } // 满足自动解引用的三条规则 // 当T: Deref<Target=U>时,允许&T转换为&U。 // 当T: DerefMut<Target=U>时,允许&mut T转换为&mut U。 // 当T: Deref<Target=U>时,允许&mut T转换为&U。 fn hello_exp(name: &mut String) -> &mut String { name.push_str(", hello!"); name } let mut b = Box::new("abc".to_string()); // 当T: DerefMut<Target=U>时,允许&mut T转换为&mut U,与&mut *b是一样的 let c = hello_exp(&mut b); println!("{}", c); // 当T: Deref<Target=U>时,允许&mut T转换为&U。 hello(&mut b); ``` #### Drop Drop trait允许我们在离开变量作用域时执行某些自定义的操作,例如释放文件和网络连接等。 `Box<T>`类型通过Drop释放指向堆上的内存。 drop的执行顺序与变量的创建顺序相反。 无法禁用drop的功能,也无法手动调用Drop的drop方法,但可以使用std::mem::drop来提前清理某个值,这个函数在预导入模块中,所以可以直接使用drop来调用。 ```rust // 实现Drop的例子 { struct TestDropStruct { data:String, } impl Drop for TestDropStruct{ fn drop(&mut self) { println!("{}", self.data) } } let _a = TestDropStruct{data:"first object".to_string()}; let _b = TestDropStruct{data:"second object".to_string()}; let _c = TestDropStruct{data:"third object".to_string()}; println!("main end"); // 手动使用std::mem::drop函数来提前清理_c的值 drop(_a); // 以上输出顺序为 // main end // first object // third object // second object // 对于_b,_c来说,丢弃顺序与创建顺序相反,所以_c先调用drop函数 // _a则是由于手动释放导致先执行 } ``` ### `Rc<T>`基于引用计数的智能指针 `Rc<T>`只能用于单线程中,用于那些在编译期无法确认哪个部分会最后释放的场景。 `RC<T>`只能持有不可变的引用,否则会打破引用规则。 ```rust { // 测试引用计数智能指针Rc<T>类型 enum RcList { RcCons(i32, Rc<RcList>), RcNil, } use RcList::*; // 新建一个引用记录类型使用Rc::new来创建,此处a为Rc<RcList>类型 let a = Rc::new( RcCons(3, Rc::new( RcCons(4, Rc::new(RcNil)), ))); { // Rc::clone全程参数对应的引用计数增加1 let _b = RcCons(1, Rc::clone(&a)); let _c = RcCons(2, Rc::clone(&a)); // 目前有a,_b,_c三个变量引用a,所以a的引用计数为3 // 除了strong_count,还有week_count,用于避免循环引用 println!("{}", Rc::strong_count(&a)) } // _b,_c离开作用域,减少了引用计数,但a还在,所以这块的数量是1 println!("{}", Rc::strong_count(&a)) } ``` ### `RefCell<T>`和内部可变性模式 内部可变性是Rust的设计模式之一,它允许你在只持有不可变引用的情况下修改数据。这在现有的借用规则下是禁止的,所以此类数据结构借用了unsafe代码来绕过可变性和借用规则的限制。 `RefCell<T>`是使用了内部可变性模式的类型。 与`Rc<T>`不同,`RefCell<T>`持有数据的维一所有权。而与`Box<T>`不同,`RefCell<T>`会在运行时检查借用规则,而非在编译时期,如果运行时发现不满足规则 ,则直接panic。所以`RefCell<T>`类型由开发者来保证借用规则 ,则不是编译器。 此类型只能用于单线程中。 `Box<T>`,`Rc<T>`,`RefCell<T>`三者的区别: 1. `Rc<T>`允许一份数据有多个所有者,而`Box<T>`和R`efCell<T>`都只有一个所有者; 2. `Box<T>`允许在编译时检查的可变或不可变借用,`Rc<T>`仅允许编译时检查的不可变借用,`RefCell<T>`允许运行时检查的可变或不可变借用; 3. 由于`RefCell<T>`允许我们在运行时检查可变借用,所以即便`RefCell<T>`本身是不可变的,我们仍然能够更改其中存储的值。 ```rust { // 假设有一个消息trait,需要实现send方法,而这一方法传递self的不可变引用 pub trait Messenger { fn send(&self, msg: &str); } // 但是在测试的时候,我们使用Mock类来模拟Messenger的send的时候,需要把消息存储下来 // 这样就可以验证存下来的消息是否符合预期,但传入不可变的self阻止了这种做法 // 此时就需要使用RefCell来实现 struct Mock { message: RefCell<Vec<String>>, } impl Mock{ fn new()->Mock{ Mock{ // 使用RefCell::new来创建新的RefCell message:RefCell::new(vec![]) } } } impl Messenger for Mock { fn send(&self, msg: &str) { // 如果这里的self.message是普通的Vec<String>,则无法执行push方法 // 而使用RefCell的borrow_mut来绕过此限制,得到可变引用 self.message.borrow_mut().push(String::from(msg)) } } let m = Mock::new(); m.send("message1"); m.send("message2"); // ["message1", "message2"] println!("{:?}", m.message.borrow()); // 以下两行可以通过编译,但在运行时报错:thread 'main' panicked at 'already borrowed: BorrowMutError' // 这是因为a是不可变引用,在已经持有不可变引用的情况下,又搞出了一个可变的引用,破坏了借用规则 ,所以panic // let a = m.message.borrow(); // let mut b = m.message.borrow_mut(); } ``` 结合使用`Rc<T>`和`RefCell<T>`来实现某个数据有多个所有者,并且都可以对数据进行修改。 ```rust { #[derive(Debug)] enum RcRefCellList { RcRefCellCons(Rc<RefCell<i32>>, Rc<RcRefCellList>), RcRefCellNil, } use RcRefCellList::*; let val = Rc::new(RefCell::new(5)); let a = Rc::new(RcRefCellCons(Rc::clone(&val), Rc::new(RcRefCellNil))); let b = RcRefCellCons(Rc::new(RefCell::new(6)), Rc::clone(&a)); let c = RcRefCellCons(Rc::new(RefCell::new(6)), Rc::clone(&a)); // 这块改动将a,b和c以及val都修改了 *val.borrow_mut() = 10; // a:RcRefCellCons(RefCell { value: 10 }, RcRefCellNil) // b:RcRefCellCons(RefCell { value: 6 }, RcRefCellCons(RefCell { value: 10 }, RcRefCellNil)) // c:RcRefCellCons(RefCell { value: 6 }, RcRefCellCons(RefCell { value: 10 }, RcRefCellNil)) println!("a:{:?}", a); println!("b:{:?}", b); println!("c:{:?}", c); } ``` Rust不保证在编译器彻底防止内存泄露。我们可以创建出一个环状引用使得引用计数不会减到0,对应的值不会被丢弃,从而造成内存泄露。 ```rust { // 创建出循环引用 // 定义一个链接,为了方便改动,这次的链接使用ReCell来处理 enum RefCellRcList { RefCellRcCons(i32, RefCell<Rc<RefCellRcList>>), RefCellRcNil, } use RefCellRcList::*; // 定义一个a,指向b // a -> 5 -> Nil let a = Rc::new( RefCellRcCons(5, RefCell::new(Rc::new(RefCellRcNil))), ); println!("reference count:a:{}", Rc::strong_count(&a)); // b -> 10 -> a let b = Rc::new( RefCellRcCons(10, RefCell::new(Rc::clone(&a))), ); println!("reference count:a:{}, b:{}", Rc::strong_count(&a), Rc::strong_count(&b)); // 将a -> b;最终变成a->b->10->a if let RefCellRcCons(i, r) = a.borrow() { *r.borrow_mut() = Rc::clone(&b); }; println!("reference count:a:{}, b:{}", Rc::strong_count(&a), Rc::strong_count(&b)); // reference count:a:1 // reference count:a:2, b:1 // reference count:a:2, b:2 // 此时a和b的引用计数都是2,在结束时,先释放b,将b的引用计数减1,但此时b已经无法将引用计数减成0了,所以无法释放 } ``` 可以合理使用弱引用`Weak<T>`来规避这个问题,Rust在回收内存时不需要强制弱引用减成0。 与Rc::clone()类似,使用Rc::downgrade()获取`Rc<T>`的弱引用,获取对应弱引用的值时,使用对应弱引用的upgrade()方法,注意这个方法可能返回None。 ```rust { // 使用Weak<T>创建树结构,子节点指向父节点使用弱引用 #[derive(Debug)] struct Node { val: i32, // 多个子节点使用Vec来保存子节点的强引用,RefCell方便修改对应的值 children: RefCell<Vec<Rc<Node>>>, // 父节点点使用弱引用 parent: RefCell<Weak<Node>>, } let leaf = Rc::new(Node { val: 10, children: RefCell::new(vec![]), // Weak::new()创建出一个空的弱引用 parent: RefCell::new(Weak::new()), }); // 弱引用获取时,由于不确定值是否回收,所以使用upgrade()时会返回Option<T>,如果已经回收或者没有值,返回None // 以下返回None println!("{:?}", leaf.parent.borrow().upgrade()); let branch = Rc::new(Node { val: 5, children: RefCell::new(vec![Rc::clone(&leaf)]), parent: RefCell::new(Weak::new()), }); *(leaf.parent.borrow_mut()) = Rc::downgrade(&branch); println!("leaf's parent:{:?}", leaf.parent.borrow().upgrade()); println!("branch's parent:{:?}", branch.parent.borrow().upgrade()); { // 在另外一个作用域中添加branch的parent let new_branch = Rc::new(Node { val: 6, children: RefCell::new(vec![Rc::clone(&branch)]), parent: RefCell::new(Weak::new()), }); *branch.parent.borrow_mut() = Rc::downgrade(&new_branch); println!("branch's parent in new area:{:?}", branch.parent.borrow().upgrade()); } // 由于new_branch离开了作用域,所以被销毁,这块拿到的是None println!("branch's parent out area:{:?}", branch.parent.borrow().upgrade()); } ``` ## 线程 使用std::thread::spawn()向参数中传入一个闭包函数来支持多线程运行。 spawn返回线程句柄,其join方法会阻塞等待线程执行完成。 在闭包中使用move关键字可使得闭包函数获取变量的所有权。 此章节例子位于example/src/bin/thread.rs中: ```rust let v = vec![1,2,3]; // 使用thread::spawn启动一个线程,rust原生不支持协程,但有其它库提供支持 // spawn的参数是一个无参数闭包或者函数,会在另外一个线程中运行这个函数的代码 // 返回一个Handler,可以调用其join函数等待线程执行完成 // 如果在闭包中使用环境中的值,需要将其所有权move到新线程中 // 否则报错closure may outlive the current function, but it borrows `v`, which is owned by the current function let t = std::thread::spawn(move || { for i in 1..10 { println!("in thread {}", i + v[0]); std::thread::sleep(std::time::Duration::from_millis(1)); } }); for i in 1..5 { println!("out thread {}", i); std::thread::sleep(std::time::Duration::from_millis(1)); } // 由于v的所有权已经被移入新线程了,所以这里就无法再使用v了 // println!("v:{:?}", v); // 使用JoinHandler的join方法来等待线程执行完成 // 返回的是Result<T, E>类型 t.join().unwrap() ``` ### 使用通道来传递消息 使用std::sync::mpsc::channel()创建一个通道,获得一个发送端和一个接收端。 发送端可以使用send来发送消息,接收端使用recv和try_recv来阻塞(非阻塞)地接收消息。 接收端还可以被当成有迭代器来处理接收到的消息。 使用std::sync::mpsc::Sender::clone()方法可以复制发送端,从而由多个发送源发送消息。 ```rust // 使用通道(channel)在线程中传递信息 // mpsc是multiple producer,single consumer的缩写,顾名思义,只能有一个消费者,但可以多个发送方 let (tx, rx) = std::sync::mpsc::channel(); std::thread::spawn(move || { let hi = "hi".to_string(); tx.send(hi).unwrap(); // send会将取得没有实现Copy trait的所有权,所以以下语句将报错 // println!("send {}", hi); }); // recv会阻塞线程,直到收到消息 // 可以使用try_recv来非阻塞地试探是否有消息可以接收,没有消息时将返回Err println!("{}", rx.recv().unwrap()); let (tx, rx) = std::sync::mpsc::channel(); // mpsc支持多个发送方,可以通过clone方法来创建出多个发送端来 let tx_2 = std::sync::mpsc::Sender::clone(&tx); std::thread::spawn(move || { for _i in 1..5 { tx.send("hi".to_string()); std::thread::sleep(std::time::Duration::from_millis(100)) } }); std::thread::spawn(move || { for _i in 1..10 { tx_2.send("there".to_string()); std::thread::sleep(std::time::Duration::from_millis(100)) } }); // 将rx当成迭代器来遍历收到的数据 // 由于tx在线程退出时执行了Drop,整个通道就关闭了,所以rx的迭代就会结束了 for m in rx { println!("got:{}", m) } ``` ### 使用共享状态来实现消息传递 使用通道类似于单一所有权,使用共享状态类似于多重所有权。 并发原语(互斥体/mutex)一次只允许一个线程访问数据: 1. 必须在使用数据前尝试获取锁; 2. 必须在使用完互斥体守护的数据后释放锁,这样其他线程才能继续完成获取锁的操作。 使用std::sync::Mutex::new(T)创建一个互斥量,保存着一个T值。 lock返回一个智能指针,在离开作用域时自动解锁。 ```rust // mutex的使用 // 使用new函数创建互斥量,存储一个i32的值 let m = std::sync::Mutex::new(10); { // 使用lock返回一个Result,正常时为MutexGuard是一个智能指针 let mut i = m.lock().unwrap(); // 修改值为20 *i = 20; // 在这个作用域的结尾,智能指针执行了drop方法,将m解锁了 } // m现在的值为20了 // Mutex { data: 20, poisoned: false, .. } println!("{:?}", m); ``` 在并发场景需要使用Mutex,需要配合引用计数智能指针使用。 `Rc<T>`无法用于并发场景,需要使用`Arc<T>`类型,并发场景下的引用计数智能指针。 多线程模式下两个重要的trait:Sync和Send。Sync和Send这两个trait是内嵌于语言实现的。 Send trait表示可以在线程间安全地转移所有权,Sync trait表示此类型可以安全地被多个线程引用。 除了裸指针外,所有基础类型都实现了Send trait,任何有Send类型组成的复合类型也都实现了Send;如果类型T是Send类型,则&T满足Sync约束。 Send和Sync属于标签trait(marker trait),没有可供实现的方法,手动实现需要使用不安全的语言特性。 自动实现了Send和Sync的语法特性称之为自动trait(auto trait),与此相对,如果不想使某个类型自动实现trait,则可以使用negative impl语法来处理,例如: ```rust impl<T: ?Sized> !Send for MutexGuard<'_, T> {} ``` `Rc<T>`无法在多个线程场景下安全地更新引用计数值,所以Rc只设计用于单线程的场景,没有实现Send trait和Sync trait。 ```rust // 并发场景下使用mutex use std::sync::{Mutex, Arc}; use std::thread; // Arc<T>是并发场景下的Rc<T> // 使用Rc<T>会报错:`Rc<Mutex<i32>>` cannot be sent between threads safely // the trait `Send` is not implemented for `Rc<Mutex<i32>>` let counter = Arc::new(Mutex::new(0)); // let countet1 = Rc::new(Mutex::new(0)); let mut handlers = vec![]; for i in 0..30 { let c = counter.clone(); // let c2 = countet1.clone(); let h = thread::spawn(move || { let mut t = c.lock().unwrap(); // c2.lock().unwrap(); *t += 1; }); handlers.push(h); } for h in handlers { h.join().unwrap(); } println!("{:?}", counter) ``` ## 面向对象的语言特性 对象包含数据和行为:Rust中提供了struct和enum,可以使用impl来对这些数据实现操作方法; 封装细节:Rust提供了数据字段的公私有性;对于私有的属性,外部只能通过封装好的方法进行访问;另外只要公共的对外接口不变,内部的实现细节变动不影响外部使用方; 继承:Rust没有继承,但使用继承所能达到的目的,Rust可以通过其它方式来实现: > 代码复用:通过trait的默认实现可以共享代码;<br/> > 多态:如下,通过```Box<dyn Trait>```来实现。 ### 实现多态 使用```Box<dyn Trait>```可以实现多态的能力: ```rust // 定义一个含有draw方法的trait trait Draw{ fn draw(&self); } // 以下两个类型,都实现了Draw struct Button(); impl Draw for Button{ fn draw(&self) { println!("drawing Button") } } struct TextField(); impl Draw for TextField{ fn draw(&self) { println!("drawing TextField") } } // 使用vec来保存实现了Draw trait的变量 // Box<dyn Draw>表示实现了Draw trait的对象 // 与泛型不同,这种方式使得在component里可以存储任意多种类型,只要实现了Draw即可 let mut components:Vec<Box<dyn Draw>> = Vec::new(); // 可以将实现了Draw的类型push进components components.push(Box::new(Button{})); components.push(Box::new(TextField{})); // 并且可以遍历调用draw方法,而不需要关心存储的具体类型是什么 for c in components{ c.draw(); } ``` 泛型中使用的trait约束,会在编译期间展开成具体的类型,称之为静态派发。 而在使用trait对象时,编译期无法确定使用哪种具体类型,需要生成一些额外代码在运行期间查找应该调用的方法,这些称之为动态派发。 动态派发会产生一些运行时开销,例如对于trait对象来说,Rust会根据对象内部的指针来确定调用哪个方法,而动态派发还会阻止编译器内联代码,使得一些优化操作无法进行。但也带来了灵活性,需要根据具体场景确定使用哪种方式。 ### 对象安全 只有满足对象安全的trait才能转成trait对象;如果一个trait中定义的所有方法满足以下两条规则,则它就是对象安全的: 1. 方法中不能返回Self类型。Self方法是当前实现此trait的类型别名,如果trait返回了Self,则rust无法确定具体会返回什么类型。例如Clone trait。 2. 方法中不包含任何泛型参数。泛型参数会被展开成具体的类型,这些具体类型会被视作当前类型的一部分。由于trait对象忘记了类型信息,所以我们无法确定被填入泛型参数处的类型究竟是哪一个。 如果使用了类型不安全的trait,会在编译时出错: ```rust // 不满足对象安全的trait不能转化为trait对象 // `Clone` cannot be made into an object // note: the trait cannot be made into an object because it requires `Self: Sized` // note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; // let wrong:Vec<Box<dyn Clone>> = vec![]; ``` 使用Rust实现状态模式的例子: ```rust // 实现状态模式 // Post表示发布文章的流程,从草稿到审核再到发布 fn main() { let mut post = Post::new(); post.add_text("I'm greate"); println!("after add_text:{}", post.content()); post.request_review(); println!("after request_review:{}", post.content()); post.approve(); println!("after approve:{}", post.content()); } struct Post { // 状态机:草稿->审核->发布 // 为什么要用Option呢?如果不用Option在处理所有权的时候会比较麻烦,在所有权处理的时候需要注意 state: Option<Box<dyn State>>, content: String, } impl Post { fn new() -> Post { Post { // 默认是草稿的状态 state: Some(Box::new(Draft {})), content: String::new(), } } fn add_text(&mut self, text: &str) { self.content.push_str(text) } fn request_review(&mut self){ // 将这些操作都代理给state,这些处理会导致新的状态,替换原来旧的状态 // Option::take()获取变量的所有权,在这里把state的所有权取出,因为马上就要使用新的state来替换进去了 if let Some(s) = self.state.take(){ self.state = Some(s.request_review()) } } fn approve(&mut self){ if let Some(s) = self.state.take(){ self.state = Some(s.approve()) } } fn content(&self)-> &str{ self.state.as_ref().unwrap().content(self) } } trait State { fn request_review(self: Box<Self>) -> Box<dyn State>; fn approve(self: Box<Self>) -> Box<dyn State>; fn content<'a>(&self, post:&'a Post)->&'a str{ "" } } struct Draft {} impl State for Draft { fn request_review(self: Box<Self>) -> Box<dyn State> { Box::new(PendingReview{}) } fn approve(self: Box<Self>) -> Box<dyn State> { self } } struct PendingReview {} impl State for PendingReview { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { Box::new(Publish{}) } } struct Publish {} impl State for Publish { fn request_review(self: Box<Self>) -> Box<dyn State> { self } fn approve(self: Box<Self>) -> Box<dyn State> { self } fn content<'a>(&self, post:&'a Post)->&'a str{ &post.content } } ``` ## 匹配模式 模式匹配分成可失败匹配(refutable)和不可失败匹配(irrefutable): * 不可失败匹配是指可以匹配任何输入值的场景,例如let x = 5; * 可失败是指有可能出现某些值不匹配导致匹配失败的,例如let Some(x) = a; 如果a为None时,这个匹配就不成功了。 for、let、函数参数只接收不可失败的匹配,如果下代码将报错: ```rust // let只接收不可失败的匹配,所以下将编译报错 // refutable pattern in local binding: `None` not covered // `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant // let Some(x) = v.iter().next(); ``` 使用匹配模式的场景 | 模式匹配场景 | 可失败or不可失败 | | ------------- |:-------------| :----------| |match |除了最后一个模式,其它模式是可失败的模式,最后一个可以是可失败的也可以是不可失败的| |if let | 可失败,如果使用不可失败将收到warning| |while let |可失败,如果使用不可失败将收到warning| |for |不可失败, 这里的不可失败是指Some里面的值,而不包含Some匹配| |let | 不可失败| |函数参数 |不可失败| 匹配的类型 | 模式匹配场景 | 举例 | | ------------- |:-------------| |字面量匹配| match m{<br/>1 => {}<br>...| |变量名匹配| match m{<br/>x => {x}<br>...| |使用\|的多重模式| match m{<br/>1\|2 => {}<br>...| |使用..=来匹配区间,注意...已经不推荐使用| match m{<br/>1..=2 => {}<br>...| | 解构结构体匹配| if let Point { x, y } = p | | 解构枚举匹配| if let Some(c) = favorite_color { | | 解构嵌套的枚举和结构体匹配| let ((feat, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 });| | 解析结构体和元组匹配| let ((feat, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); | |忽略模式匹配中的某些值| let (x, _, z) = (1, 2, 3); | |使用..来忽略值的剩余部分| let (_first, .., _last) = (1, 2, 3, 4, 5, 6, 7, 8, 9); | |使用匹配守卫(match guard)添加额外条件| match c {<br/> Some(x) if x > 6 => {}<br/>...| |@绑定| if let Some(i @ 1..=5) = c { | 以下例子位于example/src/bin/pattern.rs中: ```rust // match匹配模式 // 必须穷尽所有的可能性;为了满足这一条件,可以使用两种方式 // 1. 最后一个分支使用全匹配模式,可以使用一个变量名来处理 // 2. 使用下划线这一特殊的模式来匹配所有值 let m = 5; match m { // 字面量匹配 1 => println!("is 1"), // 变量名匹配 x => println!("is not 1, is {}", x) } match m { // 匹配区间值 // 在老的版本中1..=5的语法也写作1...5,但最新的rust 2021只能使用1..=5,表示1~5包含1和5 // 也可以使用|来表示,等价于1|2|3|4|5,但写起来更简单,字符类型也可以使用,例如'a'..='k' 1..=5 => println!("between 1~5"), _ => println!("others") } // if let条件表达式 // if let表达式只匹配match中的一种情况 // 可以与if, else if, else, else if let等混合使用,以下是一个例子 let favorite_color: Option<&str> = None; let is_friday = false; let age: Result<u8, _> = "34".parse(); if let Some(c) = favorite_color { println!("using your favorite color: {}", c); } else if is_friday { println!("using friday color: red"); } else if let Ok(a) = age { println!("your age {} colour: blue", a); } else { println!("default color: black"); } // while let 条件循环 // 与if let类似,当匹配不上时,结束循环 let v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9]; let mut i = v.iter(); while let Some(elem) = i.next() { // 123456789 print!("{}", elem) } println!(); let mut i = v.iter(); // 任何能用于match的分支都能用于其它的匹配模式 while let Some(1..=5) = i.next() { // aaaaa print!("a") } println!(); // for循环 // for循环自动把Some给解构了,并且自动调用了迭代器的next函数 for (i, v) in v.iter().enumerate() { print!("({},{})", i, v); } println!(); // 以上与以下等价 let mut it = v.iter().enumerate(); while let Some((i, v)) = it.next() { print!("({},{})", i, v); } println!(); // let语句 // 我们日常使用的let语句也是使用了模式匹配 let (x, y, z) = (1, 2, 3); println!("x:{}, y:{}, z{}", x, y, z); // 函数参数也使用了模式匹配 // 如下例子的函数参数类似于let &(x,y) = &p fn print_point(&(x, y): &(i32, i32)) { println!("point({},{})", x, y); } let p = (3, 4); print_point(&p); // point(3,4) // 可失败模式匹配和不可失败模式匹配 // let, for, 函数参数必须是不可失败的模式匹配,在不可失败的模式匹配中使用可失败的模式,将发生编译报错 // let只接收不可失败的匹配,所以下将编译报错 // refutable pattern in local binding: `None` not covered // `let` bindings require an "irrefutable pattern", like a `struct` or an `enum` with only one variant // let Some(x) = v.iter().next(); // 在接收可失败的模式中使用不可失败模式,将收到编译器警告 // irrefutable `if let` pattern // this pattern will always match, so the `if let` is useless if let x = 5 { println!("no meaning:{}", x) } let p = Point { x: 10, y: 10 }; if let Point { x, y } = p { println!("pppp({}, {})", x, y); } // 使用解构来分解值 // 可以使用模式来分解结构体、枚举、元组、引用 // 解构结构体 struct Point { x: i32, y: i32, } let p = Point { x: 10, y: 2 }; // 指定字段值赋于的变量名a和b let Point { x: a, y: b } = p; println!("a:{}, b:{}", a, b); // a:10, b:2 // 如果字段名与变量名一致时,可以简写成如下 let Point { x, y } = p; println!("x:{}, x:{}", x, y); // x:10, x:2 // 也可以使用match让某个字段指定某个值来匹配 match p { Point { x: 0, y } => { println!("point at y axial, y:{}", y) } Point { x, y: 0 } => { println!("point at x axial, x:{}", x) } Point { x, y } => { println!("point at space:({}, {})", x, y) } } // 解构枚举之前看到的Option已经使用过多次了 // 这里看一下解构嵌套的结构体和枚举 let p = Some(Point { x: 10, y: 20 }); if let Some(Point { x, y }) = p { println!("x:{}, x:{}", x, y); // x:10, x:20 } // 解析结构体和元组 let ((feat, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); println!("{},{},{},{}", feat, inches, x, y); // 3,10,3,-10 // 使用_来忽略某些值 // 忽略第一个参数 fn foo(_: i32, y: i32) { println!("{}", y); } // 忽略元组中的第二个元素 let (x, _, z) = (1, 2, 3); println!("x:{}, z:{}", x, z); // 使用下划线开头的变量来防止编译器未使用的报警 // 以下如果不使用_,则会有警告:unused variable: `x` // 注意,你还是可以使用下划线开头的变量的 println!("{}", _x); let _x = 10; // 下划线开头的变量依然会绑定值,这与纯下划线忽略值不一样 let s = Some("hello".to_string()); // 这里的_如果替换成_k,则最后打印s将报错,因为此时s中的值的所有权已经移到_k中了 // 而_不会绑定值,所以还可以使用s if let Some(_) = s {} println!("{:?}", s); // 使用..来忽略值的值的剩余部分 // 只匹配x的值,忽略剩下部分的字段 let Point { x: _x, .. } = Point { x: 10, y: 10 }; // 匹配第一个和最后一个,分别是1和9 let (_first, .., _last) = (1, 2, 3, 4, 5, 6, 7, 8, 9); // 如果编译器无法确认匹配,即..产生歧义的匹配时,将报错 // can only be used once per tuple pattern // let (.., middle, ..) = (1,2,3,4,5,6,7,8,9); // 使用匹配守卫额外添加条件 let c = Some(10); match c { // 在匹配分支后面添加if表达来额外限定匹配条件 Some(x) if x > 6 => {} Some(_) => {} None => {} } // 使用@绑定 // 用于像范围匹配这种条件的情况下,将匹配到的值赋值到变量 let c = Some(2); if let Some(i @ 1..=5) = c { println!("c is between 1~5:{}", i); } ``` ## 高级特性 ### 不安全rust 不安全超能力(unsafe superpower): 1. 解引用裸指针; 2. 调用不安全的函数或者方法; 3. 访问或者修改可变的静态变量; 4. 实现不安全的trait。 #### 裸指针 裸指针要么可变(\*mut T),要么不可变(\*const T),不可变意味着不能对解引用后的指针直接赋值 与引用和智能指针的区别: 1. 允许忽略借用规则,即可以同时拥有同一内存地址的可变和不可变指针,或者拥有多个同一内存地址的可变指针; 2. 不能保证自己总是指向了有效的内存地址; 3. 允许为空; 4. 没有实现任何自动清理机制。 优势: 1. 更好的性能; 2. 与其它语言、硬件交互的能力。 以下例子位于example/src/bin/unsafe.rs中: ```rust // 解引用裸指针 let mut num = 5; // 如果只是创建裸针针,并不需要unsafe关键字 // 使用as关键来转化类型,以下两个指针都是从有效引用创建的,所以是有效的 let r1 = &num as *const i32; let r2 = &mut num as *mut i32; // 从任意地址创建指针,这里的r3可能就不是一个可用的指针 let t = 0x423243242usize; let _r3 = t as *const i32; // 如果需要解引用裸指针,则要将代码包在unsafe里 unsafe { // 只有可变的裸指针才能赋值,不能对*r1进行赋值 // 其实以下如果不是裸指针,已经破坏了引用规则,同一个地址的可变和不可变引用,但在裸指针中不受此限制 *r2 = 10; println!("r1 val:{}", *r1); // r1 val:10 // 以下由于指到了不合法的内存地址,直接段错误: segmentation fault // println!("r3 val:{}", *_r3); } ``` 裸指针一个主要用途是与C代码接口进行交互。 不安全的方法与普通方法一样,只是在fn之前添加unsafe关键字,在不安全的函数中不需要使用unsafe关键字就可以使用不安全的特性。 ```rust // 使用不安全的函数 // 不安全的方法与普通方法一样,只是在fn之前添加unsafe关键字 // 在不安全的函数体内使用不安全特性就不需要包裹unsafe了 unsafe fn dangerous() {} // 不安全的方法需要包裹在unsafe中调用 unsafe { dangerous(); } ``` 使用不安全特性的函数不一定都是不安全的函数,可以基于不安全的代码创建一个安全的抽象,例如标准库中的split_at_mut方法: ```rust pub fn split_at_mut(&mut self, mid: usize) -> (&mut [T], &mut [T]) { assert!(mid <= self.len()); // SAFETY: `[ptr; mid]` and `[mid; len]` are inside `self`, which // fulfills the requirements of `from_raw_parts_mut`. unsafe { self.split_at_mut_unchecked(mid) } } ``` 这个函数无法仅仅使用安全的Rust来实现,因为返回的两个切片都是self的一部分,造成两个可变引用的存在。 我们尝试通过实现简化的版本来验证一下。 ```rust // 尝试实现自己的简化版本split_at_mut,使用了不安全特性 fn split_at_mut(v: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) { assert!(mid <= v.len()); // 仅仅使用安全的Rust,会报两个可变指针的错误,而我们能保证这两个可变指针其实指向的是切片非重合的两部分 // (&mut v[..mid], &mut v[mid..]) // 所以可以使用unsafe特性来实现 // 获取指向切片的可变裸指针 let p = v.as_mut_ptr(); unsafe { // 以下的from_raw_parts_mut函数是unsafe的,所以这块要包含在unsafe中 (core::slice::from_raw_parts_mut(p, mid), core::slice::from_raw_parts_mut(p.offset(mid as isize), v.len() - mid) ) } } let mut v = vec![1, 2, 3, 4, 5]; let (a, b) = split_at_mut(&mut v[..], 3); println!("{:?}, {:?}", a, b); ``` 使用extern关键字可以引入其它语言的函数,所有通过extern引入的函数都是不安全的,需要使用unsafe关键字。 ```rust extern "C"{ fn abs(input:i32)->i32; } unsafe { println!("{}", abs(-20)); } ``` #### 访问或者修改可变的静态变量 静态变量,也称为全局变量。 不可变的静态变量与常量类似,静态变量的值在内存中拥有固定的地址,使用它的值总是会访问到同样的数据。与之相反的是,常量则允许在任何被使用到的时候复制其数据。 静态变量还可以是可变的,但访问或者修改可变的静态变量,都是unsafe的操作。这是因为Rust无法保证全局变量的修改和访问是否有发生竞争。 ```rust // 可变静态变量 static mut COUNTER:u32 = 10; // 访问和修改可变静态变量需要使用unsafe特性 fn incr_counter(){ unsafe { COUNTER += 1; } } fn get_counter() -> u32{ unsafe { COUNTER } } fn main(){ incr_counter(); println!("{}", get_counter()); // 11 } ``` #### 使用不安全的trait 当trait中存在至少一个拥有编译器无法校验的不安全因素时,这个trait也需要声明为unsafe。 实现这个unsafe trait的impl需要添加unsafe声明。 ```rust // 不安全的trait unsafe trait Foo {} unsafe impl Foo for i32 {} // 在并发章节说明的Send和Sync这两个trait就是不安全的trait,要为某个不安全的类型实现trait,需要使用unsafe关键字 struct Point { x: i32, y: i32, } unsafe impl Send for Point {} unsafe impl Sync for Point {} ``` ### 高级trait #### 在trait定义中使用关联类型指定占位类型 例如Iterator trait,使用关联类型定义了Item,这个Item类型做为next的返回值。 实现Iterator的时候,需要将Item赋值到对应的类型,这样next就能返回此类型。 与泛型不同的是,如果Iterator是泛型,那么我们需要实现某个特定版本的泛型,例如实现`Iterator<i32>`这种泛型,调用的时候也要显示地指定对应的类型。 ```rust // 标准库中Iterator迭代器trait的声明,内有关联类型Item // next返回的类型是Option<Self::Item>类型,即返回Item指定的类型 pub trait Iterator { type Item; fn next(&mut self) -> Option<Self::Item>; } // 定义一个无限计数器,将关联类型指定成i32,返回一个Some(i32) struct Counter(i32); impl Iterator for Counter { type Item = i32; fn next(&mut self) -> Option<Self::Item> { self.0 += 1; Some(self.0) } } // 如果使用泛型来实现就显得很奇怪 pub trait Iterator2<T> { fn next(&mut self) -> Option<T>; } // 在指定实现泛型trait时,需要显示指定实现的版本是什么 // 如果有多个类型的实现,在调用的时候还要指定调用的是哪个版本的实现 // 而使用关联类型则可以保证只有一种实现 impl Iterator2<i32> for Counter { fn next(&mut self) -> Option<i32> { self.0 += 1; Some(self.0) } } ``` #### 默认泛型参数 即在实现泛型的trait时,不指定实现的类型,此时默认泛型参数发挥作用,实现的这个默认类型。 这个功能经常用于运算符重载,Rust提供了有限的运算符重载功能。 这个功能还能让在原来的实现上添加新的类型而不用修改原来的代码实现,只需要在这个新的泛型类型上添加默认值即可。 ```rust // 默认泛型参数 // 公共库中的Add trait实现加法运算符的重载,默认类型与被加数(Right-hand side)相同(Rhs = Self) pub trait Add<Rhs = Self> { type Output; fn add(self, rhs: Rhs) -> Self::Output; } #[derive(Debug, PartialEq)] struct Point(i32, i32); // 为Point实现了Add trait,没有指定泛型的类型,默认是Self,即Point类型 // 等价于impl std::ops::Add<Point> for Point impl std::ops::Add for Point { type Output = Point; fn add(self, rhs: Point) -> Self::Output { Point(self.0 + rhs.0, self.1 + rhs.1) } } assert_eq!(Point(1, 2) + Point(2, 3), Point(3, 5)); // 为非默认类型(i32)实现Add操作 impl std::ops::Add<i32> for Point { type Output = Point; fn add(self, rhs: i32) -> Self::Output { Point(self.0 + rhs, self.1 + rhs) } } assert_eq!(Point(1, 2) + 2, Point(3, 4)); ``` #### 完全限定语法 两个trait可以定义同名的方法,而且一个类型可以同时实现这两个trait,但当调用方法时,就有可能出现冲突,编译器报错。 此时可以使用完全限定语法来处理,例子如下: ```rust // 有两个同名函数的trait,以及同时实现这两个trait的类型在调用时发生的歧义调用 trait Pilot { fn fly(&self) { println!("Engine start!") } fn name(){ println!("Pilot") } } trait Wizard { fn fly(&self) { println!("Up!") } fn name(){ println!("Wizard") } } struct Human {} impl Pilot for Human {} impl Wizard for Human {} impl Human { fn fly(&self) { println!("Dreaming!") } fn name(){ println!("Human") } } // Human实现了Wizard的fly、Pilot的fly、以及自己也有fly方法 let h = Human {}; // 此时在调用fly时,会直接使用类型定义的方法 // 如果Human没有实现自己的fly,此时将出现编译错误:multiple `fly` found h.fly(); // Dreaming! // 可以使用全限定的语法来指定调用哪一个fly方法 Human::fly(&h); // Dreaming! Wizard::fly(&h); // Up! Pilot::fly(&h); //Engine start! // 对于没有self参数的函数冲突,原来的办法无能为力 // 以下报错:cannot infer type // note: cannot satisfy `_: Wizard` // Wizard::name(); // Human可以直接调用,输出Human的方法内容 Human::name(); // Human // trait不能直接调用其函数,需要使用以下的限定语法 <Human as Pilot>::name(); // Pilot <Human as Wizard>::name(); // Wizard ``` #### 超trait 当一个trait功能依赖于另外一个trait时,被依赖的这个trait称为当前trait的超trait(super trait)。 ```rust // 超trait,依赖于另外一个trait的trait trait Animal { fn class(&self){} } // 依赖于类型实现了Animal,因为需要调用其class方法 trait Cat:Animal{ fn miao(&self){ self.class() } } struct Persian{} // Persian必须实现了Animal,才能实现Cat impl Animal for Persian{} impl Cat for Persian{} ``` #### newtype模式 newtype模式是指将一个类型使用struct的元组模式封装一下成为一个新类型,这个类型只有一个字段,这种类型称之为瘦封闭(thin wrapper)。 在Rust中,这一模式不会导致运行时开销,编译器在在编译阶段优化掉。 可以使用这一模式绕过为类型实现trait的孤儿规则,即可以在trait、类型包之外的其它包中为类型实现trait。 但其实并没有真正地为类型实现了对应的trait,毕竟进行了封装,但可以使用Deref来实现与原来类型一样的效果。 ```rust // newtype模式 // 绕过孤儿规则,为Vec<String>实现Display trait struct Wrapper<'a>(Vec<&'a str>); impl<'a> std::fmt::Display for Wrapper<'a> { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "[{}]", self.0.join(",")) } } let w = Wrapper(vec!["i", "am", "supper", "man"]); println!("{}", w); // [i,am,supper,man] // 但是封装类型并没有实现所有Vec<&str>的能力,比如len函数,w.len()将报错,因为没有实现 // 此时可以使用Deref解引用trait以及自动解引用的性质来实现Wrapper与Vec<&str>更一致 impl<'a> std::ops::Deref for Wrapper<'a> { type Target = Vec<&'a str>; fn deref(&self) -> &Self::Target { &self.0 } } println!("len:{}", w.len()); ``` ### 高级类型 * newtype模式实现的类型,可以隐藏原始类型的一些实现,提供封装抽象能力。并且新的类型与原来的类型为两种不同的类型,编译器检查为这两种类型不能混用提供了检查。 * 而类型别名,则与newtype不同,他只是原类型的别名,两者等价可以混用,一般用于简化类型的书写,例如io库中的Result。 ```rust pub type Result<T> = result::Result<T, Error>; ``` * 永不返回的Never类型(!);一般用于在match中处理异常等情况,例如exit(),panic!等都是返回Never类型。 ```rust pub fn exit(code: i32) -> ! { crate::sys_common::rt::cleanup(); crate::sys::os::exit(code) } ``` ### 动态大小类型与Size trait str是动态大小类型,只能在运行时确认类型的大小。 我们无法创建动态大小类型的变量,也无法使用其作为函数参数,这种类型需要放在某种指针的后面,例如&str。 Rust提供了一个特殊的Size trait,编译时可确定大小的类型自动实现了Size trait,另外Rust为泛型类型隐式地添加了Size约束,也就是说泛型默认只能用于编译期可确定大小的类型。但可以显示地使用?Size来解除限制。 ```rust // 解除了Size的限制,并且参数需要使用&T,因为在编译期无法确定大小的类型,必须使用某种指针来引用。 fn generic<T:?Size> (t:&T){} ``` ### 高级函数与闭包 ```rust // 我们之前试过使用函数指针,闭包的Fn, FnMut, FnOnce这些trait来实现参数传递 // 除此之外,还可以返回函数类型和trait类型做为函数的返回值 // 以下函数,以函数指针做为返回值 fn return_fn() -> fn(i32) -> i32 { |x| x + 100 } let t = return_fn(); println!("{}", t(10)); // 110 // 以下函数,返回实现了Fn trait的函数指针或者是闭包 fn return_fn_trait() -> Box<dyn Fn(i32) -> i32> { Box::new(|x| x + 100 ) } let t= return_fn_trait(); println!("{}", t(10)); ``` ## server服务程序的例子 以下例子实现了线程池、优雅退出等特性,但比较粗糙。 ```rust // lib.rs use std::sync::{Arc, mpsc, Mutex}; use std::sync::mpsc::{Receiver, Sender}; use std::thread; // 封闭的线程运行环境 pub struct Worker { id: usize, // 为什么要用Option,因为drop的时候,需要获取到thread的所有权 // 使用take获取所有权之后,此处的值就是None了 thread: Option<thread::JoinHandle<()>>, } impl Worker { fn new(id: usize, receiver: Arc<Mutex<Receiver<Message>>>) -> Worker { // 每一个worker会起一个线程来接收对应的消息 let thread = thread::spawn(move || { loop { // receiver需要lock,这里在let语句结束之后,这个receive已经unlock了 // 因为如果MutexGuard不再使用,则将drop掉 let message = receiver.lock().unwrap().recv().unwrap(); // 换成以下两句,则这个l走到job完成后才释放unlock,不满足要求 // let l = receiver.lock().unwrap(); // let message = l.recv().unwrap(); match message { Message::Terminal => { break; } Message::NewJob(job) => { print!("{} is doing the job:", id); job(); } } } }); let thread = Some(thread); Worker { id, thread } } } // 一个任务即一个闭包函数,因为需要用于在不同的线程之间传递,所以需要实现Send pub type Job = Box<dyn FnOnce() + Send>; // 用于发送任务用的Message,有两种类型 // 一种是Terminal结束线程运行,另外一种是NewJob消息,即新的任务 pub enum Message { Terminal, NewJob(Job), } // 线程池,包含有发送Message用的sender,以及运行的Worker pub struct ThreadPool { sender: Sender<Message>, workers: Vec<Worker>, } impl ThreadPool { /// 创建一个指定线程数的线程池 /// /// # Panics /// /// `new`函数会在参数为0时panic pub fn new(s: usize) -> ThreadPool { assert!(s > 0); // 使用mpsc::channel来与给多个线程传递信息,但由于不能有多个消费者(即Receiver没有实现Sync) let (sender, receiver) = mpsc::channel(); // with_capacity可以用于预分配对应大小的动态数组,减少动态扩容 let mut workers = Vec::with_capacity(s); // receiver没有实现Sync,需要使用Mutex包裹起来实现Sync,另外需要在多个线程中使用,必须使用Arc引用计数 let receiver = Arc::new(Mutex::new(receiver)); for id in 0..s { // 每一个线程就是一个worker,保存于workers中 workers.push(Worker::new(id, receiver.clone())); } ThreadPool { sender, workers } } pub fn execute<T>(&self, f: T) where T: FnOnce() + Send + 'static { self.sender.send(Message::NewJob(Box::new(f))).unwrap(); } } impl Drop for ThreadPool { fn drop(&mut self) { for _ in &mut self.workers { println!("send terminal to workers"); self.sender.send(Message::Terminal).unwrap(); } for w in &mut self.workers { // 因为join需要获取所有权,所以这块使用了take if let Some(t) = w.thread.take() { t.join().unwrap(); println!("No. {} thread has terminal!", w.id); } } } } ``` ```rust // main.rs use std::io::{Read, Write}; use std::net::TcpListener; use std::sync::mpsc; use std::thread; use std::time::Duration; use signal_hook::consts::SIGINT; use signal_hook::iterator::Signals; use server::ThreadPool; fn main() { // 起一个线程数量为4的线程池 let thread_pool = ThreadPool::new(2); // 起一个线程单独处理信号,收到信号时,需要将信息传递给accept来结束接收连接,所以这里加了一个channel // 信号处理使用signal_hook包来处理 let (terminal_sender, terminal_receiver) = mpsc::channel(); let sig = thread::spawn(move || { let mut signal = Signals::new(&[SIGINT]).unwrap(); for sig in signal.forever() { println!("rec sig:{}", sig); terminal_sender.send(()).unwrap(); break; } }); // 将listener放在单独的作用域里,这样当信号发出时,第一时间结束监听端口 // 这样新的连接就不会打进来了,但旧的请求还是能被正常处理 { // 使用TcpListener::bind让程序监听端口; // bind接收泛型参数,只要实现了ToSocketAddrs即可,例如String类型,不管是&str还是String都行 let listener = TcpListener::bind("localhost:8888".to_string()).unwrap(); // TcpListener的incoming返回迭代器,产生std::io::Result<TcpStream>类型 // 也可以使用accept函数,将其放在loop中,其返回Result<(TcpStream, SocketAddr)>类型 for stream in listener.incoming() { // 1. 最原始每一个请求阻塞处理 // handler_connection(stream.unwrap()); // 2. 每一个请求都启动一个线程来执行,但这样很快就会耗尽机器资源,容易被ddos攻击 // thread::spawn(move || { // handler_connection(stream.unwrap()); // }); // 3. 使用线程池来处理只保留有限的线程数来处理 thread_pool.execute(move || { handler_connection(stream.unwrap()); }); // 由于把这个接收函数放在了接收任务时,所以这块有一个限制就是如果没有请求就无法运行到此处 // 暂时没有想到很好的办法来处理这个 if let Ok(_) = terminal_receiver.try_recv() { println!("get terminal sig!"); break; } } } sig.join().unwrap(); // 退出此作用域时,会调用thread_pool的drop函数来处理完请求 println!("main end!"); } // 处理每一个请求 fn handler_connection(mut stream: std::net::TcpStream) { let mut buffer = [0; 1000]; let len = stream.read(&mut buffer).unwrap(); let content = String::from_utf8_lossy(&buffer[0..10]); println!("receive a connection: remoteAddr {:?}, receive data len:{}, content:{:?}", stream.peer_addr().unwrap(), len, content); let index = b"GET / HTTP/1.1\r\n"; let sleep = b"GET /sleep HTTP/1.1\r\n"; if buffer.starts_with(index) { let response = "HTTP/1.1 200 OK\r\n\r\nOK"; stream.write(response.as_bytes()).unwrap(); } else if buffer.starts_with(sleep) { thread::sleep(Duration::from_secs(10)); stream.write(b"HTTP/1.1 200 OK\r\n\r\nsleep").unwrap(); } else { stream.write(b"HTTP/1.1 404 NOT FOUND\r\n\r\nnot found").unwrap(); } } ``` <style> center{ font-size: 0.7em; margin-top: -20px; margin-bottom: 15px; } table{ font-size:0.7em; margin-bottom: 29px; border: 2px solid #2b5fa8; } table th { background: #cef; padding: 5px; } .post ul { font-size: 0.75em; list-style-type: disc; padding-left: 16px; } td{ padding: 8px; } td.special-title{ color: #a30623; } table .field{ background-color:#cef } table .allowed{ background-color:#cfe } table .required{ background-color:#cfa } table .empty{ background-color:#fbb } .postn ul { font-size: 0.75em; list-style-type: disc; padding-left: 16px; margin-top:0px; } </style>
Java
<sup><sup>*Release notes were automatically generated by [Shipkit](http://shipkit.org/)*</sup></sup> #### 0.9.17 - 2020-05-31 - [17 commits](https://github.com/magx2/jSupla/compare/v0.9.14...v0.9.17) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.17-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.17) - [Enhancement] Deploy locally to OpenHAB [(#14)](https://github.com/magx2/jSupla/issues/14) #### 0.9.14 - 2019-03-18 - [2 commits](https://github.com/magx2/jSupla/compare/v0.9.13...v0.9.14) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.14-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.14) - No pull requests referenced in commit messages. #### 0.9.13 - 2019-03-18 - [2 commits](https://github.com/magx2/jSupla/compare/v0.9.12...v0.9.13) by [Martin](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.13-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.13) - [Bug] #13 Fix LGTM issue [(#13)](https://github.com/magx2/jSupla/pull/13) #### 0.9.12 - 2019-03-18 - no code changes (no commits) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.12-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.12) #### 0.9.11 - 2019-03-18 - [5 commits](https://github.com/magx2/jSupla/compare/v0.9.10...v0.9.11) by [Martin](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.11-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.11) - [Enhancement] Add LGTM badges [(#5)](https://github.com/magx2/jSupla/issues/5) - [Enhancement] Update protocol to ver. 10 [(#4)](https://github.com/magx2/jSupla/issues/4) - [Enhancement] Move long running tests to integration tests package [(#3)](https://github.com/magx2/jSupla/issues/3) - #3 move long running tests to integration tests package [(#10)](https://github.com/magx2/jSupla/pull/10) - #4 update to protocol ver 10 [(#9)](https://github.com/magx2/jSupla/pull/9) - #5 LGTM [(#8)](https://github.com/magx2/jSupla/pull/8) #### 0.9.10 - 2019-03-08 - [5 commits](https://github.com/magx2/jSupla/compare/v0.9.9...v0.9.10) by Martin Grzeslowski - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.10-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.10) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.9 - 2019-03-04 - [3 commits](https://github.com/magx2/jSupla/compare/v0.9.8...v0.9.9) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.9-green.svg)](https://bintray.com/big-boy/bigboy/jSupla/0.9.9) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.8 - 2019-03-04 - [1 commit](https://github.com/magx2/jSupla/compare/v0.9.7...v0.9.8) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.8-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.8) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.7 - 2019-03-04 - [1 commit](https://github.com/magx2/jSupla/compare/v0.9.6...v0.9.7) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.7-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.7) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.6 - 2019-03-04 - [2 commits](https://github.com/magx2/jSupla/compare/v0.9.5...v0.9.6) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.6-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.6) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.5 - 2019-02-20 - [1 commit](https://github.com/magx2/jSupla/compare/v0.9.4...v0.9.5) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.5-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.5) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.4 - 2019-02-20 - no code changes (no commits) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.4-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.4) #### 0.9.3 - 2019-02-20 - [1 commit](https://github.com/magx2/jSupla/compare/v0.9.2...v0.9.3) by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.3-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.3) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) #### 0.9.2 - 2019-02-19 - 865 commits by [Martin Grzeslowski](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.2-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.2) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) - Add shipkit #1 [(#2)](https://github.com/magx2/jSupla/pull/2) #### 0.9.1 - 2019-02-19 - 864 commits by [Martin](https://github.com/magx2) - published to [![Bintray](https://img.shields.io/badge/Bintray-0.9.1-green.svg)](https://bintray.com/big-boy/bigboy/maven/0.9.1) - [Enhancement] Add Shipkit [(#1)](https://github.com/magx2/jSupla/issues/1) - Add shipkit #1 [(#2)](https://github.com/magx2/jSupla/pull/2)
Java
import Ember from "ember"; export default Ember.Route.extend({ model: function() { return this.store.query('answer', {correct: true}); } });
Java
<?php /** * This file is part of the PHPMongo package. * * (c) Dmytro Sokil <dmytro.sokil@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Sokil\Mongo\Validator; /** * Alphanumeric values validator * * @author Dmytro Sokil <dmytro.sokil@gmail.com> */ class AlphaNumericValidator extends \Sokil\Mongo\Validator { public function validateField(\Sokil\Mongo\Document $document, $fieldName, array $params) { if (!$document->get($fieldName)) { return; } if (preg_match('/^\w+$/', $document->get($fieldName))) { return; } if (!isset($params['message'])) { $params['message'] = 'Field "' . $fieldName . '" not alpha-numeric in model ' . get_called_class(); } $document->addError($fieldName, $this->getName(), $params['message']); } }
Java
<?php /** * swPagesAdmin actions. * * @package soleoweb * @subpackage swPagesAdmin * @author Your name here * @version SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $ */ class baseSwBlogTagsAdminActions extends sfActions { public function executeIndex($request) { $this->sw_blog_tagList = new swBlogTagsDatagrid( $request->getParameter('filters', array()), array( 'page' => $request->getParameter('page'), 'per_page' => 10, ) ); } public function executeCreate() { $this->form = new swBlogTagForm(); $this->setTemplate('edit'); } public function executeEdit($request) { $this->form = $this->getswBlogTagForm($request->getParameter('id')); } public function executeUpdate($request) { $this->forward404Unless($request->isMethod('post')); $this->form = $this->getswBlogTagForm($request->getParameter('id')); $this->form->bind($request->getParameter('sw_blog_tag')); if ($this->form->isValid()) { $sw_blog_tag = $this->form->save(); $this->getUser()->setFlash('notice-ok', __('notice_your_change_has_been_saved', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/edit?id='.$sw_blog_tag['id']); } $this->getUser()->setFlash('notice-error', __('notice_an_error_occurred_while_saving', null, 'swToolbox')); $this->setTemplate('edit'); } public function executeDelete($request) { $this->forward404Unless($sw_blog_tag = $this->getswBlogTagById($request->getParameter('id'))); $sw_blog_tag->delete(); $this->getUser()->setFlash('notice-ok', __('notice_element_deleted', null, 'swToolbox')); $this->redirect('swBlogTagsAdmin/index'); } private function getswBlogTagTable() { return Doctrine::getTable('swBlogTag'); } private function getswBlogTagById($id) { return $this->getswBlogTagTable()->find($id); } private function getswBlogTagForm($id) { $sw_blog_tag = $this->getswBlogTagById($id); if ($sw_blog_tag instanceof swBlogTag) { return new swBlogTagForm($sw_blog_tag); } else { return new swBlogTagForm(); } } }
Java
#ifdef __OBJC__ #import <UIKit/UIKit.h> #else #ifndef FOUNDATION_EXPORT #if defined(__cplusplus) #define FOUNDATION_EXPORT extern "C" #else #define FOUNDATION_EXPORT extern #endif #endif #endif FOUNDATION_EXPORT double FlowCoreVersionNumber; FOUNDATION_EXPORT const unsigned char FlowCoreVersionString[];
Java
//This file is automatically rebuilt by the Cesium build process. /*global define*/ define(function() { 'use strict'; return "/**\n\ * Converts an RGB color to HSB (hue, saturation, brightness)\n\ * HSB <-> RGB conversion with minimal branching: {@link http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl}\n\ *\n\ * @name czm_RGBToHSB\n\ * @glslFunction\n\ * \n\ * @param {vec3} rgb The color in RGB.\n\ *\n\ * @returns {vec3} The color in HSB.\n\ *\n\ * @example\n\ * vec3 hsb = czm_RGBToHSB(rgb);\n\ * hsb.z *= 0.1;\n\ * rgb = czm_HSBToRGB(hsb);\n\ */\n\ \n\ const vec4 K_RGB2HSB = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);\n\ \n\ vec3 czm_RGBToHSB(vec3 rgb)\n\ {\n\ vec4 p = mix(vec4(rgb.bg, K_RGB2HSB.wz), vec4(rgb.gb, K_RGB2HSB.xy), step(rgb.b, rgb.g));\n\ vec4 q = mix(vec4(p.xyw, rgb.r), vec4(rgb.r, p.yzx), step(p.x, rgb.r));\n\ \n\ float d = q.x - min(q.w, q.y);\n\ return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + czm_epsilon7)), d / (q.x + czm_epsilon7), q.x);\n\ }\n\ "; });
Java
# Intro This is the documentation of [Weave.jl](http://github.com/mpastell/weave.jl). Weave is a scientific report generator/literate programming tool for Julia. It resembles [Pweave](http://mpastell.com/pweave) and, Knitr and Sweave. **Current features** * Noweb, markdown or script syntax for input documents. * Execute code as terminal or "script" chunks. * Capture Gadfly, PyPlot and Winston figures. * Supports LaTex, Pandoc, Github markdown, MultiMarkdown, Asciidoc and reStructuredText output * Publish markdown directly to html and pdf using Pandoc. * Simple caching of results ![Weave code and output](http://mpastell.com/images/weave_demo.png) ## Contents ```@contents ```
Java
/** * Demo App for TopcoatTouch */ $(document).ready(function() { <% if (kitchenSink) { if (mvc) { %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.createController('home'); tt.createController('about').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('info').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('help').addEvent('click', 'button', function() { tt.goBack(); }); tt.createController('buttonExample', { postrender: function($page) { // Show a message when anyone clicks on button of the test form... $page.find('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); } }); tt.createController('carouselExample', { postadd: function() { // When the page is loaded, run the following... // Setup iScroll.. this.carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }, pageend: function() { if (this.carouselScroll != null) { this.carouselScroll.destroy(); this.carouselScroll = null; } } }); tt.createController('checkRadioExample'); tt.createController('formExample'); tt.createController('galleryExample', { postrender: function($page) { $page.find('#changeButton').click(function() { createPlaceHolder($page, $('#gallery-picker').data('value')); }); createPlaceHolder($page, 'kittens'); } }); tt.createController('waitingDialogExample', { postadd: function() { // Show the loading message... $(document).on('click', '#showLoading', function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#topcoat-loading-message').text(count + ' seconds'); } },1000); }); // Show the dialog... $(document).on('click', '#showDialog', function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); } }); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder($page, type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $page.find('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } <% // End If MVC KitchenSink } else { // Start SingleDocument KitchenSink %> // Create the topcoatTouch object var tt = new TopcoatTouch({menu: [{id: 'help', name: 'Help'}, {id: 'info', name: 'Info'}, {id: 'about', name: 'About'}]}); // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... tt.goTo('home'); var carouselScroll = null; tt.on(tt.EVENTS.MENU_ITEM_CLICKED, function(page, id) { if (id == 'help') { tt.goTo('help', 'slidedown', true); } else if (id == 'info') { tt.goTo('info', 'flip', true); } else if (id == 'about') { tt.goTo('about', 'pop', true); } }); tt.on('click', 'button', 'help about info', function() { tt.goBack(); }); // Show the loading message... $('#showLoading').click(function() { tt.showLoading('10 seconds'); var count = 10; var interval = setInterval(function() { if (--count <= 0) { clearInterval(interval); tt.hideLoading(); } else { $('#topcoat-loading-message').text(count + ' seconds'); } },1000); }); // Show the dialog... $('#showDialog').click(function() { tt.showDialog('This is a dialog', 'Example Dialog', {OK: function() { console.log('OK Pressed') } , Cancel: function() { console.log('Cancel Pressed')}}); }); tt.on(tt.EVENTS.PAGE_START, 'carouselExample', function() { // When the page is loaded, run the following... // Setup iScroll.. carouselScroll = new IScroll('#carouselWrapper', { scrollX: true, scrollY: false, momentum: false, snap: true, snapSpeed: 400, keyBindings: true, indicators: { el: document.getElementById('carouselIndicator'), resize: false } }); }).on(tt.EVENTS.PAGE_END, 'carouselExample', function() { // When the page is unloaded, run the following... if (carouselScroll != null) { carouselScroll.destroy(); carouselScroll = null; } }); // Show a message when anyone clicks on button of the test form... $('.testForm').submit(function() { tt.showDialog('<h3>Button Clicked</h3>'); return false; }); function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } // Create the placeholders in the gallery... function createPlaceHolder(type) { var placeHolders = { kittens : 'placekitten.com', bears: 'placebear.com', lorem: 'lorempixel.com', bacon: 'baconmockup.com', murray: 'www.fillmurray.com'}; var gallery = ''; for (var i = 0; i < getRandomInt(50,100); i++) { gallery += '<li class="photoClass" style="background:url(http://' + placeHolders[type] + '/' + getRandomInt(200,300) + '/' + getRandomInt(200,300) + ') 50% 50% no-repeat"></li>'; } $('.photo-gallery').html(gallery); tt.refreshScroll(); // Refresh the scroller tt.scrollTo(0,0); // Move back to the top of the page... } $('#gallery-picker').change(function(e, id) { createPlaceHolder(id); }); createPlaceHolder('kittens'); <% } } else { %> // Create the topcoatTouch object var tt = new TopcoatTouch(); <% if (mvc) { %> tt.createController('home'); <% } else { %> // First page we go to home... This could be done in code by setting the class to 'page page-center', but here is how to do it in code... <% } %> tt.goTo('home'); <% } %> });
Java
use std::borrow::{Borrow, Cow}; use std::ffi::{CStr, CString}; use std::fmt; use std::mem; use std::ops; use std::os::raw::c_char; use std::ptr; const STRING_SIZE: usize = 512; /// This is a C String abstractions that presents a CStr like /// interface for interop purposes but tries to be little nicer /// by avoiding heap allocations if the string is within the /// generous bounds (512 bytes) of the statically sized buffer. /// Strings over this limit will be heap allocated, but the /// interface outside of this abstraction remains the same. pub enum CFixedString { Local { s: [c_char; STRING_SIZE], len: usize, }, Heap { s: CString, len: usize, }, } impl CFixedString { /// Creates an empty CFixedString, this is intended to be /// used with write! or the `fmt::Write` trait pub fn new() -> Self { unsafe { CFixedString::Local { s: mem::uninitialized(), len: 0, } } } pub fn from_str<S: AsRef<str>>(s: S) -> Self { Self::from(s.as_ref()) } pub fn as_ptr(&self) -> *const c_char { match *self { CFixedString::Local { ref s, .. } => s.as_ptr(), CFixedString::Heap { ref s, .. } => s.as_ptr(), } } /// Returns true if the string has been heap allocated pub fn is_allocated(&self) -> bool { match *self { CFixedString::Local { .. } => false, _ => true, } } /// Converts a `CFixedString` into a `Cow<str>`. /// /// This function will calculate the length of this string (which normally /// requires a linear amount of work to be done) and then return the /// resulting slice as a `Cow<str>`, replacing any invalid UTF-8 sequences /// with `U+FFFD REPLACEMENT CHARACTER`. If there are no invalid UTF-8 /// sequences, this will merely return a borrowed slice. pub fn to_string(&self) -> Cow<str> { String::from_utf8_lossy(&self.to_bytes()) } pub unsafe fn as_str(&self) -> &str { use std::slice; use std::str; match *self { CFixedString::Local { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } CFixedString::Heap { ref s, len } => { str::from_utf8_unchecked(slice::from_raw_parts(s.as_ptr() as *const u8, len)) } } } } impl<'a> From<&'a str> for CFixedString { fn from(s: &'a str) -> Self { use std::fmt::Write; let mut string = CFixedString::new(); string.write_str(s).unwrap(); string } } impl fmt::Write for CFixedString { fn write_str(&mut self, s: &str) -> Result<(), fmt::Error> { // use std::fmt::Write; unsafe { let cur_len = self.as_str().len(); match cur_len + s.len() { len if len <= STRING_SIZE - 1 => { match *self { CFixedString::Local { s: ref mut ls, len: ref mut lslen } => { let ptr = ls.as_mut_ptr() as *mut u8; ptr::copy(s.as_ptr(), ptr.offset(cur_len as isize), s.len()); *ptr.offset(len as isize) = 0; *lslen = len; } _ => unreachable!(), } } len => { let mut heapstring = String::with_capacity(len + 1); heapstring.write_str(self.as_str()).unwrap(); heapstring.write_str(s).unwrap(); *self = CFixedString::Heap { s: CString::new(heapstring).unwrap(), len: len, }; } } } // Yah....we should do error handling Ok(()) } } impl From<CFixedString> for String { fn from(s: CFixedString) -> Self { String::from_utf8_lossy(&s.to_bytes()).into_owned() } } impl ops::Deref for CFixedString { type Target = CStr; fn deref(&self) -> &CStr { use std::slice; match *self { CFixedString::Local { ref s, len } => unsafe { mem::transmute(slice::from_raw_parts(s.as_ptr(), len + 1)) }, CFixedString::Heap { ref s, .. } => s, } } } impl Borrow<CStr> for CFixedString { fn borrow(&self) -> &CStr { self } } impl AsRef<CStr> for CFixedString { fn as_ref(&self) -> &CStr { self } } impl Borrow<str> for CFixedString { fn borrow(&self) -> &str { unsafe { self.as_str() } } } impl AsRef<str> for CFixedString { fn as_ref(&self) -> &str { unsafe { self.as_str() } } } macro_rules! format_c { // This does not work on stable, to change the * to a + and // have this arm be used when there are no arguments :( // ($fmt:expr) => { // use std::fmt::Write; // let mut fixed = CFixedString::new(); // write!(&mut fixed, $fmt).unwrap(); // fixed // } ($fmt:expr, $($args:tt)*) => ({ use std::fmt::Write; let mut fixed = CFixedString::new(); write!(&mut fixed, $fmt, $($args)*).unwrap(); fixed }) } #[cfg(test)] mod tests { use super::*; use std::fmt::Write; fn gen_string(len: usize) -> String { let mut out = String::with_capacity(len); for _ in 0..len / 16 { out.write_str("zyxvutabcdef9876").unwrap(); } for i in 0..len % 16 { out.write_char((i as u8 + 'A' as u8) as char).unwrap(); } assert_eq!(out.len(), len); out } #[test] fn test_empty_handler() { let short_string = ""; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_1() { let short_string = "test_local"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_short_2() { let short_string = "test_local stoheusthsotheost"; let t = CFixedString::from_str(short_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), short_string); } #[test] fn test_511() { // this string (width 511) buffer should just fit let test_511_string = gen_string(511); let t = CFixedString::from_str(&test_511_string); assert!(!t.is_allocated()); assert_eq!(&t.to_string(), &test_511_string); } #[test] fn test_512() { // this string (width 512) buffer should not fit let test_512_string = gen_string(512); let t = CFixedString::from_str(&test_512_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_512_string); } #[test] fn test_513() { // this string (width 513) buffer should not fit let test_513_string = gen_string(513); let t = CFixedString::from_str(&test_513_string); assert!(t.is_allocated()); assert_eq!(&t.to_string(), &test_513_string); } #[test] fn test_to_owned() { let short = "this is an amazing string"; let t = CFixedString::from_str(short); assert!(!t.is_allocated()); assert_eq!(&String::from(t), short); let long = gen_string(1025); let t = CFixedString::from_str(&long); assert!(t.is_allocated()); assert_eq!(&String::from(t), &long); } #[test] fn test_short_format() { let mut fixed = CFixedString::new(); write!(&mut fixed, "one_{}", 1).unwrap(); write!(&mut fixed, "_two_{}", "two").unwrap(); write!(&mut fixed, "_three_{}-{}-{:.3}", 23, "some string data", 56.789) .unwrap(); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), "one_1_two_two_three_23-some string data-56.789"); } #[test] fn test_long_format() { let mut fixed = CFixedString::new(); let mut string = String::new(); for i in 1..30 { let genned = gen_string(i * i); write!(&mut fixed, "{}_{}", i, genned).unwrap(); write!(&mut string, "{}_{}", i, genned).unwrap(); } assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &string); } // TODO: Reenable this test once the empty match arm is allowed // by the compiler // #[test] // fn test_empty_fmt_macro() { // let empty = format_c!(""); // let no_args = format_c!("there are no format args"); // // assert!(!empty.is_allocated()); // assert_eq!(&empty.to_string(), ""); // // assert!(!no_args.is_allocated()); // assert_eq!(&no_args.to_string(), "there are no format args"); // } #[test] fn test_short_fmt_macro() { let first = 23; let second = "#@!*()&^%_-+={}[]|\\/?><,.:;~`"; let third = u32::max_value(); let fourth = gen_string(512 - 45); let fixed = format_c!("{}_{}_0x{:x}_{}", first, second, third, fourth); let heaped = format!("{}_{}_0x{:x}_{}", first, second, third, fourth); assert!(!fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } #[test] fn test_long_fmt_macro() { let first = ""; let second = gen_string(510); let third = 3; let fourth = gen_string(513 * 8); let fixed = format_c!("{}_{}{}{}", first, second, third, fourth); let heaped = format!("{}_{}{}{}", first, second, third, fourth); assert!(fixed.is_allocated()); assert_eq!(&fixed.to_string(), &heaped); } }
Java
const sizeOf = { object: function () { return function (object) { let $start = 0 $start += 1 * object.array.length + 2 return $start } } () } const serializer = { all: { object: function () { return function (object, $buffer, $start) { let $i = [] for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) { $buffer[$start++] = object.array[$i[0]] & 0xff } $buffer[$start++] = 0xd $buffer[$start++] = 0xa return { start: $start, serialize: null } } } () }, inc: { object: function () { return function (object, $step = 0, $i = []) { let $_, $bite return function $serialize ($buffer, $start, $end) { for (;;) { switch ($step) { case 0: $i[0] = 0 $step = 1 case 1: $bite = 0 $_ = object.array[$i[0]] case 2: while ($bite != -1) { if ($start == $end) { $step = 2 return { start: $start, serialize: $serialize } } $buffer[$start++] = $_ >>> $bite * 8 & 0xff $bite-- } if (++$i[0] != object.array.length) { $step = 1 continue } $step = 3 case 3: if ($start == $end) { $step = 3 return { start: $start, serialize: $serialize } } $buffer[$start++] = 0xd case 4: if ($start == $end) { $step = 4 return { start: $start, serialize: $serialize } } $buffer[$start++] = 0xa case 5: } break } return { start: $start, serialize: null } } } } () } } const parser = { all: { object: function () { return function ($buffer, $start) { let $i = [] let object = { array: [] } $i[0] = 0 for (;;) { if ( $buffer[$start] == 0xd && $buffer[$start + 1] == 0xa ) { $start += 2 break } object.array[$i[0]] = $buffer[$start++] $i[0]++ } return object } } () }, inc: { object: function () { return function (object, $step = 0, $i = []) { let $length = 0 return function $parse ($buffer, $start, $end) { for (;;) { switch ($step) { case 0: object = { array: [] } case 1: $i[0] = 0 case 2: $step = 2 if ($start == $end) { return { start: $start, object: null, parse: $parse } } if ($buffer[$start] != 0xd) { $step = 4 continue } $start++ $step = 3 case 3: $step = 3 if ($start == $end) { return { start: $start, object: null, parse: $parse } } if ($buffer[$start] != 0xa) { $step = 4 $parse(Buffer.from([ 0xd ]), 0, 1) continue } $start++ $step = 7 continue case 4: case 5: if ($start == $end) { $step = 5 return { start: $start, object: null, parse: $parse } } object.array[$i[0]] = $buffer[$start++] case 6: $i[0]++ $step = 2 continue case 7: } return { start: $start, object: object, parse: null } break } } } } () } } module.exports = { sizeOf: sizeOf, serializer: { all: serializer.all, inc: serializer.inc, bff: function ($incremental) { return { object: function () { return function (object) { return function ($buffer, $start, $end) { let $i = [] if ($end - $start < 2 + object.array.length * 1) { return $incremental.object(object, 0, $i)($buffer, $start, $end) } for ($i[0] = 0; $i[0] < object.array.length; $i[0]++) { $buffer[$start++] = object.array[$i[0]] & 0xff } $buffer[$start++] = 0xd $buffer[$start++] = 0xa return { start: $start, serialize: null } } } } () } } (serializer.inc) }, parser: { all: parser.all, inc: parser.inc, bff: function ($incremental) { return { object: function () { return function () { return function ($buffer, $start, $end) { let $i = [] let object = { array: [] } $i[0] = 0 for (;;) { if ($end - $start < 2) { return $incremental.object(object, 2, $i)($buffer, $start, $end) } if ( $buffer[$start] == 0xd && $buffer[$start + 1] == 0xa ) { $start += 2 break } if ($end - $start < 1) { return $incremental.object(object, 4, $i)($buffer, $start, $end) } object.array[$i[0]] = $buffer[$start++] $i[0]++ } return { start: $start, object: object, parse: null } } } () } } } (parser.inc) } }
Java
#body { width: auto; } /* Coding Table */ .table_stat { z-index: 2; position: relative; } .table_bar { height: 80%; position: absolute; background: #DEF; /* cornflowerblue */ z-index: -1; top: 10%; left: 0%; } #agreement_table, #tweet_table { font-size: 10pt; } #agreement_table small { opacity: 0.5; } .tweet_table_Text { width: 60%; } #agreement_table tr:nth-child(even){ background-color: #F7F7F7; } .matrix-table-div { text-align: center; display: inline-block; position: relative; } .ylabel { top: 50%; height: 100%; left: 0px; transform: translate(-100%, -50%); text-orientation: sideways; writing-mode: vertical-lr; position: absolute; } #lMatrices table { table-layout: fixed; width: inherit; } #lMatrices td { font-size: 12px; width: 23px; height: 23px; overflow: hidden; white-space: nowrap; text-align: center; border-right-style: dotted; border-bottom-style: dotted; border-top-style: none; border-left-style: none; border-width: 1px; } #lMatrices tr td:last-child { border-right-style: none; border-left-style: double; border-left-width: 3px; } #lMatrices table tr:first-child, #lMatrices tr td:first-child { font-weight: bold; } #codes_confusion_matrix td { width: 30px; height: 30px; } #codes_confusion_matrix tr:last-child td { border-bottom-style: none; border-top-style: double; border-top-width: 3px; } /* #matrices tr:hover { background: #EEE; }*/ .coding_header h2 { display: inline; margin-right: 30px; } .u_cell_plain { border-right-style: none !important; border-left-style: none !important; border-top-style: none !important; border-bottom-style: none !important; } .u_cell_pairwise { border-right-style: dotted !important; border-left-style: none !important; border-top-style: none !important; border-bottom-style: dotted !important; } .u_cell_coltotal { border-right-style: dotted !important; border-left-style: none !important; border-top-style: double !important; border-bottom-style: none !important; } .u_cell_rowtotal { border-right-style: none !important; border-left-style: double !important; border-top-style: none !important; border-bottom-style: dotted !important; } .u_cell_toolow { background-color: #ff9896 } .u_cell_toohigh { background-color: #aec7e8 } .u_cell_lt75 { background-color: #dbdb8d } .u_cell_gt90 { background-color: #98df8a } .u_cell_colorscale { padding: 0px 5px; margin: 0px 5px; }
Java
--- layout: post title: Mengerjakan Dapodik 2016 dalam Linux tags: [dapodik, virtualbox, linux] comments: true --- Hari ini Dapodik versi 2016 telah diluncurkan. Jika boleh berpendapat, mestinya Dapodik kembali menggunakan _Software as a service_ layaknya Dapodikdas generasi awal atau [Padamu Negeri](http://padamu.siap.web.id/). Sebagai pengguna GNU/Linux, rada ribed juga karena walaupun Dapodik menggunakan aplikasi _open source_ macam Apache, PHP dan postgre SQL, namun sulit dan hampir tidak mungkin untuk dijalankan dalam Linux. Dan sepertinya Dapodik versi 2016 ini memiliki ketergantungan terhadap dot NET, _well shit_... Entah mengapa saya tidak pernah merasa nyaman mengerjakan Dapodik secara langsung dalam VirtualBox, mungkin karena banyak melakukan _copy-paste_ antar dokumen atau memang sudah tidak terbiasa dengan lingkungan Windows. Mungkin ada cara lain, namun saya lebih memilih memasang aplikasi Dapodik dalam VirtualBox dengan Windows 7 sebagai _guest_ dan melakukan [_port forwarding_](https://en.wikipedia.org/wiki/Port_forwarding) ke _host_. Dengan demikian saya bisa mengerjakan Dapodik langsung melalui _guest_ dan atau melalui peramban di _host_. Untuk melakukan _port forwarding_ dari _guest_ (Windows 7) VirtualBox ke _host_ (Linux), ikuti langkah berikut; Pertama, kita harus tahu IP dari _guest_. Karenanya jalankan _guest_ dan jalankan perintah `ipconfig` dalam _command line_ di _guest_. [![ipconfig]({{ site.baseurl }}/assets/img/cmd-ipconfig.png)]({{ site.baseurl }}/assets/img/cmd-ipconfig.png) Dari gambar di atas kita dapat IP adalah `10.0.2.15`. Dapodikdas versi 2016 dijalankan dalam _localhost_ pada _port_ `5774` di _guest_. Untuk _host_ baiknya kita gunakan _port_ yang tidak digunakan, misalnya `8080`. Dicontohkan menggunakan `VBoxManage` untuk _port forwarding_ Dapodik di _virtual machine_ bernama Windows 7 dengan IP `10.0.2.15` dan _port_ `5774` ke _localhost_ dengan IP `127.0.0.1` dan _port_ `8080`. ```sh VBoxManage modifyvm "Windows 7" --natpf1 Dapodikdas,tcp,127.0.0.1,8080,10.0.2.15,5774 ``` _That’s it!_ Dalam hal ini _guest_ berfungsi sebagai _server_ dan _host_ sebagai _client_. Untuk mengerjakan Dapodik di _host_ mesti menjalankan _guest_ terlebih dahulu, baru kemudian membuka _browser_ di _host_ dan masukkan alamat `http://localhost:8080`. [![dapodik]({{ site.baseurl }}/assets/img/vbox-port-forward-dapodik.png)]({{ site.baseurl }}/assets/img/vbox-port-forward-dapodik.png) Meski bisa mengerjakan Dapodik secara simultan dalam _guest_ dan _host_, namun untuk sinkronisasi tetap harus melalui _guest_ (Windows 7).
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Submission 944</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> </head> <body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0"> <img src="gallery/submissions/944.jpg" height="400"> </body> </html>
Java
@charset "UTF-8"; /* グレー系 */ /* シアン系 */ /* マージン、パディング */ /* フォントサイズ */ /* 行の高さ */ /* グレー系 */ /* シアン系 */ /* マージン、パディング */ /* フォントサイズ */ /* 行の高さ */ /* line 6, /vagrant/app/assets/stylesheets/staff/container.css.scss */ div#wrapper div#container h1 { margin: 0; padding: 9px 6px; font-size: 16px; font-weight: normal; background-color: #1a3333; color: #eeeeee; } /* マージン、パディング */ /* フォントサイズ */ /* 行の高さ */ /* グレー系 */ /* シアン系 */ /* マージン、パディング */ /* フォントサイズ */ /* 行の高さ */ /* line 4, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ html, body { margin: 0; padding: 0; height: 100%; } /* line 9, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ div#wrapper { position: relative; box-sizing: border-box; min-height: 100%; margin: 0 auto; padding-bottom: 48px; background-color: #cccccc; } /* line 17, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ header { padding: 6px; background-color: #448888; color: #fafafa; } /* line 21, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ header span.logo-mark { font-weight: bold; } /* line 25, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ footer { bottom: 0; position: absolute; width: 100%; background-color: #666666; color: #fafafa; } /* line 31, /vagrant/app/assets/stylesheets/staff/layout.css.scss */ footer p { text-align: center; padding: 6px; margin: 0; } /* */ /* * This is a manifest file that'll be compiled into application.css, which will include all the files * listed below. * * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets, * or vendor/assets/stylesheets of plugins, if any, can be referenced here using a relative path. * * You're free to add application-wide styles to this file and they'll appear at the bottom of the * compiled file so the styles you add here take precedence over styles defined in any styles * defined in the other CSS/SCSS files in this directory. It is generally better to create a new * file per style scope. * */
Java
<?php namespace Fannan\MembersModule\Member; use Anomaly\Streams\Platform\Database\Seeder\Seeder; class MemberSeeder extends Seeder { /** * Run the seeder. */ public function run() { // } }
Java
<?php namespace InfinityGames\InfinityBundle\DependencyInjection; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\Config\FileLocator; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\Loader; /** * This is the class that loads and manages your bundle configuration * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html} */ class InfinityGamesInfinityExtension extends Extension { /** * {@inheritDoc} */ public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } }
Java
import modelExtend from 'dva-model-extend' import { create, remove, update } from '../services/user' import * as usersService from '../services/users' import { pageModel } from './common' import { config } from 'utils' const { query } = usersService const { prefix } = config export default modelExtend(pageModel, { namespace: 'user', state: { currentItem: {}, modalVisible: false, modalType: 'create', selectedRowKeys: [], isMotion: localStorage.getItem(`${prefix}userIsMotion`) === 'true', }, subscriptions: { setup ({ dispatch, history }) { history.listen(location => { if (location.pathname === '/user') { dispatch({ type: 'query', payload: location.query, }) } }) }, }, effects: { *query ({ payload = {} }, { call, put }) { const data = yield call(query, payload) if (data) { yield put({ type: 'querySuccess', payload: { list: data.data, pagination: { current: Number(payload.page) || 1, pageSize: Number(payload.pageSize) || 10, total: data.total, }, }, }) } }, *'delete' ({ payload }, { call, put, select }) { const data = yield call(remove, { id: payload }) const { selectedRowKeys } = yield select(_ => _.user) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: selectedRowKeys.filter(_ => _ !== payload) } }) yield put({ type: 'query' }) } else { throw data } }, *'multiDelete' ({ payload }, { call, put }) { const data = yield call(usersService.remove, payload) if (data.success) { yield put({ type: 'updateState', payload: { selectedRowKeys: [] } }) yield put({ type: 'query' }) } else { throw data } }, *create ({ payload }, { call, put }) { const data = yield call(create, payload) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, *update ({ payload }, { select, call, put }) { const id = yield select(({ user }) => user.currentItem.id) const newUser = { ...payload, id } const data = yield call(update, newUser) if (data.success) { yield put({ type: 'hideModal' }) yield put({ type: 'query' }) } else { throw data } }, }, reducers: { showModal (state, { payload }) { return { ...state, ...payload, modalVisible: true } }, hideModal (state) { return { ...state, modalVisible: false } }, switchIsMotion (state) { localStorage.setItem(`${prefix}userIsMotion`, !state.isMotion) return { ...state, isMotion: !state.isMotion } }, }, })
Java
#!/bin/bash cd "$(dirname "$BASH_SOURCE")" || { echo "Error getting script directory" >&2 exit 1 } ./hallo.command sudo launchctl load -w /System/Library/LaunchDaemons/com.apple.metadata.mds.plist
Java
<?php class C_admin extends CI_Controller { public function __construct() { parent::__construct(); if($this->session->userdata('level') != 'admin') { redirect('auth'); } } public function index() { $data['username'] = $this->session->userdata('username'); $this->load->view('dashboard_admin', $data); } public function activity() { $data['username'] = $this->session->userdata('username'); $this->load->view('activity_admin', $data); } public function mahasiswa() { $data['username'] = $this->session->userdata('username'); $this->load->view('mahasiswa_admin', $data); } public function logout() { $this->session->unset_userdata('username'); $this->session->unset_userdata('level'); $this->session->sess_destroy(); redirect('auth'); } } ?>
Java
var blueMarker = L.AwesomeMarkers.icon({ icon: 'record', prefix: 'glyphicon', markerColor: 'blue' }); var airportMarker = L.AwesomeMarkers.icon({ icon: 'plane', prefix: 'fa', markerColor: 'cadetblue' }); var cityMarker = L.AwesomeMarkers.icon({ icon: 'home', markerColor: 'red' }); var stationMarker = L.AwesomeMarkers.icon({ icon: 'train', prefix: 'fa', markerColor: 'cadetblue' });
Java
<?php namespace Phossa\Cache; interface CachePoolInterface { } class CachePool implements CachePoolInterface { } class TestMap { private $cache; public function __construct(CachePoolInterface $cache) { $this->cache = $cache; } public function getCache() { return $this->cache; } }
Java
/** * jspsych plugin for categorization trials with feedback and animated stimuli * Josh de Leeuw * * documentation: docs.jspsych.org **/ jsPsych.plugins["categorize-animation"] = (function() { var plugin = {}; jsPsych.pluginAPI.registerPreload('categorize-animation', 'stimuli', 'image'); plugin.info = { name: 'categorize-animation', description: '', parameters: { stimuli: { type: jsPsych.plugins.parameterType.IMAGE, pretty_name: 'Stimuli', default: undefined, description: 'Array of paths to image files.' }, key_answer: { type: jsPsych.plugins.parameterType.KEYCODE, pretty_name: 'Key answer', default: undefined, description: 'The key to indicate correct response' }, choices: { type: jsPsych.plugins.parameterType.KEYCODE, pretty_name: 'Choices', default: jsPsych.ALL_KEYS, array: true, description: 'The keys subject is allowed to press to respond to stimuli.' }, text_answer: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Text answer', default: null, description: 'Text to describe correct answer.' }, correct_text: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Correct text', default: 'Correct.', description: 'String to show when subject gives correct answer' }, incorrect_text: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Incorrect text', default: 'Wrong.', description: 'String to show when subject gives incorrect answer.' }, frame_time: { type: jsPsych.plugins.parameterType.INT, pretty_name: 'Frame time', default: 500, description: 'Duration to display each image.' }, sequence_reps: { type: jsPsych.plugins.parameterType.INT, pretty_name: 'Sequence repetitions', default: 1, description: 'How many times to display entire sequence.' }, allow_response_before_complete: { type: jsPsych.plugins.parameterType.BOOL, pretty_name: 'Allow response before complete', default: false, description: 'If true, subject can response before the animation sequence finishes' }, feedback_duration: { type: jsPsych.plugins.parameterType.INT, pretty_name: 'Feedback duration', default: 2000, description: 'How long to show feedback' }, prompt: { type: jsPsych.plugins.parameterType.STRING, pretty_name: 'Prompt', default: null, description: 'Any content here will be displayed below the stimulus.' }, render_on_canvas: { type: jsPsych.plugins.parameterType.BOOL, pretty_name: 'Render on canvas', default: true, description: 'If true, the images will be drawn onto a canvas element (prevents blank screen between consecutive images in some browsers).'+ 'If false, the image will be shown via an img element.' } } } plugin.trial = function(display_element, trial) { var animate_frame = -1; var reps = 0; var showAnimation = true; var responded = false; var timeoutSet = false; var correct; if (trial.render_on_canvas) { // first clear the display element (because the render_on_canvas method appends to display_element instead of overwriting it with .innerHTML) if (display_element.hasChildNodes()) { // can't loop through child list because the list will be modified by .removeChild() while (display_element.firstChild) { display_element.removeChild(display_element.firstChild); } } var canvas = document.createElement("canvas"); canvas.id = "jspsych-categorize-animation-stimulus"; canvas.style.margin = 0; canvas.style.padding = 0; display_element.insertBefore(canvas, null); var ctx = canvas.getContext("2d"); if (trial.prompt !== null) { var prompt_div = document.createElement("div"); prompt_div.id = "jspsych-categorize-animation-prompt"; prompt_div.style.visibility = "hidden"; prompt_div.innerHTML = trial.prompt; display_element.insertBefore(prompt_div, canvas.nextElementSibling); } var feedback_div = document.createElement("div"); display_element.insertBefore(feedback_div, display_element.nextElementSibling); } // show animation var animate_interval = setInterval(function() { if (!trial.render_on_canvas) { display_element.innerHTML = ''; // clear everything } animate_frame++; if (animate_frame == trial.stimuli.length) { animate_frame = 0; reps++; // check if reps complete // if (trial.sequence_reps != -1 && reps >= trial.sequence_reps) { // done with animation showAnimation = false; } } if (showAnimation) { if (trial.render_on_canvas) { display_element.querySelector('#jspsych-categorize-animation-stimulus').style.visibility = 'visible'; var img = new Image(); img.src = trial.stimuli[animate_frame]; canvas.height = img.naturalHeight; canvas.width = img.naturalWidth; ctx.drawImage(img,0,0); } else { display_element.innerHTML += '<img src="'+trial.stimuli[animate_frame]+'" class="jspsych-categorize-animation-stimulus"></img>'; } } if (!responded && trial.allow_response_before_complete) { // in here if the user can respond before the animation is done if (trial.prompt !== null) { if (trial.render_on_canvas) { prompt_div.style.visibility = "visible"; } else { display_element.innerHTML += trial.prompt; } } if (trial.render_on_canvas) { if (!showAnimation) { canvas.remove(); } } } else if (!responded) { // in here if the user has to wait to respond until animation is done. // if this is the case, don't show the prompt until the animation is over. if (!showAnimation) { if (trial.prompt !== null) { if (trial.render_on_canvas) { prompt_div.style.visibility = "visible"; } else { display_element.innerHTML += trial.prompt; } } if (trial.render_on_canvas) { canvas.remove(); } } } else { // user has responded if we get here. // show feedback var feedback_text = ""; if (correct) { feedback_text = trial.correct_text.replace("%ANS%", trial.text_answer); } else { feedback_text = trial.incorrect_text.replace("%ANS%", trial.text_answer); } if (trial.render_on_canvas) { if (trial.prompt !== null) { prompt_div.remove(); } feedback_div.innerHTML = feedback_text; } else { display_element.innerHTML += feedback_text; } // set timeout to clear feedback if (!timeoutSet) { timeoutSet = true; jsPsych.pluginAPI.setTimeout(function() { endTrial(); }, trial.feedback_duration); } } }, trial.frame_time); var keyboard_listener; var trial_data = {}; var after_response = function(info) { // ignore the response if animation is playing and subject // not allowed to respond before it is complete if (!trial.allow_response_before_complete && showAnimation) { return false; } correct = false; if (trial.key_answer == info.key) { correct = true; } responded = true; trial_data = { "stimulus": JSON.stringify(trial.stimuli), "rt": info.rt, "correct": correct, "key_press": info.key }; jsPsych.pluginAPI.cancelKeyboardResponse(keyboard_listener); } keyboard_listener = jsPsych.pluginAPI.getKeyboardResponse({ callback_function: after_response, valid_responses: trial.choices, rt_method: 'performance', persist: true, allow_held_key: false }); function endTrial() { clearInterval(animate_interval); // stop animation! display_element.innerHTML = ''; // clear everything jsPsych.finishTrial(trial_data); } }; return plugin; })();
Java
<?php /* * This file is part of the Pho package. * * (c) Emre Sokullu <emre@phonetworks.org> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Pho\Lib\Graph; /** * Holds the relationship between nodes and edges. * * EdgeList objects are attached to all Node objects, they are * created at object initialization. They contain edge objects * categorized by their direction. * * @see ImmutableEdgeList For a list that doesn't accept new values. * * @author Emre Sokullu <emre@phonetworks.org> */ class EdgeList { /** * The node thay this edgelist belongs to * * @var NodeInterface */ private $master; /** * An internal pointer of outgoing nodes in [ID=>EncapsulatedEdge] format * where ID belongs to the edge. * * @var array */ private $out = []; /** * An internal pointer of incoming nodes in [ID=>EncapsulatedEdge] format * where ID belongs to the edge * * @var array */ private $in = []; /** * An internal pointer of incoming nodes in [ID=>[ID=>EncapsulatedEdge]] format * where first ID belongs to the node, and second to the edge. * * @var array */ private $from = []; /** * An internal pointer of outgoing nodes in [ID=>[ID=>EncapsulatedEdge]] format * where first ID belongs to the node, and second to the edge. * * @var array */ private $to = []; /** * Constructor * * For performance reasons, the constructor doesn't load the seed data * (if available) but waits for a method to attempt to access. * * @param NodeInterface $node The master, the owner of this EdgeList object. * @param array $data Initial data to seed. */ public function __construct(NodeInterface $node, array $data = []) { $this->master = $node; $this->import($data); } public function delete(ID $id): void { $id = (string) $id; foreach($this->from as $key=>$val) { unset($this->from[$key][$id]); } foreach($this->to as $key=>$val) { unset($this->to[$key][$id]); } unset($this->in[$id]); unset($this->out[$id]); $this->master->emit("modified"); } /** * Imports data from given array source * * @param array $data Data source. * * @return void */ public function import(array $data): void { if(!$this->isDataSetProperly($data)) { return; } $wakeup = function (array $array): EncapsulatedEdge { return EncapsulatedEdge::fromArray($array); }; $this->out = array_map($wakeup, $data["out"]); $this->in = array_map($wakeup, $data["in"]); foreach($data["from"] as $from => $frozen) { $this->from[$from] = array_map($wakeup, $frozen); } foreach($data["to"] as $to => $frozen) { $this->to[$to] = array_map($wakeup, $frozen); } } /** * Checks if the data source for import is valid. * * @param array $data * * @return bool */ private function isDataSetProperly(array $data): bool { return (isset($data["in"]) && isset($data["out"]) && isset($data["from"]) && isset($data["to"])); } /** * Retrieves this object in array format * * With all "in" and "out" values in simple string format. * The "to" array can be reconstructed. * * @return array */ public function toArray(): array { $to_array = function (EncapsulatedEdge $encapsulated): array { return $encapsulated->toArray(); }; $array = []; $array["to"] = []; foreach($this->to as $to => $encapsulated) { $array["to"][$to] = array_map($to_array, $encapsulated); } $array["from"] = []; foreach($this->from as $from => $encapsulated) { $array["from"][$from] = array_map($to_array, $encapsulated); } $array["in"] = array_map($to_array, $this->in); $array["out"] = array_map($to_array, $this->out); return $array; } /** * Adds an incoming edge to the list. * * The edge must be already initialized. * * @param EdgeInterface $edge * * @return void */ public function addIncoming(EdgeInterface $edge): void { $edge_encapsulated = EncapsulatedEdge::fromEdge($edge); $this->from[(string) $edge->tail()->id()][(string) $edge->id()] = $edge_encapsulated; $this->in[(string) $edge->id()] = $edge_encapsulated; $this->master->emit("modified"); } /** * Adds an outgoing edge to the list. * * The edge must be already initialized. * * @param EdgeInterface $edge * * @return void */ public function addOutgoing(EdgeInterface $edge): void { $edge_encapsulated = EncapsulatedEdge::fromEdge($edge); $this->to[(string) $edge->head()->id()][(string) $edge->id()] = $edge_encapsulated; $this->out[(string) $edge->id()] = $edge_encapsulated; $this->master->emit("modified"); } /** * Returns a list of all the edges directed towards * this particular node. * * @see retrieve Used by this method to fetch objects. * * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of EdgeInterface objects. */ public function in(string $class=""): \ArrayIterator { return $this->retrieve(Direction::in(), $class); } /** * Returns a list of all the edges originating from * this particular node. * * @see retrieve Used by this method to fetch objects. * * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of EdgeInterface objects. */ public function out(string $class=""): \ArrayIterator { return $this->retrieve(Direction::out(), $class); } /** * A helper method to retrieve edges. * * @see out A method that uses this function * @see in A method that uses this function * * @param Direction $direction Lets you choose to fetch incoming or outgoing edges. * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of EdgeInterface objects. */ protected function retrieve(Direction $direction, string $class): \ArrayIterator { $d = (string) $direction; $hydrate = function (EncapsulatedEdge $encapsulated): EdgeInterface { if(!$encapsulated->hydrated()) return $this->master->edge($encapsulated->id()); return $encapsulated->edge(); }; $filter_classes = function (EncapsulatedEdge $encapsulated) use ($class): bool { return in_array($class, $encapsulated->classes()); }; if(empty($class)) { return new \ArrayIterator( array_map($hydrate, $this->$d) ); } return new \ArrayIterator( array_map($hydrate, array_filter($this->$d, $filter_classes) ) ); } /** * Returns a list of all the edges (both in and out) pertaining to * this particular node. * * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of EdgeInterface objects. */ public function all(string $class=""): \ArrayIterator { return new \ArrayIterator( array_merge( $this->in($class)->getArrayCopy(), $this->out($class)->getArrayCopy() ) ); } /** * Retrieves a list of edges from the list's owner node to the given * target node. * * @param ID $node_id Target (head) node. * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of edge objects to. Returns an empty array if there is no such connections. */ public function to(ID $node_id, string $class=""): \ArrayIterator { return $this->retrieveDirected(Direction::out(), $node_id, $class); } /** * Retrieves a list of edges to the list's owner node from the given * source node. * * @param ID $node_id Source (tail) node. * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of edge objects from. Returns an empty array if there is no such connections. */ public function from(ID $node_id, string $class=""): \ArrayIterator { return $this->retrieveDirected(Direction::in(), $node_id, $class); } /** * Retrieves a list of edges between the list's owner node and the given * node. * * @param ID $node_id The other node. * @param string $class The type of edge (defined in edge class) to return * * @return \ArrayIterator An array of edge objects in between. Returns an empty array if there is no such connections. */ public function between(ID $node_id, string $class=""): \ArrayIterator { return new \ArrayIterator( array_merge( $this->from($node_id, $class)->getArrayCopy(), $this->to($node_id, $class)->getArrayCopy() ) ); } /** * A helper method to retrieve directed edges. * * @see from A method that uses this function * @see to A method that uses this function * * @param Direction $direction Lets you choose to fetch incoming or outgoing edges. * @param ID $node_id Directed towards which node. * @param string $class The type of edge (defined in edge class) to return. * * @return \ArrayIterator An array of EdgeInterface objects. */ protected function retrieveDirected(Direction $direction, ID $node_id, string $class): \ArrayIterator { $key = $direction->equals(Direction::in()) ? "from" : "to"; $direction = (string) $direction; $hydrate = function (EncapsulatedEdge $encapsulated): EdgeInterface { if(!$encapsulated->hydrated()) return $this->master->edge($encapsulated->id()); return $encapsulated->edge(); }; $filter_classes = function (EncapsulatedEdge $encapsulated) use ($class): bool { return in_array($class, $encapsulated->classes()); }; if(!isset($this->$key[(string) $node_id])) { return new \ArrayIterator(); } if(empty($class)) { return new \ArrayIterator( array_map($hydrate, $this->$key[(string) $node_id]) ); } return new \ArrayIterator( array_map($hydrate, array_filter($this->$key[(string) $node_id], $filter_classes)) ); } }
Java
package me.august.lumen.data; import me.august.lumen.compile.resolve.data.ClassData; import me.august.lumen.compile.resolve.lookup.DependencyManager; import org.junit.Assert; import org.junit.Test; public class DataTest { @Test public void testClassData() { ClassData data = ClassData.fromClass(String.class); Assert.assertEquals( String.class.getName(), data.getName() ); String[] expected = new String[]{ "java.io.Serializable", "java.lang.Comparable", "java.lang.CharSequence" }; Assert.assertArrayEquals( expected, data.getInterfaces() ); } @Test public void testAssignableTo() { DependencyManager deps = new DependencyManager(); ClassData data; data = ClassData.fromClass(String.class); Assert.assertTrue( "Expected String to be assignable to String", data.isAssignableTo("java.lang.String", deps) ); Assert.assertTrue( "Expected String to be assignable to Object", data.isAssignableTo("java.lang.Object", deps) ); Assert.assertTrue( "Expected String to be assignable to CharSequence", data.isAssignableTo("java.lang.CharSequence", deps) ); data = ClassData.fromClass(Object.class); Assert.assertFalse( "Expected Object to not be assignable to String", data.isAssignableTo("java.lang.String", deps) ); data = ClassData.fromClass(CharSequence.class); Assert.assertTrue( "Expected CharSequence to be assignable to Object", data.isAssignableTo("java.lang.Object", deps) ); } }
Java
<?php /** * CodeBin * * @author CRH380A-2722 <609657831@qq.com> * @copyright 2016 CRH380A-2722 * @license MIT */ /** 配置文件 */ /** 站点域名 */ define("SITEDOMAIN", "{SITE-DOMAIN}"); /** 数据库信息 */ //数据库服务器 define("DB_HOST", "{DB-HOST}"); //数据库用户名 define("DB_USER", "{DB-USER}"); //数据库密码 define("DB_PASSWORD", "{DB-PASS}"); //数据库名 define("DB_NAME", "{DB-NAME}"); //数据表前缀 define("DB_PREFIX", "{DB-PREFIX}"); //Flag: 开发者模式?(1=ON, 0=OFF) $devMode = 0; /** * Gravatar镜像地址 * * @var string $link * @note 此处填上你的Gravatar镜像地址(不要带http://或https://)如:gravatar.duoshuo.com * @note HTTP可用gravatar.duoshuo.com, HTTPS建议secure.gravatar.com * @note 或者你自己设立一个镜像存储也行 * @note 一般对墙内用户来说比较有用 */ $link = "{GRAVATAR-LINK}"; /** 好了,以下内容不要再编辑了!!*/ if (!$devMode) error_reporting(0); define("BASEROOT", dirname(__FILE__)); define("SESSIONNAME", "CodeClipboard"); require BASEROOT . "/includes/functions.php"; session_name(SESSIONNAME);
Java
<?php /** * @package Response * @subpackage Header * * @author Wojtek Zalewski <wojtek@neverbland.com> * * @copyright Copyright (c) 2013, Wojtek Zalewski * @license MIT */ namespace Wtk\Response\Header\Field; use Wtk\Response\Header\Field\AbstractField; use Wtk\Response\Header\Field\FieldInterface; /** * Basic implementation - simple Value Object for Header elements * * @author Wojtek Zalewski <wojtek@neverbland.com> */ class Field extends AbstractField implements FieldInterface { /** * Field name * * @var string */ protected $name; /** * Field value * * @var mixed */ protected $value; /** * * @param string $name * @param mixed $value */ public function __construct($name, $value) { $this->name = $name; /** * @todo: is is object, than it has to * implement toString method * We have to check for it now. */ $this->value = $value; } /** * Returns field name * * @return string */ public function getName() { return $this->name; } /** * Returns header field value * * @return string */ public function getValue() { return $this->value; } }
Java
--- layout: post author: Najko Jahn title: Max Planck Digital Library updates expenditures for articles published in the New Journal of Physics date: 2015-12-23 15:21:29 summary: categories: general comments: true --- [Max Planck Digital Library (MPDL)](https://www.mpdl.mpg.de/en/) provides [institutional funding for Open Access publications](https://www.mpdl.mpg.de/en/?id=50:open-access-publishing&catid=17:open-access) for researchers affiliated with the [Max Planck Society](http://www.mpg.de/en). MPDL makes use of central agreements with Open Access publishers. It has now updated its expenditures for Open Access articles in the [New Journal of Physics](http://iopscience.iop.org/1367-2630). Please note that article processing charges funded locally by Max Planck Institutes are not part of this data set. The Max Planck Society has a limited input tax reduction. The refund of input VAT for APC is 20%. ## Cost data The data set covers publication fees for 522 articles published in the New Journal of Physics by MPG researchers, which MPDL covered from 2006 until 2014. Total expenditure amounts to 497 229€ and the average fee is 953€. ### Average costs per year (in EURO) ![plot of chunk box_mpdl_njp_year](/figure/box_mpdl_njp_year-1.png)
Java
'use strict'; var app = angular.module('Fablab'); app.controller('GlobalPurchaseEditController', function ($scope, $location, $filter, $window, PurchaseService, NotificationService, StaticDataService, SupplyService) { $scope.selected = {purchase: undefined}; $scope.currency = App.CONFIG.CURRENCY; $scope.loadPurchase = function (id) { PurchaseService.get(id, function (data) { $scope.purchase = data; }); }; $scope.save = function () { var purchaseCurrent = angular.copy($scope.purchase); updateStock(); PurchaseService.save(purchaseCurrent, function (data) { $scope.purchase = data; NotificationService.notify("success", "purchase.notification.saved"); $location.path("purchases"); }); }; var updateStock = function () { var stockInit = $scope.purchase.supply.quantityStock; $scope.purchase.supply.quantityStock = parseFloat(stockInit) - parseFloat($scope.purchase.quantity); var supplyCurrent = angular.copy($scope.purchase.supply); SupplyService.save(supplyCurrent, function (data) { $scope.purchase.supply = data; }); }; $scope.maxMoney = function () { return parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice); }; $scope.updatePrice = function () { var interTotal = parseFloat($scope.purchase.quantity) * parseFloat($scope.purchase.supply.sellingPrice); if ($scope.purchase.discount === undefined || !$scope.purchase.discount) { //0.05 cts ceil var val = $window.Math.ceil(interTotal * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); ; } else { if ($scope.purchase.discountPercent) { var discountInter = parseFloat(interTotal) * (parseFloat($scope.purchase.discount) / parseFloat(100)); var total = parseFloat(interTotal) - parseFloat(discountInter); //0.05 cts ceil var val = $window.Math.ceil(total * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); } else { var total = parseFloat(interTotal) - parseFloat($scope.purchase.discount); //0.05 cts ceil var val = $window.Math.ceil(total * 20) / 20; $scope.purchase.purchasePrice = $filter('number')(val, 2); } } }; $scope.firstPercent = App.CONFIG.FIRST_PERCENT.toUpperCase() === "PERCENT"; $scope.optionsPercent = [{ name: "%", value: true }, { name: App.CONFIG.CURRENCY, value: false }]; $scope.today = function () { $scope.dt = new Date(); }; $scope.today(); $scope.clear = function () { $scope.dt = null; }; $scope.open = function ($event) { $event.preventDefault(); $event.stopPropagation(); $scope.opened = true; }; $scope.dateOptions = { formatYear: 'yy', startingDay: 1 }; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[2]; var tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); var afterTomorrow = new Date(); afterTomorrow.setDate(tomorrow.getDate() + 2); $scope.events = [ { date: tomorrow, status: 'full' }, { date: afterTomorrow, status: 'partially' } ]; $scope.getDayClass = function (date, mode) { if (mode === 'day') { var dayToCheck = new Date(date).setHours(0, 0, 0, 0); for (var i = 0; i < $scope.events.length; i++) { var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0); if (dayToCheck === currentDay) { return $scope.events[i].status; } } } return ''; }; StaticDataService.loadSupplyStock(function (data) { $scope.supplyStock = data; }); StaticDataService.loadCashiers(function (data) { $scope.cashierList = data; }); } ); app.controller('PurchaseNewController', function ($scope, $controller, $rootScope) { $controller('GlobalPurchaseEditController', {$scope: $scope}); $scope.newPurchase = true; $scope.paidDirectly = false; $scope.purchase = { purchaseDate: new Date(), user: $rootScope.connectedUser.user }; } ); app.controller('PurchaseEditController', function ($scope, $routeParams, $controller) { $controller('GlobalPurchaseEditController', {$scope: $scope}); $scope.newPurchase = false; $scope.loadPurchase($routeParams.id); } );
Java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package ons; import ons.util.WeightedGraph; import org.w3c.dom.*; /** * The physical topology of a network refers to he physical layout of devices on * a network, or to the way that the devices on a network are arranged and how * they communicate with each other. * * @author andred */ public abstract class PhysicalTopology { protected int nodes; protected int links; protected OXC[] nodeVector; protected Link[] linkVector; protected Link[][] adjMatrix; /** * Creates a new PhysicalTopology object. Takes the XML file containing all * the information about the simulation environment and uses it to populate * the PhysicalTopology object. The physical topology is basically composed * of nodes connected by links, each supporting different wavelengths. * * @param xml file that contains the simulation environment information */ public PhysicalTopology(Element xml) { try { if (Simulator.verbose) { System.out.println(xml.getAttribute("name")); } } catch (Throwable t) { t.printStackTrace(); } } /** * Retrieves the number of nodes in a given PhysicalTopology. * * @return the value of the PhysicalTopology's nodes attribute */ public int getNumNodes() { return nodes; } /** * Retrieves the number of links in a given PhysicalTopology. * * @return number of items in the PhysicalTopology's linkVector attribute */ public int getNumLinks() { return linkVector.length; } /** * Retrieves a specific node in the PhysicalTopology object. * * @param id the node's unique identifier * @return specified node from the PhysicalTopology's nodeVector */ public OXC getNode(int id) { return nodeVector[id]; } /** * Retrieves a specific link in the PhysicalTopology object, based on its * unique identifier. * * @param linkid the link's unique identifier * @return specified link from the PhysicalTopology's linkVector */ public Link getLink(int linkid) { return linkVector[linkid]; } /** * Retrieves a specific link in the PhysicalTopology object, based on its * source and destination nodes. * * @param src the link's source node * @param dst the link's destination node * @return the specified link from the PhysicalTopology's adjMatrix */ public Link getLink(int src, int dst) { return adjMatrix[src][dst]; } /** * Retrives a given PhysicalTopology's adjancency matrix, which contains the * links between source and destination nodes. * * @return the PhysicalTopology's adjMatrix */ public Link[][] getAdjMatrix() { return adjMatrix; } /** * Says whether exists or not a link between two given nodes. * * @param node1 possible link's source node * @param node2 possible link's destination node * @return true if the link exists in the PhysicalTopology's adjMatrix */ public boolean hasLink(int node1, int node2) { if (adjMatrix[node1][node2] != null) { return true; } else { return false; } } /** * Checks if a path made of links makes sense by checking its continuity * * @param links to be checked * @return true if the link exists in the PhysicalTopology's adjMatrix */ public boolean checkLinkPath(int links[]) { for (int i = 0; i < links.length - 1; i++) { if (!(getLink(links[i]).dst == getLink(links[i + 1]).src)) { return false; } } return true; } /** * Returns a weighted graph with vertices, edges and weights representing * the physical network nodes, links and weights implemented by this class * object. * * @return an WeightedGraph class object */ public WeightedGraph getWeightedGraph() { WeightedGraph g = new WeightedGraph(nodes); for (int i = 0; i < nodes; i++) { for (int j = 0; j < nodes; j++) { if (hasLink(i, j)) { g.addEdge(i, j, getLink(i, j).getWeight()); } } } return g; } /** * * */ public void printXpressInputFile() { // Edges System.out.println("EDGES: ["); for (int i = 0; i < this.getNumNodes(); i++) { for (int j = 0; j < this.getNumNodes(); j++) { if (this.hasLink(i, j)) { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 1"); } else { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 0"); } } } System.out.println("]"); System.out.println(); // SD Pairs System.out.println("TRAFFIC: ["); for (int i = 0; i < this.getNumNodes(); i++) { for (int j = 0; j < this.getNumNodes(); j++) { if (i != j) { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 1"); } else { System.out.println("(" + Integer.toString(i + 1) + " " + Integer.toString(j + 1) + ") 0"); } } } System.out.println("]"); } /** * Prints all nodes and links between them in the PhysicalTopology object. * * @return string containing the PhysicalTopology's adjMatrix values */ @Override public String toString() { String topo = ""; for (int i = 0; i < nodes; i++) { for (int j = 0; j < nodes; j++) { if (adjMatrix[i][j] != null) { topo += adjMatrix[i][j].toString() + "\n\n"; } } } return topo; } public abstract void createPhysicalLightpath(LightPath lp); public abstract void removePhysicalLightpath(LightPath lp); public abstract boolean canCreatePhysicalLightpath(LightPath lp); public abstract double getBW(LightPath lp); public abstract double getBWAvailable(LightPath lp); public abstract boolean canAddFlow(Flow flow, LightPath lightpath); public abstract void addFlow(Flow flow, LightPath lightpath); public abstract void addBulkData(BulkData bulkData, LightPath lightpath); public abstract void removeFlow(Flow flow, LightPath lightpath); public abstract boolean canAddBulkData(BulkData bulkData, LightPath lightpath); }
Java
require File.join [Pluct.root, 'lib/pluct/extensions/json'] describe JSON do it 'returns false for invalid data' do ['', ' ', 'string'].each do |s| expect(JSON.is_json?(s)).to be_false end end it 'returns true for valid data' do expect(JSON.is_json?('{"name" : "foo"}')).to be_true end end
Java
module VhdlTestScript class Wait CLOCK_LENGTH = 2 def initialize(length) @length = length end def to_vhdl "wait for #{@length * CLOCK_LENGTH} ns;" end def in(ports) self end def origin self end end end
Java
--- version: v1.4.13 category: API redirect_from: - /docs/v0.37.8/api/global-shortcut - /docs/v0.37.7/api/global-shortcut - /docs/v0.37.6/api/global-shortcut - /docs/v0.37.5/api/global-shortcut - /docs/v0.37.4/api/global-shortcut - /docs/v0.37.3/api/global-shortcut - /docs/v0.36.12/api/global-shortcut - /docs/v0.37.1/api/global-shortcut - /docs/v0.37.0/api/global-shortcut - /docs/v0.36.11/api/global-shortcut - /docs/v0.36.10/api/global-shortcut - /docs/v0.36.9/api/global-shortcut - /docs/v0.36.8/api/global-shortcut - /docs/v0.36.7/api/global-shortcut - /docs/v0.36.6/api/global-shortcut - /docs/v0.36.5/api/global-shortcut - /docs/v0.36.4/api/global-shortcut - /docs/v0.36.3/api/global-shortcut - /docs/v0.35.5/api/global-shortcut - /docs/v0.36.2/api/global-shortcut - /docs/v0.36.0/api/global-shortcut - /docs/v0.35.4/api/global-shortcut - /docs/v0.35.3/api/global-shortcut - /docs/v0.35.2/api/global-shortcut - /docs/v0.34.4/api/global-shortcut - /docs/v0.35.1/api/global-shortcut - /docs/v0.34.3/api/global-shortcut - /docs/v0.34.2/api/global-shortcut - /docs/v0.34.1/api/global-shortcut - /docs/v0.34.0/api/global-shortcut - /docs/v0.33.9/api/global-shortcut - /docs/v0.33.8/api/global-shortcut - /docs/v0.33.7/api/global-shortcut - /docs/v0.33.6/api/global-shortcut - /docs/v0.33.4/api/global-shortcut - /docs/v0.33.3/api/global-shortcut - /docs/v0.33.2/api/global-shortcut - /docs/v0.33.1/api/global-shortcut - /docs/v0.33.0/api/global-shortcut - /docs/v0.32.3/api/global-shortcut - /docs/v0.32.2/api/global-shortcut - /docs/v0.31.2/api/global-shortcut - /docs/v0.31.0/api/global-shortcut - /docs/v0.30.4/api/global-shortcut - /docs/v0.29.2/api/global-shortcut - /docs/v0.29.1/api/global-shortcut - /docs/v0.28.3/api/global-shortcut - /docs/v0.28.2/api/global-shortcut - /docs/v0.28.1/api/global-shortcut - /docs/v0.28.0/api/global-shortcut - /docs/v0.27.3/api/global-shortcut - /docs/v0.27.2/api/global-shortcut - /docs/v0.27.1/api/global-shortcut - /docs/v0.27.0/api/global-shortcut - /docs/v0.26.1/api/global-shortcut - /docs/v0.26.0/api/global-shortcut - /docs/v0.25.3/api/global-shortcut - /docs/v0.25.2/api/global-shortcut - /docs/v0.25.1/api/global-shortcut - /docs/v0.25.0/api/global-shortcut - /docs/v0.24.0/api/global-shortcut - /docs/v0.23.0/api/global-shortcut - /docs/v0.22.3/api/global-shortcut - /docs/v0.22.2/api/global-shortcut - /docs/v0.22.1/api/global-shortcut - /docs/v0.21.3/api/global-shortcut - /docs/v0.21.2/api/global-shortcut - /docs/v0.21.1/api/global-shortcut - /docs/v0.21.0/api/global-shortcut - /docs/v0.20.8/api/global-shortcut - /docs/v0.20.7/api/global-shortcut - /docs/v0.20.6/api/global-shortcut - /docs/v0.20.5/api/global-shortcut - /docs/v0.20.4/api/global-shortcut - /docs/v0.20.3/api/global-shortcut - /docs/v0.20.2/api/global-shortcut - /docs/v0.20.1/api/global-shortcut - /docs/v0.20.0/api/global-shortcut - /docs/vlatest/api/global-shortcut source_url: 'https://github.com/electron/electron/blob/master/docs/api/global-shortcut.md' title: globalShortcut excerpt: Detect keyboard events when the application does not have keyboard focus. sort_title: global-shortcut --- # globalShortcut > Detect keyboard events when the application does not have keyboard focus. Process: [Main]({{site.baseurl}}/docs/tutorial/quick-start#main-process) The `globalShortcut` module can register/unregister a global keyboard shortcut with the operating system so that you can customize the operations for various shortcuts. **Note:** The shortcut is global; it will work even if the app does not have the keyboard focus. You should not use this module until the `ready` event of the app module is emitted. ```javascript const {app, globalShortcut} = require('electron') app.on('ready', () => { // Register a 'CommandOrControl+X' shortcut listener. const ret = globalShortcut.register('CommandOrControl+X', () => { console.log('CommandOrControl+X is pressed') }) if (!ret) { console.log('registration failed') } // Check whether a shortcut is registered. console.log(globalShortcut.isRegistered('CommandOrControl+X')) }) app.on('will-quit', () => { // Unregister a shortcut. globalShortcut.unregister('CommandOrControl+X') // Unregister all shortcuts. globalShortcut.unregisterAll() }) ``` ## Methods The `globalShortcut` module has the following methods: ### `globalShortcut.register(accelerator, callback)` * `accelerator` [Accelerator]({{site.baseurl}}/docs/api/accelerator) * `callback` Function Registers a global shortcut of `accelerator`. The `callback` is called when the registered shortcut is pressed by the user. When the accelerator is already taken by other applications, this call will silently fail. This behavior is intended by operating systems, since they don't want applications to fight for global shortcuts. ### `globalShortcut.isRegistered(accelerator)` * `accelerator` [Accelerator]({{site.baseurl}}/docs/api/accelerator) Returns `Boolean` - Whether this application has registered `accelerator`. When the accelerator is already taken by other applications, this call will still return `false`. This behavior is intended by operating systems, since they don't want applications to fight for global shortcuts. ### `globalShortcut.unregister(accelerator)` * `accelerator` [Accelerator]({{site.baseurl}}/docs/api/accelerator) Unregisters the global shortcut of `accelerator`. ### `globalShortcut.unregisterAll()` Unregisters all of the global shortcuts.
Java
--- uid: SolidEdgeFrameworkSupport.BSplineCurve2d.GetParameterRange(System.Double@,System.Double@) summary: remarks: syntax: parameters: - id: End description: Specifies the end parameter of the curve. - id: Start description: Specifies the start parameter of the curve. ---
Java
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_ #define BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_ #include <stdint.h> #include <map> #include <memory> #include <set> #include <vector> #include "base/atomicops.h" #include "base/containers/hash_tables.h" #include "base/macros.h" #include "base/memory/ref_counted.h" #include "base/memory/singleton.h" #include "base/synchronization/lock.h" #include "base/timer/timer.h" #include "base/trace_event/memory_dump_request_args.h" #include "base/trace_event/process_memory_dump.h" #include "base/trace_event/trace_event.h" namespace base { class SingleThreadTaskRunner; class Thread; namespace trace_event { class MemoryDumpManagerDelegate; class MemoryDumpProvider; class MemoryDumpSessionState; // This is the interface exposed to the rest of the codebase to deal with // memory tracing. The main entry point for clients is represented by // RequestDumpPoint(). The extension by Un(RegisterDumpProvider). class BASE_EXPORT MemoryDumpManager : public TraceLog::EnabledStateObserver { public: static const char* const kTraceCategory; // This value is returned as the tracing id of the child processes by // GetTracingProcessId() when tracing is not enabled. static const uint64_t kInvalidTracingProcessId; static MemoryDumpManager* GetInstance(); // Invoked once per process to listen to trace begin / end events. // Initialization can happen after (Un)RegisterMemoryDumpProvider() calls // and the MemoryDumpManager guarantees to support this. // On the other side, the MemoryDumpManager will not be fully operational // (i.e. will NACK any RequestGlobalMemoryDump()) until initialized. // Arguments: // is_coordinator: if true this MemoryDumpManager instance will act as a // coordinator and schedule periodic dumps (if enabled via TraceConfig); // false when the MemoryDumpManager is initialized in a slave process. // delegate: inversion-of-control interface for embedder-specific behaviors // (multiprocess handshaking). See the lifetime and thread-safety // requirements in the |MemoryDumpManagerDelegate| docstring. void Initialize(MemoryDumpManagerDelegate* delegate, bool is_coordinator); // (Un)Registers a MemoryDumpProvider instance. // Args: // - mdp: the MemoryDumpProvider instance to be registered. MemoryDumpManager // does NOT take memory ownership of |mdp|, which is expected to either // be a singleton or unregister itself. // - name: a friendly name (duplicates allowed). Used for debugging and // run-time profiling of memory-infra internals. Must be a long-lived // C string. // - task_runner: either a SingleThreadTaskRunner or SequencedTaskRunner. All // the calls to |mdp| will be run on the given |task_runner|. If passed // null |mdp| should be able to handle calls on arbitrary threads. // - options: extra optional arguments. See memory_dump_provider.h. void RegisterDumpProvider(MemoryDumpProvider* mdp, const char* name, scoped_refptr<SingleThreadTaskRunner> task_runner); void RegisterDumpProvider(MemoryDumpProvider* mdp, const char* name, scoped_refptr<SingleThreadTaskRunner> task_runner, MemoryDumpProvider::Options options); void RegisterDumpProviderWithSequencedTaskRunner( MemoryDumpProvider* mdp, const char* name, scoped_refptr<SequencedTaskRunner> task_runner, MemoryDumpProvider::Options options); void UnregisterDumpProvider(MemoryDumpProvider* mdp); // Unregisters an unbound dump provider and takes care about its deletion // asynchronously. Can be used only for for dump providers with no // task-runner affinity. // This method takes ownership of the dump provider and guarantees that: // - The |mdp| will be deleted at some point in the near future. // - Its deletion will not happen concurrently with the OnMemoryDump() call. // Note that OnMemoryDump() calls can still happen after this method returns. void UnregisterAndDeleteDumpProviderSoon(scoped_ptr<MemoryDumpProvider> mdp); // Requests a memory dump. The dump might happen or not depending on the // filters and categories specified when enabling tracing. // The optional |callback| is executed asynchronously, on an arbitrary thread, // to notify about the completion of the global dump (i.e. after all the // processes have dumped) and its success (true iff all the dumps were // successful). void RequestGlobalDump(MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail, const MemoryDumpCallback& callback); // Same as above (still asynchronous), but without callback. void RequestGlobalDump(MemoryDumpType dump_type, MemoryDumpLevelOfDetail level_of_detail); // TraceLog::EnabledStateObserver implementation. void OnTraceLogEnabled() override; void OnTraceLogDisabled() override; // Returns the MemoryDumpSessionState object, which is shared by all the // ProcessMemoryDump and MemoryAllocatorDump instances through all the tracing // session lifetime. const scoped_refptr<MemoryDumpSessionState>& session_state() const { return session_state_; } // Returns a unique id for identifying the processes. The id can be // retrieved by child processes only when tracing is enabled. This is // intended to express cross-process sharing of memory dumps on the // child-process side, without having to know its own child process id. uint64_t GetTracingProcessId() const; // Returns the name for a the allocated_objects dump. Use this to declare // suballocator dumps from other dump providers. // It will return nullptr if there is no dump provider for the system // allocator registered (which is currently the case for Mac OS). const char* system_allocator_pool_name() const { return kSystemAllocatorPoolName; }; // When set to true, calling |RegisterMemoryDumpProvider| is a no-op. void set_dumper_registrations_ignored_for_testing(bool ignored) { dumper_registrations_ignored_for_testing_ = ignored; } private: friend std::default_delete<MemoryDumpManager>; // For the testing instance. friend struct DefaultSingletonTraits<MemoryDumpManager>; friend class MemoryDumpManagerDelegate; friend class MemoryDumpManagerTest; // Descriptor used to hold information about registered MDPs. // Some important considerations about lifetime of this object: // - In nominal conditions, all the MemoryDumpProviderInfo instances live in // the |dump_providers_| collection (% unregistration while dumping). // - Upon each dump they (actually their scoped_refptr-s) are copied into // the ProcessMemoryDumpAsyncState. This is to allow removal (see below). // - When the MDP.OnMemoryDump() is invoked, the corresponding MDPInfo copy // inside ProcessMemoryDumpAsyncState is removed. // - In most cases, the MDPInfo is destroyed within UnregisterDumpProvider(). // - If UnregisterDumpProvider() is called while a dump is in progress, the // MDPInfo is destroyed in SetupNextMemoryDump() or InvokeOnMemoryDump(), // when the copy inside ProcessMemoryDumpAsyncState is erase()-d. // - The non-const fields of MemoryDumpProviderInfo are safe to access only // on tasks running in the |task_runner|, unless the thread has been // destroyed. struct MemoryDumpProviderInfo : public RefCountedThreadSafe<MemoryDumpProviderInfo> { // Define a total order based on the |task_runner| affinity, so that MDPs // belonging to the same SequencedTaskRunner are adjacent in the set. struct Comparator { bool operator()(const scoped_refptr<MemoryDumpProviderInfo>& a, const scoped_refptr<MemoryDumpProviderInfo>& b) const; }; using OrderedSet = std::set<scoped_refptr<MemoryDumpProviderInfo>, Comparator>; MemoryDumpProviderInfo(MemoryDumpProvider* dump_provider, const char* name, scoped_refptr<SequencedTaskRunner> task_runner, const MemoryDumpProvider::Options& options); MemoryDumpProvider* const dump_provider; // Used to transfer ownership for UnregisterAndDeleteDumpProviderSoon(). // nullptr in all other cases. scoped_ptr<MemoryDumpProvider> owned_dump_provider; // Human readable name, for debugging and testing. Not necessarily unique. const char* const name; // The task runner affinity. Can be nullptr, in which case the dump provider // will be invoked on |dump_thread_|. const scoped_refptr<SequencedTaskRunner> task_runner; // The |options| arg passed to RegisterDumpProvider(). const MemoryDumpProvider::Options options; // For fail-safe logic (auto-disable failing MDPs). int consecutive_failures; // Flagged either by the auto-disable logic or during unregistration. bool disabled; private: friend class base::RefCountedThreadSafe<MemoryDumpProviderInfo>; ~MemoryDumpProviderInfo(); DISALLOW_COPY_AND_ASSIGN(MemoryDumpProviderInfo); }; // Holds the state of a process memory dump that needs to be carried over // across task runners in order to fulfil an asynchronous CreateProcessDump() // request. At any time exactly one task runner owns a // ProcessMemoryDumpAsyncState. struct ProcessMemoryDumpAsyncState { ProcessMemoryDumpAsyncState( MemoryDumpRequestArgs req_args, const MemoryDumpProviderInfo::OrderedSet& dump_providers, scoped_refptr<MemoryDumpSessionState> session_state, MemoryDumpCallback callback, scoped_refptr<SingleThreadTaskRunner> dump_thread_task_runner); ~ProcessMemoryDumpAsyncState(); // Gets or creates the memory dump container for the given target process. ProcessMemoryDump* GetOrCreateMemoryDumpContainerForProcess(ProcessId pid); // A map of ProcessId -> ProcessMemoryDump, one for each target process // being dumped from the current process. Typically each process dumps only // for itself, unless dump providers specify a different |target_process| in // MemoryDumpProvider::Options. std::map<ProcessId, scoped_ptr<ProcessMemoryDump>> process_dumps; // The arguments passed to the initial CreateProcessDump() request. const MemoryDumpRequestArgs req_args; // An ordered sequence of dump providers that have to be invoked to complete // the dump. This is a copy of |dump_providers_| at the beginning of a dump // and becomes empty at the end, when all dump providers have been invoked. std::vector<scoped_refptr<MemoryDumpProviderInfo>> pending_dump_providers; // The trace-global session state. scoped_refptr<MemoryDumpSessionState> session_state; // Callback passed to the initial call to CreateProcessDump(). MemoryDumpCallback callback; // The |success| field that will be passed as argument to the |callback|. bool dump_successful; // The thread on which FinalizeDumpAndAddToTrace() (and hence |callback|) // should be invoked. This is the thread on which the initial // CreateProcessDump() request was called. const scoped_refptr<SingleThreadTaskRunner> callback_task_runner; // The thread on which unbound dump providers should be invoked. // This is essentially |dump_thread_|.task_runner() but needs to be kept // as a separate variable as it needs to be accessed by arbitrary dumpers' // threads outside of the lock_ to avoid races when disabling tracing. // It is immutable for all the duration of a tracing session. const scoped_refptr<SingleThreadTaskRunner> dump_thread_task_runner; private: DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDumpAsyncState); }; static const int kMaxConsecutiveFailuresCount; static const char* const kSystemAllocatorPoolName; MemoryDumpManager(); ~MemoryDumpManager() override; static void SetInstanceForTesting(MemoryDumpManager* instance); static void FinalizeDumpAndAddToTrace( scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state); // Enable heap profiling if kEnableHeapProfiling is specified. void EnableHeapProfilingIfNeeded(); // Internal, used only by MemoryDumpManagerDelegate. // Creates a memory dump for the current process and appends it to the trace. // |callback| will be invoked asynchronously upon completion on the same // thread on which CreateProcessDump() was called. void CreateProcessDump(const MemoryDumpRequestArgs& args, const MemoryDumpCallback& callback); // Calls InvokeOnMemoryDump() for the next MDP on the task runner specified by // the MDP while registration. On failure to do so, skips and continues to // next MDP. void SetupNextMemoryDump( scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state); // Invokes OnMemoryDump() of the next MDP and calls SetupNextMemoryDump() at // the end to continue the ProcessMemoryDump. Should be called on the MDP task // runner. void InvokeOnMemoryDump(ProcessMemoryDumpAsyncState* owned_pmd_async_state); // Helper for RegierDumpProvider* functions. void RegisterDumpProviderInternal( MemoryDumpProvider* mdp, const char* name, scoped_refptr<SequencedTaskRunner> task_runner, const MemoryDumpProvider::Options& options); // Helper for the public UnregisterDumpProvider* functions. void UnregisterDumpProviderInternal(MemoryDumpProvider* mdp, bool take_mdp_ownership_and_delete_async); // An ordererd set of registered MemoryDumpProviderInfo(s), sorted by task // runner affinity (MDPs belonging to the same task runners are adjacent). MemoryDumpProviderInfo::OrderedSet dump_providers_; // Shared among all the PMDs to keep state scoped to the tracing session. scoped_refptr<MemoryDumpSessionState> session_state_; MemoryDumpManagerDelegate* delegate_; // Not owned. // When true, this instance is in charge of coordinating periodic dumps. bool is_coordinator_; // Protects from concurrent accesses to the |dump_providers_*| and |delegate_| // to guard against disabling logging while dumping on another thread. Lock lock_; // Optimization to avoid attempting any memory dump (i.e. to not walk an empty // dump_providers_enabled_ list) when tracing is not enabled. subtle::AtomicWord memory_tracing_enabled_; // For time-triggered periodic dumps. RepeatingTimer periodic_dump_timer_; // Thread used for MemoryDumpProviders which don't specify a task runner // affinity. scoped_ptr<Thread> dump_thread_; // The unique id of the child process. This is created only for tracing and is // expected to be valid only when tracing is enabled. uint64_t tracing_process_id_; // When true, calling |RegisterMemoryDumpProvider| is a no-op. bool dumper_registrations_ignored_for_testing_; // Whether new memory dump providers should be told to enable heap profiling. bool heap_profiling_enabled_; DISALLOW_COPY_AND_ASSIGN(MemoryDumpManager); }; // The delegate is supposed to be long lived (read: a Singleton) and thread // safe (i.e. should expect calls from any thread and handle thread hopping). class BASE_EXPORT MemoryDumpManagerDelegate { public: virtual void RequestGlobalMemoryDump(const MemoryDumpRequestArgs& args, const MemoryDumpCallback& callback) = 0; // Returns tracing process id of the current process. This is used by // MemoryDumpManager::GetTracingProcessId. virtual uint64_t GetTracingProcessId() const = 0; protected: MemoryDumpManagerDelegate() {} virtual ~MemoryDumpManagerDelegate() {} void CreateProcessDump(const MemoryDumpRequestArgs& args, const MemoryDumpCallback& callback) { MemoryDumpManager::GetInstance()->CreateProcessDump(args, callback); } private: DISALLOW_COPY_AND_ASSIGN(MemoryDumpManagerDelegate); }; } // namespace trace_event } // namespace base #endif // BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_
Java
class CreateUser < ActiveRecord::Migration def up create_table :users do |t| t.integer :user_id, :limit => 8 t.string :screen_name t.boolean :following, :default => false t.boolean :followed, :default => false t.boolean :unfollowed, :default => false t.timestamp :followed_at t.timestamp :created_at t.timestamp :updated_at t.boolean :keep t.text :twitter_attributes end end end
Java
/* crypto/cryptlib.c */ /* ==================================================================== * Copyright (c) 1998-2006 The OpenSSL Project. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. All advertising materials mentioning features or use of this * software must display the following acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit. (http://www.openssl.org/)" * * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to * endorse or promote products derived from this software without * prior written permission. For written permission, please contact * openssl-core@openssl.org. * * 5. Products derived from this software may not be called "OpenSSL" * nor may "OpenSSL" appear in their names without prior written * permission of the OpenSSL Project. * * 6. Redistributions of any form whatsoever must retain the following * acknowledgment: * "This product includes software developed by the OpenSSL Project * for use in the OpenSSL Toolkit (http://www.openssl.org/)" * * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * ==================================================================== * * This product includes cryptographic software written by Eric Young * (eay@cryptsoft.com). This product includes software written by Tim * Hudson (tjh@cryptsoft.com). * */ /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) * All rights reserved. * * This package is an SSL implementation written * by Eric Young (eay@cryptsoft.com). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson (tjh@cryptsoft.com). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young (eay@cryptsoft.com)" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson (tjh@cryptsoft.com)" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* ==================================================================== * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED. * ECDH support in OpenSSL originally developed by * SUN MICROSYSTEMS, INC., and contributed to the OpenSSL project. */ #include "internal/cryptlib.h" #ifndef OPENSSL_NO_DEPRECATED static unsigned long (*id_callback) (void) = 0; #endif static void (*threadid_callback) (CRYPTO_THREADID *) = 0; /* * the memset() here and in set_pointer() seem overkill, but for the sake of * CRYPTO_THREADID_cmp() this avoids any platform silliness that might cause * two "equal" THREADID structs to not be memcmp()-identical. */ void CRYPTO_THREADID_set_numeric(CRYPTO_THREADID *id, unsigned long val) { memset(id, 0, sizeof(*id)); id->val = val; } static const unsigned char hash_coeffs[] = { 3, 5, 7, 11, 13, 17, 19, 23 }; void CRYPTO_THREADID_set_pointer(CRYPTO_THREADID *id, void *ptr) { unsigned char *dest = (void *)&id->val; unsigned int accum = 0; unsigned char dnum = sizeof(id->val); memset(id, 0, sizeof(*id)); id->ptr = ptr; if (sizeof(id->val) >= sizeof(id->ptr)) { /* * 'ptr' can be embedded in 'val' without loss of uniqueness */ id->val = (unsigned long)id->ptr; return; } /* * hash ptr ==> val. Each byte of 'val' gets the mod-256 total of a * linear function over the bytes in 'ptr', the co-efficients of which * are a sequence of low-primes (hash_coeffs is an 8-element cycle) - the * starting prime for the sequence varies for each byte of 'val' (unique * polynomials unless pointers are >64-bit). For added spice, the totals * accumulate rather than restarting from zero, and the index of the * 'val' byte is added each time (position dependence). If I was a * black-belt, I'd scan big-endian pointers in reverse to give low-order * bits more play, but this isn't crypto and I'd prefer nobody mistake it * as such. Plus I'm lazy. */ while (dnum--) { const unsigned char *src = (void *)&id->ptr; unsigned char snum = sizeof(id->ptr); while (snum--) accum += *(src++) * hash_coeffs[(snum + dnum) & 7]; accum += dnum; *(dest++) = accum & 255; } } int CRYPTO_THREADID_set_callback(void (*func) (CRYPTO_THREADID *)) { if (threadid_callback) return 0; threadid_callback = func; return 1; } void (*CRYPTO_THREADID_get_callback(void)) (CRYPTO_THREADID *) { return threadid_callback; } void CRYPTO_THREADID_current(CRYPTO_THREADID *id) { if (threadid_callback) { threadid_callback(id); return; } #ifndef OPENSSL_NO_DEPRECATED /* If the deprecated callback was set, fall back to that */ if (id_callback) { CRYPTO_THREADID_set_numeric(id, id_callback()); return; } #endif /* Else pick a backup */ #if defined(OPENSSL_SYS_WIN32) CRYPTO_THREADID_set_numeric(id, (unsigned long)GetCurrentThreadId()); #else /* For everything else, default to using the address of 'errno' */ CRYPTO_THREADID_set_pointer(id, (void *)&errno); #endif } int CRYPTO_THREADID_cmp(const CRYPTO_THREADID *a, const CRYPTO_THREADID *b) { return memcmp(a, b, sizeof(*a)); } void CRYPTO_THREADID_cpy(CRYPTO_THREADID *dest, const CRYPTO_THREADID *src) { memcpy(dest, src, sizeof(*src)); } unsigned long CRYPTO_THREADID_hash(const CRYPTO_THREADID *id) { return id->val; } #ifndef OPENSSL_NO_DEPRECATED unsigned long (*CRYPTO_get_id_callback(void)) (void) { return (id_callback); } void CRYPTO_set_id_callback(unsigned long (*func) (void)) { id_callback = func; } unsigned long CRYPTO_thread_id(void) { unsigned long ret = 0; if (id_callback == NULL) { # if defined(OPENSSL_SYS_WIN32) ret = (unsigned long)GetCurrentThreadId(); # elif defined(GETPID_IS_MEANINGLESS) ret = 1L; # else ret = (unsigned long)getpid(); # endif } else ret = id_callback(); return (ret); } #endif
Java
// WinProm Copyright 2015 Edward Earl // All rights reserved. // // This software is distributed under a license that is described in // the LICENSE file that accompanies it. // // DomapInfo_dlg.cpp : implementation file // #include "stdafx.h" #include "winprom.h" #include "DomapInfo_dlg.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDomapInfo_dlg dialog CDomapInfo_dlg::CDomapInfo_dlg(const Area_info& a, const Area_info& d, const CString& n, bool m) : CMapInfo_dlg(a,d,n,m,CDomapInfo_dlg::IDD) { //{{AFX_DATA_INIT(CDomapInfo_dlg) m_ndom_0peak = 0; m_ndom_1peak = 0; m_ndom_peaks = 0; m_ndom_total = 0; m_ndom_area = 0; //}}AFX_DATA_INIT } void CDomapInfo_dlg::DoDataExchange(CDataExchange* pDX) { CMapInfo_dlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDomapInfo_dlg) DDX_Text(pDX, IDC_NDOM_0PEAK, m_ndom_0peak); DDX_Text(pDX, IDC_NDOM_1PEAK, m_ndom_1peak); DDX_Text(pDX, IDC_NDOM_PEAKS, m_ndom_peaks); DDX_Text(pDX, IDC_NDOM, m_ndom_total); DDX_Text(pDX, IDC_NDOM_AREA, m_ndom_area); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDomapInfo_dlg, CMapInfo_dlg) //{{AFX_MSG_MAP(CDomapInfo_dlg) // NOTE: the ClassWizard will add message map macros here //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDomapInfo_dlg message handlers
Java
{{<govuk_template}} {{$head}} {{>includes/elements_head}} {{>includes/elements_scripts}} {{/head}} {{$propositionHeader}} {{>includes/propositional_navigation4}} {{/propositionHeader}} {{$headerClass}}with-proposition{{/headerClass}} {{$content}} <script> if(sessionStorage.condition) { sessionStorage.removeItem('condition'); } function start() { window.location.href = 'condition-selection'; } </script> <main id="page-container" role="main"> {{>includes/phase_banner}} <div id="notify" class="starthidden"> <div class="grid-row" style="margin-top:1.5em"> <div class="column-two-thirds"> <h1 style="margin-top:0.5em;" class="form-title heading-xlarge"> Tell DVLA about your medical condition </h1> <p>You can use this service to tell DVLA about your medical condition.</p> <p>It is a legal requirement to tell DVLA of a medical condition that might affect your driving.</p> <div style="padding-top: 0px; padding-bottom: 5px;" class="panel-indent"> <!--div class="help-notice"> <h2 class="heading-medium">Don’t worry</h2> </div--> <h2 class="heading-medium">Don’t worry</h2> <p>Most drivers are allowed to continue driving.</p> </div> <h2 class="heading-medium">What you'll need</h2> <ul class="list-bullet" style="margin-bottom: 0;"> <li>to be a resident in Great Britain - there is a different process in <a href="http://amdr.herokuapp.com/COA_Direct_v4/Landing_page">Northern Ireland, Isle of Man and the Channel Islands</a> <li>your healthcare professionals' (eg GP, nurse, consultant) details</li> </ul> <!--details style="margin-top: 1em;"> <summary> <span class="summary"> What you'll need </span> </summary> <div class="panel-indent"> <ul class="list-bullet" style="margin-bottom: 0;"> <li>to be a resident in Great Britain - there is a different process in <a href="http://amdr.herokuapp.com/COA_Direct_v4/Landing_page">Northern Ireland, Isle of Man and the Channel Islands</a>. <li>your personal details</li> <li>your healthcare professionals' (e.g. GP, Nurse, Consultant) details</li> </ul> </div> </details--> <br/><br/> <div style=""> <h2 style="display: inline;"> <img src="/public/images/verify-logo-inline.png" style="width: 100px; display: inline; float: left;"/> <strong>GOV.UK</strong> <br/> VERIFY </h2> </div> <br/> <p>This service uses GOV.UK Verify to check your identity.</p> <br/> <a href="javascript:start();" class="button button-get-started" role="button">Start now</a> </div> <div class="column-third" style=";margin-bottom:0.75em"> <nav class="popular-needs"> <h3 class="heading-medium" style="border-top:10px solid #005ea5;margin-top:1em;padding-top:1em">Driving with a medical condition</h3> <ul style="list-style-type: none;"> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/health-conditions-and-driving">Conditions that need to be reported</a></li> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/driving-licence-categories">Types of driving licences</a></li> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/giving-up-your-driving-licence">I want to give up my licence</a></li> </ul> </nav> </div> </div> </div> <div id="renewal" class="starthidden"> <div class="grid-row" style="margin-top:1.5em"> <div class="column-two-thirds"> <h1 style="margin-top:0.5em;" class="form-title heading-xlarge"> Renew your medical driving licence </h1> <p>Use this service to:</p> <ul class="list-bullet"> <li>renew your medical driving licence</li> </ul> <p>If you need to tell DVLA about a different condition, download and complete the paper form – then post it to DVLA.</p> <a href="javascript:start();" class="button button-get-started" role="button">Start now</a> <h2 class="heading-medium" style="margin-top:0.75em">Other ways to apply</h2> <h2 class="heading-small" style="margin-top:0.75em">By post</h2> Please provide the following: <ul class="list-bullet"> <li>your full name and address</li> <li>your driving licence number (or your date of birth if you do not know your driving licence number)</li> <li>details about your medical condition</li> </ul> <p>Send to:</p> Drivers Medical Group <br> DVLA <br> Swansea <br> SA99 1TU </div> <div class="column-third" style=";margin-bottom:0.75em"> <nav class="popular-needs"> <h3 class="heading-medium" style="border-top:10px solid #005ea5;margin-top:1em;padding-top:1em">Driving with a medical condition</h3> <ul style=";list-style-type: none"> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/health-conditions-and-driving">Conditions that need to be reported</a></li> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/driving-licence-categories">Types of driving licences</a></li> <li style="margin-top: 0.5em;"><a href="https://www.gov.uk/giving-up-your-driving-licence">I want to give up my licence</a></li> </ul> </nav> </div> </div> </div> <script> show((QueryString.service == null) ? 'notify' : QueryString.service); </script> </main> {{/content}} {{$bodyEnd}} {{/bodyEnd}} {{/govuk_template}}
Java
// MIT License // // Copyright( c ) 2017 Packt // // 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. // // Vulkan Cookbook // ISBN: 9781786468154 // © Packt Publishing Limited // // Author: Pawel Lapinski // LinkedIn: https://www.linkedin.com/in/pawel-lapinski-84522329 // // Chapter: 11 Lighting // Recipe: 01 Rendering a geometry with vertex diffuse lighting #include "CookbookSampleFramework.h" using namespace VulkanCookbook; class Sample : public VulkanCookbookSample { Mesh Model; VkDestroyer(VkBuffer) VertexBuffer; VkDestroyer(VkDeviceMemory) VertexBufferMemory; VkDestroyer(VkDescriptorSetLayout) DescriptorSetLayout; VkDestroyer(VkDescriptorPool) DescriptorPool; std::vector<VkDescriptorSet> DescriptorSets; VkDestroyer(VkRenderPass) RenderPass; VkDestroyer(VkPipelineLayout) PipelineLayout; VkDestroyer(VkPipeline) Pipeline; VkDestroyer(VkBuffer) StagingBuffer; VkDestroyer(VkDeviceMemory) StagingBufferMemory; bool UpdateUniformBuffer; VkDestroyer(VkBuffer) UniformBuffer; VkDestroyer(VkDeviceMemory) UniformBufferMemory; virtual bool Initialize( WindowParameters window_parameters ) override { if( !InitializeVulkan( window_parameters ) ) { return false; } // Vertex data if( !Load3DModelFromObjFile( "Data/Models/knot.obj", true, false, false, true, Model ) ) { return false; } InitVkDestroyer( LogicalDevice, VertexBuffer ); if( !CreateBuffer( *LogicalDevice, sizeof( Model.Data[0] ) * Model.Data.size(), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, *VertexBuffer ) ) { return false; } InitVkDestroyer( LogicalDevice, VertexBufferMemory ); if( !AllocateAndBindMemoryObjectToBuffer( PhysicalDevice, *LogicalDevice, *VertexBuffer, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, *VertexBufferMemory ) ) { return false; } if( !UseStagingBufferToUpdateBufferWithDeviceLocalMemoryBound( PhysicalDevice, *LogicalDevice, sizeof( Model.Data[0] ) * Model.Data.size(), &Model.Data[0], *VertexBuffer, 0, 0, VK_ACCESS_VERTEX_ATTRIBUTE_READ_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_VERTEX_INPUT_BIT, GraphicsQueue.Handle, FramesResources.front().CommandBuffer, {} ) ) { return false; } // Staging buffer InitVkDestroyer( LogicalDevice, StagingBuffer ); if( !CreateBuffer( *LogicalDevice, 2 * 16 * sizeof(float), VK_BUFFER_USAGE_TRANSFER_SRC_BIT, *StagingBuffer ) ) { return false; } InitVkDestroyer( LogicalDevice, StagingBufferMemory ); if( !AllocateAndBindMemoryObjectToBuffer( PhysicalDevice, *LogicalDevice, *StagingBuffer, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT, *StagingBufferMemory ) ) { return false; } // Uniform buffer InitVkDestroyer( LogicalDevice, UniformBuffer ); InitVkDestroyer( LogicalDevice, UniformBufferMemory ); if( !CreateUniformBuffer( PhysicalDevice, *LogicalDevice, 2 * 16 * sizeof( float ), VK_BUFFER_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, *UniformBuffer, *UniformBufferMemory ) ) { return false; } if( !UpdateStagingBuffer( true ) ) { return false; } // Descriptor set with uniform buffer VkDescriptorSetLayoutBinding descriptor_set_layout_binding = { 0, // uint32_t binding VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType descriptorType 1, // uint32_t descriptorCount VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlags stageFlags nullptr // const VkSampler * pImmutableSamplers }; InitVkDestroyer( LogicalDevice, DescriptorSetLayout ); if( !CreateDescriptorSetLayout( *LogicalDevice, { descriptor_set_layout_binding }, *DescriptorSetLayout ) ) { return false; } VkDescriptorPoolSize descriptor_pool_size = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType type 1 // uint32_t descriptorCount }; InitVkDestroyer( LogicalDevice, DescriptorPool ); if( !CreateDescriptorPool( *LogicalDevice, false, 1, { descriptor_pool_size }, *DescriptorPool ) ) { return false; } if( !AllocateDescriptorSets( *LogicalDevice, *DescriptorPool, { *DescriptorSetLayout }, DescriptorSets ) ) { return false; } BufferDescriptorInfo buffer_descriptor_update = { DescriptorSets[0], // VkDescriptorSet TargetDescriptorSet 0, // uint32_t TargetDescriptorBinding 0, // uint32_t TargetArrayElement VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // VkDescriptorType TargetDescriptorType { // std::vector<VkDescriptorBufferInfo> BufferInfos { *UniformBuffer, // VkBuffer buffer 0, // VkDeviceSize offset VK_WHOLE_SIZE // VkDeviceSize range } } }; UpdateDescriptorSets( *LogicalDevice, {}, { buffer_descriptor_update }, {}, {} ); // Render pass std::vector<VkAttachmentDescription> attachment_descriptions = { { 0, // VkAttachmentDescriptionFlags flags Swapchain.Format, // VkFormat format VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp VK_ATTACHMENT_STORE_OP_STORE, // VkAttachmentStoreOp storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout VK_IMAGE_LAYOUT_PRESENT_SRC_KHR // VkImageLayout finalLayout }, { 0, // VkAttachmentDescriptionFlags flags DepthFormat, // VkFormat format VK_SAMPLE_COUNT_1_BIT, // VkSampleCountFlagBits samples VK_ATTACHMENT_LOAD_OP_CLEAR, // VkAttachmentLoadOp loadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp storeOp VK_ATTACHMENT_LOAD_OP_DONT_CARE, // VkAttachmentLoadOp stencilLoadOp VK_ATTACHMENT_STORE_OP_DONT_CARE, // VkAttachmentStoreOp stencilStoreOp VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout initialLayout VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // VkImageLayout finalLayout } }; VkAttachmentReference depth_attachment = { 1, // uint32_t attachment VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // VkImageLayout layout }; std::vector<SubpassParameters> subpass_parameters = { { VK_PIPELINE_BIND_POINT_GRAPHICS, // VkPipelineBindPoint PipelineType {}, // std::vector<VkAttachmentReference> InputAttachments { // std::vector<VkAttachmentReference> ColorAttachments { 0, // uint32_t attachment VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout layout } }, {}, // std::vector<VkAttachmentReference> ResolveAttachments &depth_attachment, // VkAttachmentReference const * DepthStencilAttachment {} // std::vector<uint32_t> PreserveAttachments } }; std::vector<VkSubpassDependency> subpass_dependencies = { { VK_SUBPASS_EXTERNAL, // uint32_t srcSubpass 0, // uint32_t dstSubpass VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags srcStageMask VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags dstStageMask VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags dstAccessMask VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags }, { 0, // uint32_t srcSubpass VK_SUBPASS_EXTERNAL, // uint32_t dstSubpass VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, // VkPipelineStageFlags srcStageMask VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, // VkPipelineStageFlags dstStageMask VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags srcAccessMask VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags dstAccessMask VK_DEPENDENCY_BY_REGION_BIT // VkDependencyFlags dependencyFlags } }; InitVkDestroyer( LogicalDevice, RenderPass ); if( !CreateRenderPass( *LogicalDevice, attachment_descriptions, subpass_parameters, subpass_dependencies, *RenderPass ) ) { return false; } // Graphics pipeline InitVkDestroyer( LogicalDevice, PipelineLayout ); if( !CreatePipelineLayout( *LogicalDevice, { *DescriptorSetLayout }, {}, *PipelineLayout ) ) { return false; } std::vector<unsigned char> vertex_shader_spirv; if( !GetBinaryFileContents( "Data/Shaders/11 Lighting/01 Rendering a geometry with vertex diffuse lighting/shader.vert.spv", vertex_shader_spirv ) ) { return false; } VkDestroyer(VkShaderModule) vertex_shader_module; InitVkDestroyer( LogicalDevice, vertex_shader_module ); if( !CreateShaderModule( *LogicalDevice, vertex_shader_spirv, *vertex_shader_module ) ) { return false; } std::vector<unsigned char> fragment_shader_spirv; if( !GetBinaryFileContents( "Data/Shaders/11 Lighting/01 Rendering a geometry with vertex diffuse lighting/shader.frag.spv", fragment_shader_spirv ) ) { return false; } VkDestroyer(VkShaderModule) fragment_shader_module; InitVkDestroyer( LogicalDevice, fragment_shader_module ); if( !CreateShaderModule( *LogicalDevice, fragment_shader_spirv, *fragment_shader_module ) ) { return false; } std::vector<ShaderStageParameters> shader_stage_params = { { VK_SHADER_STAGE_VERTEX_BIT, // VkShaderStageFlagBits ShaderStage *vertex_shader_module, // VkShaderModule ShaderModule "main", // char const * EntryPointName nullptr // VkSpecializationInfo const * SpecializationInfo }, { VK_SHADER_STAGE_FRAGMENT_BIT, // VkShaderStageFlagBits ShaderStage *fragment_shader_module, // VkShaderModule ShaderModule "main", // char const * EntryPointName nullptr // VkSpecializationInfo const * SpecializationInfo } }; std::vector<VkPipelineShaderStageCreateInfo> shader_stage_create_infos; SpecifyPipelineShaderStages( shader_stage_params, shader_stage_create_infos ); std::vector<VkVertexInputBindingDescription> vertex_input_binding_descriptions = { { 0, // uint32_t binding 6 * sizeof( float ), // uint32_t stride VK_VERTEX_INPUT_RATE_VERTEX // VkVertexInputRate inputRate } }; std::vector<VkVertexInputAttributeDescription> vertex_attribute_descriptions = { { 0, // uint32_t location 0, // uint32_t binding VK_FORMAT_R32G32B32_SFLOAT, // VkFormat format 0 // uint32_t offset }, { 1, // uint32_t location 0, // uint32_t binding VK_FORMAT_R32G32B32_SFLOAT, // VkFormat format 3 * sizeof( float ) // uint32_t offset } }; VkPipelineVertexInputStateCreateInfo vertex_input_state_create_info; SpecifyPipelineVertexInputState( vertex_input_binding_descriptions, vertex_attribute_descriptions, vertex_input_state_create_info ); VkPipelineInputAssemblyStateCreateInfo input_assembly_state_create_info; SpecifyPipelineInputAssemblyState( VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, false, input_assembly_state_create_info ); ViewportInfo viewport_infos = { { // std::vector<VkViewport> Viewports { 0.0f, // float x 0.0f, // float y 500.0f, // float width 500.0f, // float height 0.0f, // float minDepth 1.0f // float maxDepth } }, { // std::vector<VkRect2D> Scissors { { // VkOffset2D offset 0, // int32_t x 0 // int32_t y }, { // VkExtent2D extent 500, // uint32_t width 500 // uint32_t height } } } }; VkPipelineViewportStateCreateInfo viewport_state_create_info; SpecifyPipelineViewportAndScissorTestState( viewport_infos, viewport_state_create_info ); VkPipelineRasterizationStateCreateInfo rasterization_state_create_info; SpecifyPipelineRasterizationState( false, false, VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, VK_FRONT_FACE_COUNTER_CLOCKWISE, false, 0.0f, 0.0f, 0.0f, 1.0f, rasterization_state_create_info ); VkPipelineMultisampleStateCreateInfo multisample_state_create_info; SpecifyPipelineMultisampleState( VK_SAMPLE_COUNT_1_BIT, false, 0.0f, nullptr, false, false, multisample_state_create_info ); VkPipelineDepthStencilStateCreateInfo depth_stencil_state_create_info; SpecifyPipelineDepthAndStencilState( true, true, VK_COMPARE_OP_LESS_OR_EQUAL, false, 0.0f, 1.0f, false, {}, {}, depth_stencil_state_create_info ); std::vector<VkPipelineColorBlendAttachmentState> attachment_blend_states = { { false, // VkBool32 blendEnable VK_BLEND_FACTOR_ONE, // VkBlendFactor srcColorBlendFactor VK_BLEND_FACTOR_ONE, // VkBlendFactor dstColorBlendFactor VK_BLEND_OP_ADD, // VkBlendOp colorBlendOp VK_BLEND_FACTOR_ONE, // VkBlendFactor srcAlphaBlendFactor VK_BLEND_FACTOR_ONE, // VkBlendFactor dstAlphaBlendFactor VK_BLEND_OP_ADD, // VkBlendOp alphaBlendOp VK_COLOR_COMPONENT_R_BIT | // VkColorComponentFlags colorWriteMask VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT } }; VkPipelineColorBlendStateCreateInfo blend_state_create_info; SpecifyPipelineBlendState( false, VK_LOGIC_OP_COPY, attachment_blend_states, { 1.0f, 1.0f, 1.0f, 1.0f }, blend_state_create_info ); std::vector<VkDynamicState> dynamic_states = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR }; VkPipelineDynamicStateCreateInfo dynamic_state_create_info; SpecifyPipelineDynamicStates( dynamic_states, dynamic_state_create_info ); VkGraphicsPipelineCreateInfo pipeline_create_info; SpecifyGraphicsPipelineCreationParameters( 0, shader_stage_create_infos, vertex_input_state_create_info, input_assembly_state_create_info, nullptr, &viewport_state_create_info, rasterization_state_create_info, &multisample_state_create_info, &depth_stencil_state_create_info, &blend_state_create_info, &dynamic_state_create_info, *PipelineLayout, *RenderPass, 0, VK_NULL_HANDLE, -1, pipeline_create_info ); std::vector<VkPipeline> pipeline; if( !CreateGraphicsPipelines( *LogicalDevice, { pipeline_create_info }, VK_NULL_HANDLE, pipeline ) ) { return false; } InitVkDestroyer( LogicalDevice, Pipeline ); *Pipeline = pipeline[0]; return true; } virtual bool Draw() override { auto prepare_frame = [&]( VkCommandBuffer command_buffer, uint32_t swapchain_image_index, VkFramebuffer framebuffer ) { if( !BeginCommandBufferRecordingOperation( command_buffer, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, nullptr ) ) { return false; } if( UpdateUniformBuffer ) { UpdateUniformBuffer = false; BufferTransition pre_transfer_transition = { *UniformBuffer, // VkBuffer Buffer VK_ACCESS_UNIFORM_READ_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags NewAccess VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily VK_QUEUE_FAMILY_IGNORED // uint32_t NewQueueFamily }; SetBufferMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, { pre_transfer_transition } ); std::vector<VkBufferCopy> regions = { { 0, // VkDeviceSize srcOffset 0, // VkDeviceSize dstOffset 2 * 16 * sizeof( float ) // VkDeviceSize size } }; CopyDataBetweenBuffers( command_buffer, *StagingBuffer, *UniformBuffer, regions ); BufferTransition post_transfer_transition = { *UniformBuffer, // VkBuffer Buffer VK_ACCESS_TRANSFER_WRITE_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_UNIFORM_READ_BIT, // VkAccessFlags NewAccess VK_QUEUE_FAMILY_IGNORED, // uint32_t CurrentQueueFamily VK_QUEUE_FAMILY_IGNORED // uint32_t NewQueueFamily }; SetBufferMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_VERTEX_SHADER_BIT, { post_transfer_transition } ); } if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) { ImageTransition image_transition_before_drawing = { Swapchain.Images[swapchain_image_index], // VkImage Image VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags NewAccess VK_IMAGE_LAYOUT_UNDEFINED, // VkImageLayout CurrentLayout VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // VkImageLayout NewLayout PresentQueue.FamilyIndex, // uint32_t CurrentQueueFamily GraphicsQueue.FamilyIndex, // uint32_t NewQueueFamily VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect }; SetImageMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, { image_transition_before_drawing } ); } // Drawing BeginRenderPass( command_buffer, *RenderPass, framebuffer, { { 0, 0 }, Swapchain.Size }, { { 0.1f, 0.2f, 0.3f, 1.0f }, { 1.0f, 0 } }, VK_SUBPASS_CONTENTS_INLINE ); VkViewport viewport = { 0.0f, // float x 0.0f, // float y static_cast<float>(Swapchain.Size.width), // float width static_cast<float>(Swapchain.Size.height), // float height 0.0f, // float minDepth 1.0f, // float maxDepth }; SetViewportStateDynamically( command_buffer, 0, { viewport } ); VkRect2D scissor = { { // VkOffset2D offset 0, // int32_t x 0 // int32_t y }, { // VkExtent2D extent Swapchain.Size.width, // uint32_t width Swapchain.Size.height // uint32_t height } }; SetScissorStateDynamically( command_buffer, 0, { scissor } ); BindVertexBuffers( command_buffer, 0, { { *VertexBuffer, 0 } } ); BindDescriptorSets( command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *PipelineLayout, 0, DescriptorSets, {} ); BindPipelineObject( command_buffer, VK_PIPELINE_BIND_POINT_GRAPHICS, *Pipeline ); for( size_t i = 0; i < Model.Parts.size(); ++i ) { DrawGeometry( command_buffer, Model.Parts[i].VertexCount, 1, Model.Parts[i].VertexOffset, 0 ); } EndRenderPass( command_buffer ); if( PresentQueue.FamilyIndex != GraphicsQueue.FamilyIndex ) { ImageTransition image_transition_before_present = { Swapchain.Images[swapchain_image_index], // VkImage Image VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT, // VkAccessFlags CurrentAccess VK_ACCESS_MEMORY_READ_BIT, // VkAccessFlags NewAccess VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout CurrentLayout VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, // VkImageLayout NewLayout GraphicsQueue.FamilyIndex, // uint32_t CurrentQueueFamily PresentQueue.FamilyIndex, // uint32_t NewQueueFamily VK_IMAGE_ASPECT_COLOR_BIT // VkImageAspectFlags Aspect }; SetImageMemoryBarrier( command_buffer, VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, { image_transition_before_present } ); } if( !EndCommandBufferRecordingOperation( command_buffer ) ) { return false; } return true; }; return IncreasePerformanceThroughIncreasingTheNumberOfSeparatelyRenderedFrames( *LogicalDevice, GraphicsQueue.Handle, PresentQueue.Handle, *Swapchain.Handle, Swapchain.Size, Swapchain.ImageViewsRaw, *RenderPass, {}, prepare_frame, FramesResources ); } void OnMouseEvent() { UpdateStagingBuffer( false ); } bool UpdateStagingBuffer( bool force ) { UpdateUniformBuffer = true; static float horizontal_angle = 0.0f; static float vertical_angle = 0.0f; if( MouseState.Buttons[0].IsPressed || force ) { horizontal_angle += 0.5f * MouseState.Position.Delta.X; vertical_angle -= 0.5f * MouseState.Position.Delta.Y; if( vertical_angle > 90.0f ) { vertical_angle = 90.0f; } if( vertical_angle < -90.0f ) { vertical_angle = -90.0f; } Matrix4x4 rotation_matrix = PrepareRotationMatrix( vertical_angle, { 1.0f, 0.0f, 0.0f } ) * PrepareRotationMatrix( horizontal_angle, { 0.0f, -1.0f, 0.0f } ); Matrix4x4 translation_matrix = PrepareTranslationMatrix( 0.0f, 0.0f, -4.0f ); Matrix4x4 model_view_matrix = translation_matrix * rotation_matrix; if( !MapUpdateAndUnmapHostVisibleMemory( *LogicalDevice, *StagingBufferMemory, 0, sizeof( model_view_matrix[0] ) * model_view_matrix.size(), &model_view_matrix[0], true, nullptr ) ) { return false; } Matrix4x4 perspective_matrix = PreparePerspectiveProjectionMatrix( static_cast<float>(Swapchain.Size.width) / static_cast<float>(Swapchain.Size.height), 50.0f, 0.5f, 10.0f ); if( !MapUpdateAndUnmapHostVisibleMemory( *LogicalDevice, *StagingBufferMemory, sizeof( model_view_matrix[0] ) * model_view_matrix.size(), sizeof( perspective_matrix[0] ) * perspective_matrix.size(), &perspective_matrix[0], true, nullptr ) ) { return false; } } return true; } virtual bool Resize() override { if( !CreateSwapchain() ) { return false; } if( IsReady() ) { if( !UpdateStagingBuffer( true ) ) { return false; } } return true; } }; VULKAN_COOKBOOK_SAMPLE_FRAMEWORK( "11/01 - Rendering a geometry with vertex diffuse lighting", 50, 25, 1280, 800, Sample )
Java
# == Schema Information # # Table name: currencies # # id :integer not null, primary key # name :string # abbrev :string # created_at :datetime not null # updated_at :datetime not null # class Currency < ActiveRecord::Base validates :name, :abbrev, presence: true end
Java
shared_examples 'collection::ansible' do include_examples 'python::toolchain' include_examples 'ansible::toolchain' end
Java
export const ic_my_location_twotone = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M13 3.06V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06c-.46-4.17-3.77-7.48-7.94-7.94zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"},"children":[]},{"name":"circle","attribs":{"cx":"12","cy":"12","opacity":".3","r":"2"},"children":[]},{"name":"path","attribs":{"d":"M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"},"children":[]}]};
Java
<div class="form-group fg-float"> <div class="fg-line"> {!! Form::text('name', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('name', 'Name', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::textarea('description', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('description', 'Description', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::text('count', null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('count', 'Count', array('class' => 'fg-label')) !!} </div> <div class="form-group fg-float"> <div class="fg-line"> {!! Form::checkbox('sub_visible', 1, null, array('class' => 'form-control fg-input')) !!} </div> {!! Form::label('sub_visible', 'Visible', array('class' => 'fg-label')) !!} </div> <div class="form-group"> {!! Form::submit($submit_text, array('class' => 'btn btn-primary')) !!} </div>
Java
package exercise.task5_kingsGambitExtended.utils; public class MessegeLogger { public static void log(String message){ System.out.println(message); } }
Java
[![Build Status](https://travis-ci.org/artsy/Artsy-OSSUIFonts.svg?branch=master)](https://travis-ci.org/artsy/Artsy-OSSUIFonts) # Artsy+OSSUIFonts This project contains the fonts and UIFont categories required to make a project with standard artsy design. We cannot include the fonts that we would normally use in a public project, so these are the closest equivilents that are available and have open source-compatible licenses. You can find out more by checking out the websites for [EB Garamond](http://www.georgduffner.at/ebgaramond/index.html) and [TeX Gyre Adventor](http://www.gust.org.pl/projects/e-foundry/tex-gyre). To make it work you have to include in the Applications XX-Info.plist. See [here](https://github.com/artsy/Artsy-OSSUIFonts/blob/master/Example/FontApp/FontApp-Info.plist#L37-L45) for an example. ``` <array> <string>EBGaramond08-Italic.ttf</string> <string>EBGaramond08-Regular.ttf</string> <string>EBGaramond12-Italic.ttf</string> <string>EBGaramond12-Regular.ttf</string> <string>texgyreadventor-regular.ttf</string> </array> ``` ## Usage To run the example project; clone the repo, and run `pod install` from the Example directory first. ## Installation Artsy+OSSUIFonts is available through [CocoaPods](http://cocoapods.org), and the [Artsy Specs Repo](https://github.com/artsy/specs). To install the Specs repo run: pod repo add artsy https://github.com/artsy/Specs.git To install the pod, add following line to your Podfile: pod "Artsy+OSSUIFonts" ## Wrapper Orta, orta.therox@gmail.com ## License The Code itself is MIT. The font license for EB Garamonds is the [SIL Open Fonts License](http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=OFL) The font license for Text Gyre Adventor is the [GUST Font License](http://www.gust.org.pl/projects/e-foundry/index_html#GFL)
Java
<?php /** * Created by Khang Nguyen. * Email: khang.nguyen@banvien.com * Date: 10/3/2017 * Time: 9:33 AM */ ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Tin Đất Đai | Quản lý bài đăng</title> <?php $this->load->view('/admin/common/header-js') ?> <link rel="stylesheet" href="<?=base_url('/admin/css/bootstrap-datepicker.min.css')?>"> </head> <body class="hold-transition skin-blue sidebar-mini"> <div class="wrapper"> <!-- Main Header --> <?php $this->load->view('/admin/common/admin-header')?> <!-- Left side column. contains the logo and sidebar --> <?php $this->load->view('/admin/common/left-menu') ?> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> Quản lý bài đăng <?=isset($user) ? 'của:<b> '.$user->FullName.' - '.$user->Phone.'</b>': ''?> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> Trang chủ</a></li> <li class="active">Quản lý bài đăng</li> </ol> </section> <!-- Main content --> <?php $attributes = array("id" => "frmPost"); echo form_open("admin/product/list", $attributes); ?> <section class="content container-fluid"> <?php if(!empty($message_response)){ echo '<div class="alert alert-success">'; echo '<a href="#" class="close" data-dismiss="alert" aria-label="close" title="close">&times;</a>'; echo $message_response; echo '</div>'; }?> <div class="box"> <div class="box-header"> <h3 class="box-title">Danh sách bài đăng</h3> </div> <!-- /.box-header --> <div class="box-body"> <div class="search-filter"> <div class="row"> <div class="col-sm-6"> <label>Tiêu đề</label> <div class="form-group"> <input type="text" name="searchFor" placeholder="Tìm tiêu đề" class="form-control" id="searchKey"> </div> </div> <div class="col-sm-2"> <label>Số điện thoại</label> <div class="form-group"> <input type="text" name="phoneNumber" class="form-control" id="phoneNumber"> </div> </div> <div class="col-sm-2"> <label>Từ ngày</label> <div class="form-group"> <input type="text" name="postFromDate" class="form-control datepicker" id="fromDate"> </div> </div> <div class="col-sm-2"> <label>Đến ngày</label> <div class="form-group"> <input type="text" name="postToDate" class="form-control datepicker" id="toDate"> </div> </div> <div class="col-sm-2"> <label>Mã tin(ID)</label> <div class="form-group"> <input type="text" name="code" class="form-control" id="code"> </div> </div> <div class="col-sm-3"> <label>Loại tin</label> <div class="form-group"> <label><input id="chb-0" checked="checked" type="radio" name="hasAuthor" value="-1"> Tất cả</label> <label><input id="chb-2" type="radio" name="hasAuthor" value="1"> Chính chủ</label> <label><input id="chb-1" type="radio" name="hasAuthor" value="0"> Crawler</label> </div> </div> <div class="col-sm-4"> <label>Tình trạng</label> <div class="form-group"> <label><input id="st_0" checked="checked" type="radio" name="status" value="-1"> Tất cả</label> <label><input id="st-1" type="radio" name="status" value="1"> Hoạt động</label> <label><input id="st-0" type="radio" name="status" value="0"> Tạm dừng</label> <label><input id="st-2" type="radio" name="status" value="2"> Chờ thanh toán</label> </div> </div> </div> <div class="text-center"> <a class="btn btn-primary" onclick="sendRequest()">Tìm kiếm</a> </div> </div> <div class="row no-margin"> <a class="btn btn-danger" id="deleteMulti">Xóa Nhiều</a> </div> <div class="table-responsive"> <table class="admin-table table table-bordered table-striped"> <thead> <tr> <th><input name="checkAll" value="1" type="checkbox" ></th> <th data-action="sort" data-title="Title" data-direction="ASC"><span>Tiêu đề</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="Status" data-direction="ASC"><span>Status</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="Vip" data-direction="ASC"><span>Loại tin</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="View" data-direction="ASC"><span>Lượt xem</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="PostDate" data-direction="ASC"><span>Ngày đăng</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="ExpireDate" data-direction="ASC"><span>Hết hạn</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="ModifiedDate" data-direction="ASC"><span>Cập nhật</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="CreatedByID" data-direction="ASC"><span>Người đăng</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th data-action="sort" data-title="IpAddress" data-direction="ASC"><span>Ip Address</span><i class="glyphicon glyphicon-triangle-bottom"></i></th> <th></th> </tr> </thead> <tbody> <?php $counter = 1; foreach ($products as $product) { ?> <tr> <td><input name="checkList[]" type="checkbox" value="<?=$product->ProductID?>"></td> <td><a class="vip<?=$product->Vip?>" data-toggle="tooltip" title="<?=$product->Title?>" href="<?=base_url(seo_url($product->Title).'-p').$product->ProductID.'.html'?>"><?=substr_at_middle($product->Title, 60)?></a></td> <td> <?php if($product->Status == ACTIVE){ echo '<span class="label label-success">Show</span>'; }else if($product->Status == PAYMENT_DELAY){ echo '<span class="label label-info">Payment</span>'; } else{ echo '<span class="label label-danger">Hide</span>'; } ?> </td> <td> <select onchange="updateVip('<?=$product->ProductID?>', this.value);"> <option value="0" <?=$product->Vip == 0 ? ' selected' : ''?>>Vip 0</option> <option value="1" <?=$product->Vip == 1 ? ' selected' : ''?>>Vip 1</option> <option value="2" <?=$product->Vip == 2 ? ' selected' : ''?>>Vip 2</option> <option value="3" <?=$product->Vip == 3 ? ' selected' : ''?>>Vip 3</option> <option value="5" <?=$product->Vip == 5 ? ' selected' : ''?>>Thường</option> </select> </td> <td class="text-right"> <?php if(isset($product->FullName)) { ?> <input class="txtView" id="pr-<?=$product->ProductID?>" type="text" value="<?= $product->View?>" onchange="updateView('<?=$product->ProductID?>', this.value);"/> <?php }else{ echo $product->View; } ?> </td> <td><?=date('d/m/Y H:i', strtotime($product->PostDate))?></td> <td><?=date('d/m/Y', strtotime($product->ExpireDate))?></td> <td id="modifiedDate_<?=$product->ProductID?>"><?=date('d/m/Y H:i', strtotime($product->ModifiedDate))?></td> <td><a href="<?=base_url('/admin/product/list.html?createdById='.$product->CreatedByID)?>"><?=$product->FullName?></a> </td> <td><?=$product->IpAddress?></td> <td> <a href="<?=base_url('/admin/product/edit.html?postId='.$product->ProductID)?>" data-toggle="tooltip" title="Chỉnh sửa"><i class="glyphicon glyphicon-edit"></i></a>&nbsp;|&nbsp; <a onclick="pushPostUp('<?=$product->ProductID?>');" data-toggle="tooltip" title="Làm mới tin"><i class="glyphicon glyphicon-refresh"></i></a>&nbsp;|&nbsp; <a class="remove-post" data-post="<?=$product->ProductID?>" data-toggle="tooltip" title="Xóa tin đăng"><i class="glyphicon glyphicon-remove"></i></a> </td> </tr> <?php } ?> </tbody> </table> <div class="text-center"> <?php echo $pagination; ?> </div> </div> </div> </div> </section> <!-- /.content --> <input type="hidden" id="crudaction" name="crudaction"> <input type="hidden" id="productId" name="productId"> <?php echo form_close(); ?> </div> <!-- /.content-wrapper --> <!-- Main Footer --> <?php $this->load->view('/admin/common/admin-footer')?> </div> <!-- ./wrapper --> <!-- REQUIRED JS SCRIPTS --> <!-- jQuery 3 --> <script src="<?=base_url('/admin/js/jquery.min.js')?>"></script> <!-- Bootstrap 3.3.7 --> <script src="<?=base_url('/admin/js/bootstrap.min.js')?>"></script> <!-- AdminLTE App --> <script src="<?=base_url('/admin/js/adminlte.min.js')?>"></script> <script src="<?=base_url('/js/bootbox.min.js')?>"></script> <script src="<?=base_url('/admin/js/bootstrap-datepicker.min.js')?>"></script> <script src="<?=base_url('/admin/js/tindatdai_admin.js')?>"></script> <script type="text/javascript"> var sendRequest = function(){ var searchKey = $('#searchKey').val()||""; var fromDate = $('#fromDate').val()||""; var toDate = $('#toDate').val()||""; var code = $('#code').val()||""; var hasAuthor = $('input[name=hasAuthor]:checked').val(); var status = $('input[name=status]:checked').val(); var phoneNumber = $('#phoneNumber').val()||""; window.location.href = '<?=base_url('admin/product/list.html')?>?query='+searchKey + '&phoneNumber=' + phoneNumber + '&fromDate=' + fromDate + '&toDate=' + toDate + '&hasAuthor=' + hasAuthor + '&code=' + code + '&status=' + status + '&orderField='+curOrderField+'&orderDirection='+curOrderDirection; } var curOrderField, curOrderDirection; $('[data-action="sort"]').on('click', function(e){ curOrderField = $(this).data('title'); curOrderDirection = $(this).data('direction'); sendRequest(); }); $('#searchKey').val(decodeURIComponent(getNamedParameter('query')||"")); $('#fromDate').val(decodeURIComponent(getNamedParameter('fromDate')||"")); $('#toDate').val(decodeURIComponent(getNamedParameter('toDate')||"")); $('#code').val(decodeURIComponent(getNamedParameter('code')||"")); $('#phoneNumber').val(decodeURIComponent(getNamedParameter('phoneNumber')||"")); if(decodeURIComponent(getNamedParameter('hasAuthor')) != null){ $("#chb-" + (parseInt(decodeURIComponent(getNamedParameter('hasAuthor'))) + 1)).prop( "checked", true ); }else{ $("#chb-0").prop( "checked", true ); } if(decodeURIComponent(getNamedParameter('status')) != null){ $("#st-" + (parseInt(decodeURIComponent(getNamedParameter('status'))))).prop( "checked", true ); }else{ $("#st_0").prop( "checked", true ); } var curOrderField = getNamedParameter('orderField')||""; var curOrderDirection = getNamedParameter('orderDirection')||""; var currentSort = $('[data-action="sort"][data-title="'+getNamedParameter('orderField')+'"]'); if(curOrderDirection=="ASC"){ currentSort.attr('data-direction', "DESC").find('i.glyphicon').removeClass('glyphicon-triangle-bottom').addClass('glyphicon-triangle-top active'); }else{ currentSort.attr('data-direction', "ASC").find('i.glyphicon').removeClass('glyphicon-triangle-top').addClass('glyphicon-triangle-bottom active'); } function updateView(productId, val){ $("#pr-" + productId).addClass("process"); jQuery.ajax({ type: "POST", url: '<?=base_url("/Ajax_controller/updateViewForProductIdManual")?>', dataType: 'json', data: {productId: productId, view: val}, success: function(res){ if(res == 'success'){ /*bootbox.alert("Cập nhật thành công");*/ $("#pr-" + productId).addClass("success"); } } }); } function updateVip(productId, val){ jQuery.ajax({ type: "POST", url: '<?=base_url("/Ajax_controller/updateVipPackageForProductId")?>', dataType: 'json', data: {productId: productId, vip: val}, success: function(res){ if(res == 'success'){ bootbox.alert("Cập nhật thành công"); } } }); } function pushPostUp(productId){ jQuery.ajax({ type: "POST", url: '<?=base_url("/admin/ProductManagement_controller/pushPostUp")?>', dataType: 'json', data: {productId: productId}, success: function(res){ if(res == 'success'){ bootbox.alert("Cập nhật thành công"); } } }); } function deleteMultiplePostHandler(){ $("#deleteMulti").click(function(){ var selectedItems = $("input[name='checkList[]']:checked").length; if(selectedItems > 0) { bootbox.confirm("Bạn đã chắc chắn xóa những tin rao này chưa?", function (result) { if (result) { $("#crudaction").val("delete-multiple"); $("#frmPost").submit(); } }); }else{ bootbox.alert("Bạn chưa check chọn tin cần xóa!"); } }); } function deletePostHandler(){ $('.remove-post').click(function(){ var prId = $(this).data('post'); bootbox.confirm("Bạn đã chắc chắn xóa tin rao này chưa?", function(result){ if(result){ $("#productId").val(prId); $("#crudaction").val("delete"); $("#frmPost").submit(); } }); }); } $(document).ready(function(){ deletePostHandler(); deleteMultiplePostHandler(); }); </script> </body> </html>
Java
import Form from 'cerebral-module-forms/Form' import submitForm from './chains/submitForm' import resetForm from './chains/resetForm' import validateForm from './chains/validateForm' export default (options = {}) => { return (module, controller) => { module.addState(Form({ name: { value: '', isRequired: true }, email: { value: '', validations: ['isEmail'], errorMessages: ['Not valid email'], isRequired: true }, password: { value: '', validations: ['equalsField:repeatPassword'], dependsOn: 'simple.repeatPassword', errorMessages: ['Not equal to repeated password'], isRequired: true }, repeatPassword: { value: '', validations: ['equalsField:password'], dependsOn: 'simple.password', errorMessages: ['Not equal to password'], isRequired: true }, address: Form({ street: { value: '' }, postalCode: { value: '', validations: ['isLength:4', 'isNumeric'], errorMessages: ['Has to be length 4', 'Can only contain numbers'] } }) })) module.addSignals({ formSubmitted: submitForm, resetClicked: resetForm, validateFormClicked: validateForm }) } }
Java
namespace GarboDev { using System; using System.Collections.Generic; using System.Text; public partial class Renderer : IRenderer { private Memory memory; private uint[] scanline = new uint[240]; private byte[] blend = new byte[240]; private byte[] windowCover = new byte[240]; private uint[] back = new uint[240 * 160]; //private uint[] front = new uint[240 * 160]; private const uint pitch = 240; // Convenience variable as I use it everywhere, set once in RenderLine private ushort dispCnt; // Window helper variables private byte win0x1, win0x2, win0y1, win0y2; private byte win1x1, win1x2, win1y1, win1y2; private byte win0Enabled, win1Enabled, winObjEnabled, winOutEnabled; private bool winEnabled; private byte blendSource, blendTarget; private byte blendA, blendB, blendY; private int blendType; private int curLine = 0; private static uint[] colorLUT; static Renderer() { colorLUT = new uint[0x10000]; // Pre-calculate the color LUT for (uint i = 0; i <= 0xFFFF; i++) { uint r = (i & 0x1FU); uint g = (i & 0x3E0U) >> 5; uint b = (i & 0x7C00U) >> 10; r = (r << 3) | (r >> 2); g = (g << 3) | (g >> 2); b = (b << 3) | (b >> 2); colorLUT[i] = (r << 16) | (g << 8) | b; } } public Memory Memory { set { this.memory = value; } } public void Initialize(object data) { } public void Reset() { } public uint[] ShowFrame() { //Array.Copy(this.back, this.front, this.front.Length); //return this.front; return this.back; } public void RenderLine(int line) { this.curLine = line; // Render the line this.dispCnt = Memory.ReadU16(this.memory.IORam, Memory.DISPCNT); if ((this.dispCnt & (1 << 7)) != 0) { uint bgColor = Renderer.GbaTo32((ushort)0x7FFF); for (int i = 0; i < 240; i++) this.scanline[i] = bgColor; } else { this.winEnabled = false; if ((this.dispCnt & (1 << 13)) != 0) { // Calculate window 0 information ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN0V); this.win0y1 = (byte)(winy >> 8); this.win0y2 = (byte)(winy & 0xff); ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN0H); this.win0x1 = (byte)(winx >> 8); this.win0x2 = (byte)(winx & 0xff); if (this.win0x2 > 240 || this.win0x1 > this.win0x2) { this.win0x2 = 240; } if (this.win0y2 > 160 || this.win0y1 > this.win0y2) { this.win0y2 = 160; } this.win0Enabled = this.memory.IORam[Memory.WININ]; this.winEnabled = true; } if ((this.dispCnt & (1 << 14)) != 0) { // Calculate window 1 information ushort winy = Memory.ReadU16(this.memory.IORam, Memory.WIN1V); this.win1y1 = (byte)(winy >> 8); this.win1y2 = (byte)(winy & 0xff); ushort winx = Memory.ReadU16(this.memory.IORam, Memory.WIN1H); this.win1x1 = (byte)(winx >> 8); this.win1x2 = (byte)(winx & 0xff); if (this.win1x2 > 240 || this.win1x1 > this.win1x2) { this.win1x2 = 240; } if (this.win1y2 > 160 || this.win1y1 > this.win1y2) { this.win1y2 = 160; } this.win1Enabled = this.memory.IORam[Memory.WININ + 1]; this.winEnabled = true; } if ((this.dispCnt & (1 << 15)) != 0 && (this.dispCnt & (1 << 12)) != 0) { // Object windows are enabled this.winObjEnabled = this.memory.IORam[Memory.WINOUT + 1]; this.winEnabled = true; } if (this.winEnabled) { this.winOutEnabled = this.memory.IORam[Memory.WINOUT]; } // Calculate blending information ushort bldcnt = Memory.ReadU16(this.memory.IORam, Memory.BLDCNT); this.blendType = (bldcnt >> 6) & 0x3; this.blendSource = (byte)(bldcnt & 0x3F); this.blendTarget = (byte)((bldcnt >> 8) & 0x3F); ushort bldalpha = Memory.ReadU16(this.memory.IORam, Memory.BLDALPHA); this.blendA = (byte)(bldalpha & 0x1F); if (this.blendA > 0x10) this.blendA = 0x10; this.blendB = (byte)((bldalpha >> 8) & 0x1F); if (this.blendB > 0x10) this.blendB = 0x10; this.blendY = (byte)(this.memory.IORam[Memory.BLDY] & 0x1F); if (this.blendY > 0x10) this.blendY = 0x10; switch (this.dispCnt & 0x7) { case 0: this.RenderMode0Line(); break; case 1: this.RenderMode1Line(); break; case 2: this.RenderMode2Line(); break; case 3: this.RenderMode3Line(); break; case 4: this.RenderMode4Line(); break; case 5: this.RenderMode5Line(); break; } } Array.Copy(this.scanline, 0, this.back, this.curLine * Renderer.pitch, Renderer.pitch); } private void DrawBackdrop() { byte[] palette = this.memory.PaletteRam; // Initialize window coverage buffer if neccesary if (this.winEnabled) { for (int i = 0; i < 240; i++) { this.windowCover[i] = this.winOutEnabled; } if ((this.dispCnt & (1 << 15)) != 0) { // Sprite window this.DrawSpriteWindows(); } if ((this.dispCnt & (1 << 14)) != 0) { // Window 1 if (this.curLine >= this.win1y1 && this.curLine < this.win1y2) { for (int i = this.win1x1; i < this.win1x2; i++) { this.windowCover[i] = this.win1Enabled; } } } if ((this.dispCnt & (1 << 13)) != 0) { // Window 0 if (this.curLine >= this.win0y1 && this.curLine < this.win0y2) { for (int i = this.win0x1; i < this.win0x2; i++) { this.windowCover[i] = this.win0Enabled; } } } } // Draw backdrop first uint bgColor = Renderer.GbaTo32((ushort)(palette[0] | (palette[1] << 8))); uint modColor = bgColor; if (this.blendType == 2 && (this.blendSource & (1 << 5)) != 0) { // Brightness increase uint r = bgColor & 0xFF; uint g = (bgColor >> 8) & 0xFF; uint b = (bgColor >> 16) & 0xFF; r = r + (((0xFF - r) * this.blendY) >> 4); g = g + (((0xFF - g) * this.blendY) >> 4); b = b + (((0xFF - b) * this.blendY) >> 4); modColor = r | (g << 8) | (b << 16); } else if (this.blendType == 3 && (this.blendSource & (1 << 5)) != 0) { // Brightness decrease uint r = bgColor & 0xFF; uint g = (bgColor >> 8) & 0xFF; uint b = (bgColor >> 16) & 0xFF; r = r - ((r * this.blendY) >> 4); g = g - ((g * this.blendY) >> 4); b = b - ((b * this.blendY) >> 4); modColor = r | (g << 8) | (b << 16); } if (this.winEnabled) { for (int i = 0; i < 240; i++) { if ((this.windowCover[i] & (1 << 5)) != 0) { this.scanline[i] = modColor; } else { this.scanline[i] = bgColor; } this.blend[i] = 1 << 5; } } else { for (int i = 0; i < 240; i++) { this.scanline[i] = modColor; this.blend[i] = 1 << 5; } } } private void RenderTextBg(int bg) { if (this.winEnabled) { switch (this.blendType) { case 0: this.RenderTextBgWindow(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBlend(bg); else this.RenderTextBgWindow(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBrightInc(bg); else this.RenderTextBgWindow(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgWindowBrightDec(bg); else this.RenderTextBgWindow(bg); break; } } else { switch (this.blendType) { case 0: this.RenderTextBgNormal(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBlend(bg); else this.RenderTextBgNormal(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBrightInc(bg); else this.RenderTextBgNormal(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderTextBgBrightDec(bg); else this.RenderTextBgNormal(bg); break; } } } private void RenderRotScaleBg(int bg) { if (this.winEnabled) { switch (this.blendType) { case 0: this.RenderRotScaleBgWindow(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBlend(bg); else this.RenderRotScaleBgWindow(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBrightInc(bg); else this.RenderRotScaleBgWindow(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgWindowBrightDec(bg); else this.RenderRotScaleBgWindow(bg); break; } } else { switch (this.blendType) { case 0: this.RenderRotScaleBgNormal(bg); break; case 1: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBlend(bg); else this.RenderRotScaleBgNormal(bg); break; case 2: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBrightInc(bg); else this.RenderRotScaleBgNormal(bg); break; case 3: if ((this.blendSource & (1 << bg)) != 0) this.RenderRotScaleBgBrightDec(bg); else this.RenderRotScaleBgNormal(bg); break; } } } private void DrawSprites(int pri) { if (this.winEnabled) { switch (this.blendType) { case 0: this.DrawSpritesWindow(pri); break; case 1: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBlend(pri); else this.DrawSpritesWindow(pri); break; case 2: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBrightInc(pri); else this.DrawSpritesWindow(pri); break; case 3: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesWindowBrightDec(pri); else this.DrawSpritesWindow(pri); break; } } else { switch (this.blendType) { case 0: this.DrawSpritesNormal(pri); break; case 1: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBlend(pri); else this.DrawSpritesNormal(pri); break; case 2: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBrightInc(pri); else this.DrawSpritesNormal(pri); break; case 3: if ((this.blendSource & (1 << 4)) != 0) this.DrawSpritesBrightDec(pri); else this.DrawSpritesNormal(pri); break; } } } private void RenderMode0Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { for (int i = 3; i >= 0; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderTextBg(i); } } } this.DrawSprites(pri); } } private void RenderMode1Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { if ((this.dispCnt & (1 << (8 + 2))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); if ((bgcnt & 0x3) == pri) { this.RenderRotScaleBg(2); } } for (int i = 1; i >= 0; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderTextBg(i); } } } this.DrawSprites(pri); } } private void RenderMode2Line() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); for (int pri = 3; pri >= 0; pri--) { for (int i = 3; i >= 2; i--) { if ((this.dispCnt & (1 << (8 + i))) != 0) { ushort bgcnt = Memory.ReadU16(this.memory.IORam, Memory.BG0CNT + 0x2 * (uint)i); if ((bgcnt & 0x3) == pri) { this.RenderRotScaleBg(i); } } } this.DrawSprites(pri); } } private void RenderMode3Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160) { int curIdx = ((ay * 240) + ax) * 2; this.scanline[i] = Renderer.GbaTo32((ushort)(vram[curIdx] | (vram[curIdx + 1] << 8))); this.blend[i] = blendMaskType; } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void RenderMode4Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int baseIdx = 0; if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx = 0xA000; int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 240 && ay >= 0 && ay < 160) { int lookup = vram[baseIdx + (ay * 240) + ax]; if (lookup != 0) { this.scanline[i] = Renderer.GbaTo32((ushort)(palette[lookup * 2] | (palette[lookup * 2 + 1] << 8))); this.blend[i] = blendMaskType; } } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void RenderMode5Line() { ushort bg2Cnt = Memory.ReadU16(this.memory.IORam, Memory.BG2CNT); byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; this.DrawBackdrop(); byte blendMaskType = (byte)(1 << 2); int bgPri = bg2Cnt & 0x3; for (int pri = 3; pri > bgPri; pri--) { this.DrawSprites(pri); } if ((this.dispCnt & (1 << 10)) != 0) { // Background enabled, render it int baseIdx = 0; if ((this.dispCnt & (1 << 4)) == 1 << 4) baseIdx += 160 * 128 * 2; int x = this.memory.Bgx[0]; int y = this.memory.Bgy[0]; short dx = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PA); short dy = (short)Memory.ReadU16(this.memory.IORam, Memory.BG2PC); for (int i = 0; i < 240; i++) { int ax = ((int)x) >> 8; int ay = ((int)y) >> 8; if (ax >= 0 && ax < 160 && ay >= 0 && ay < 128) { int curIdx = (int)(ay * 160 + ax) * 2; this.scanline[i] = Renderer.GbaTo32((ushort)(vram[baseIdx + curIdx] | (vram[baseIdx + curIdx + 1] << 8))); this.blend[i] = blendMaskType; } x += dx; y += dy; } } for (int pri = bgPri; pri >= 0; pri--) { this.DrawSprites(pri); } } private void DrawSpriteWindows() { byte[] palette = this.memory.PaletteRam; byte[] vram = this.memory.VideoRam; // OBJ must be enabled in this.dispCnt if ((this.dispCnt & (1 << 12)) == 0) return; for (int oamNum = 127; oamNum >= 0; oamNum--) { ushort attr0 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 0); // Not an object window, so continue if (((attr0 >> 10) & 3) != 2) continue; ushort attr1 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 2); ushort attr2 = this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(oamNum * 8) + 4); int x = attr1 & 0x1FF; int y = attr0 & 0xFF; int width = -1, height = -1; switch ((attr0 >> 14) & 3) { case 0: // Square switch ((attr1 >> 14) & 3) { case 0: width = 8; height = 8; break; case 1: width = 16; height = 16; break; case 2: width = 32; height = 32; break; case 3: width = 64; height = 64; break; } break; case 1: // Horizontal Rectangle switch ((attr1 >> 14) & 3) { case 0: width = 16; height = 8; break; case 1: width = 32; height = 8; break; case 2: width = 32; height = 16; break; case 3: width = 64; height = 32; break; } break; case 2: // Vertical Rectangle switch ((attr1 >> 14) & 3) { case 0: width = 8; height = 16; break; case 1: width = 8; height = 32; break; case 2: width = 16; height = 32; break; case 3: width = 32; height = 64; break; } break; } // Check double size flag here int rwidth = width, rheight = height; if ((attr0 & (1 << 8)) != 0) { // Rot-scale on if ((attr0 & (1 << 9)) != 0) { rwidth *= 2; rheight *= 2; } } else { // Invalid sprite if ((attr0 & (1 << 9)) != 0) width = -1; } if (width == -1) { // Invalid sprite continue; } // Y clipping if (y > ((y + rheight) & 0xff)) { if (this.curLine >= ((y + rheight) & 0xff) && !(y < this.curLine)) continue; } else { if (this.curLine < y || this.curLine >= ((y + rheight) & 0xff)) continue; } int scale = 1; if ((attr0 & (1 << 13)) != 0) scale = 2; int spritey = this.curLine - y; if (spritey < 0) spritey += 256; if ((attr0 & (1 << 8)) == 0) { if ((attr1 & (1 << 13)) != 0) spritey = (height - 1) - spritey; int baseSprite; if ((this.dispCnt & (1 << 6)) != 0) { // 1 dimensional baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * (width / 8)) * scale; } else { // 2 dimensional baseSprite = (attr2 & 0x3FF) + ((spritey / 8) * 0x20); } int baseInc = scale; if ((attr1 & (1 << 12)) != 0) { baseSprite += ((width / 8) * scale) - scale; baseInc = -baseInc; } if ((attr0 & (1 << 13)) != 0) { // 256 colors for (int i = x; i < x + width; i++) { if ((i & 0x1ff) < 240) { int tx = (i - x) & 7; if ((attr1 & (1 << 12)) != 0) tx = 7 - tx; int curIdx = baseSprite * 32 + ((spritey & 7) * 8) + tx; int lookup = vram[0x10000 + curIdx]; if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } if (((i - x) & 7) == 7) baseSprite += baseInc; } } else { // 16 colors int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2); for (int i = x; i < x + width; i++) { if ((i & 0x1ff) < 240) { int tx = (i - x) & 7; if ((attr1 & (1 << 12)) != 0) tx = 7 - tx; int curIdx = baseSprite * 32 + ((spritey & 7) * 4) + (tx / 2); int lookup = vram[0x10000 + curIdx]; if ((tx & 1) == 0) { lookup &= 0xf; } else { lookup >>= 4; } if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } if (((i - x) & 7) == 7) baseSprite += baseInc; } } } else { int rotScaleParam = (attr1 >> 9) & 0x1F; short dx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x6); short dmx = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0xE); short dy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x16); short dmy = (short)this.memory.ReadU16Debug(Memory.OAM_BASE + (uint)(rotScaleParam * 8 * 4) + 0x1E); int cx = rwidth / 2; int cy = rheight / 2; int baseSprite = attr2 & 0x3FF; int pitch; if ((this.dispCnt & (1 << 6)) != 0) { // 1 dimensional pitch = (width / 8) * scale; } else { // 2 dimensional pitch = 0x20; } short rx = (short)((dmx * (spritey - cy)) - (cx * dx) + (width << 7)); short ry = (short)((dmy * (spritey - cy)) - (cx * dy) + (height << 7)); // Draw a rot/scale sprite if ((attr0 & (1 << 13)) != 0) { // 256 colors for (int i = x; i < x + rwidth; i++) { int tx = rx >> 8; int ty = ry >> 8; if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height) { int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 8) + (tx & 7); int lookup = vram[0x10000 + curIdx]; if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } rx += dx; ry += dy; } } else { // 16 colors int palIdx = 0x200 + (((attr2 >> 12) & 0xF) * 16 * 2); for (int i = x; i < x + rwidth; i++) { int tx = rx >> 8; int ty = ry >> 8; if ((i & 0x1ff) < 240 && tx >= 0 && tx < width && ty >= 0 && ty < height) { int curIdx = (baseSprite + ((ty / 8) * pitch) + ((tx / 8) * scale)) * 32 + ((ty & 7) * 4) + ((tx & 7) / 2); int lookup = vram[0x10000 + curIdx]; if ((tx & 1) == 0) { lookup &= 0xf; } else { lookup >>= 4; } if (lookup != 0) { this.windowCover[i & 0x1ff] = this.winObjEnabled; } } rx += dx; ry += dy; } } } } } public static uint GbaTo32(ushort color) { // more accurate, but slower :( // return colorLUT[color]; return ((color & 0x1FU) << 19) | ((color & 0x3E0U) << 6) | ((color & 0x7C00U) >> 7); } } }
Java
--- layout: page title: Green Storm Tech Executive Retreat date: 2016-05-24 author: Austin Dixon tags: weekly links, java status: published summary: Class aptent taciti sociosqu ad litora torquent per. banner: images/banner/leisure-04.jpg booking: startDate: 11/11/2019 endDate: 11/13/2019 ctyhocn: GXYCOHX groupCode: GSTER published: true --- Donec fringilla libero sit amet arcu ullamcorper, a tincidunt turpis facilisis. Morbi blandit justo eget elit rutrum, faucibus dapibus nunc vulputate. Sed placerat vel diam eget suscipit. Nulla tempus turpis nec nulla gravida, at porta quam tempus. Cras efficitur pretium rutrum. Phasellus tellus lectus, blandit ut purus vel, egestas vulputate lectus. Suspendisse mi odio, volutpat sit amet libero eu, gravida maximus diam. Vestibulum vulputate elit id lacus porttitor semper. Maecenas libero velit, faucibus et convallis quis, dignissim at neque. Donec eget gravida risus. Sed odio enim, maximus ac sagittis vitae, ornare nec nisl. Vivamus non augue eget sapien aliquam fermentum. Praesent dictum tellus a metus tristique, a feugiat libero semper. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; * Sed ut sem non nibh venenatis aliquam sit amet non mauris * Etiam sed purus tempor, vestibulum felis ultrices, malesuada nisl * Nullam eget lorem mattis, condimentum mauris quis, interdum nisl. Cras non odio et tellus consequat faucibus. Nulla id porttitor dui. Nulla sed turpis quis sem elementum pharetra et sed diam. Nam nec turpis nec dolor convallis scelerisque quis in metus. Quisque a elementum elit. Phasellus sit amet ornare justo. Nulla eget ex ac eros blandit bibendum. Nulla sed tincidunt velit. Pellentesque et ligula odio. Aenean a orci quis tortor tristique egestas. Integer ac venenatis nulla, eget pulvinar mi. Vestibulum erat turpis, efficitur sed ligula eu, iaculis tincidunt lacus. Aliquam id massa sit amet enim porttitor auctor.
Java
package models import java.util.UUID import play.api.db.slick.Config.driver.simple._ import org.joda.time.DateTime import com.github.tototoshi.slick.HsqldbJodaSupport._ case class ClientGrantType( clientId: String, grantTypeId: Int ) extends Model class ClientGrantTypes(tag: Tag) extends Table[ClientGrantType](tag, "CLIENT_GRANT_TYPES") { def clientId = column[String]("CLIENT_ID") def grantTypeId = column[Int]("GRANT_TYPE_ID") def * = (clientId, grantTypeId) <> (ClientGrantType.tupled, ClientGrantType.unapply) val pk = primaryKey("PK_CLIENT_GRANT_TYPE", (clientId, grantTypeId)) } object ClientGrantTypes extends BaseSlickTrait[ClientGrantType] { override protected def model = TableQueries.clientGrantTypes }
Java
<?php $data = array ( 0 => array ( 'id' => '3', 'name' => '三国杀', 'desc' => '三国演义', 'parent_id' => '0', 'has_child' => '0', 'is_show' => '0', 'level' => '1', 'type' => '0', 'sort' => '0', ), ); ?>
Java
<?php namespace AppBundle\Controller; use AppBundle\Entity\BillingAddress; use AppBundle\Entity\ShippingAddress; use AppBundle\Form\BillingAddressFormType; use AppBundle\Form\ShippingAddressFormType; use AppBundle\Form\ShippingMethodFormType; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; class CheckoutController extends Controller { /** * @Route("/checkout/billing",name="billing-address") * */ public function billingAddressAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $billingAddress = new BillingAddress(); $billingAddress->setUser($user); $billingAddress->setFirstName($user->getFirstName()); $billingAddress->setLastName($user->getLastName()); $billingAddress->setEmailAddress($user->getUserName()); $form = $this->createForm(BillingAddressFormType::class, $billingAddress); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $billingAddress = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($billingAddress); $em->flush(); return $this->redirectToRoute('shipping-address'); } return $this->render(':partials:checkout-billing.htm.twig', [ 'billingAddressForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/shipping",name="shipping-address") * */ public function shippingAddressAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $shippingAddress = new ShippingAddress(); $shippingAddress->setUser($user); $shippingAddress->setFirstName($user->getFirstName()); $shippingAddress->setLastName($user->getLastName()); $shippingAddress->setEmailAddress($user->getUserName()); $form = $this->createForm(ShippingAddressFormType::class, $shippingAddress); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $shippingAddress = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($shippingAddress); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-shipping-address.htm.twig', [ 'shippingAddressForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/shipping-method",name="shipping-method") * */ public function shippingMethodAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $shippingAddress = new ShippingAddress(); $shippingAddress->setUser($user); $form = $this->createForm(ShippingMethodFormType::class); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $category = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-shipping-method.htm.twig', [ 'shippingMethodForm' => $form->createView(), 'cart' => $cart[0] ]); } /** * @Route("/checkout/payment",name="payment") * */ public function paymentAction(Request $request) { $user = $this->get('security.token_storage')->getToken()->getUser(); $em = $this->getDoctrine()->getManager(); $cart = $em->getRepository('AppBundle:Cart') ->findMyCart($user); $form = $this->createForm(ShippingAddressFormType::class); //only handles data on POST $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $category = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($category); $em->flush(); return $this->redirectToRoute('shipping-method'); } return $this->render(':partials:checkout-pay.htm.twig', [ 'paymentForm' => $form->createView(), 'cart' => $cart[0] ]); } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MVCAngularJS.Aplicacao")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("MVCAngularJS.Aplicacao")] [assembly: AssemblyCopyright("Copyright © Microsoft 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("99fa9143-c9b1-4f28-ab07-79cb1b49c950")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Java
<?php declare(strict_types=1); /** * This file is part of phpDocumentor. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * @link http://phpdoc.org */ namespace phpDocumentor\Descriptor; use Mockery\Adapter\Phpunit\MockeryTestCase; use stdClass; /** * Tests the functionality for the Collection class. * * @coversDefaultClass \phpDocumentor\Descriptor\Collection */ final class CollectionTest extends MockeryTestCase { /** @var Collection $fixture */ private $fixture; /** * Creates a new (empty) fixture object. */ protected function setUp() : void { $this->fixture = new Collection(); } /** * @covers ::__construct */ public function testInitialize() : void { $fixture = new Collection(); $this->assertEmpty($fixture->getAll()); } /** * @covers ::__construct */ public function testInitializeWithExistingArray() : void { $expected = [1, 2]; $fixture = new Collection($expected); $this->assertEquals($expected, $fixture->getAll()); } /** * @covers ::add */ public function testAddNewItem() : void { $expected = ['abc']; $expectedSecondRun = ['abc', 'def']; $this->fixture->add('abc'); $this->assertEquals($expected, $this->fixture->getAll()); $this->fixture->add('def'); $this->assertEquals($expectedSecondRun, $this->fixture->getAll()); } /** * @covers ::set * @covers ::offsetSet */ public function testSetItemsWithKey() : void { $expected = ['z' => 'abc']; $expectedSecondRun = ['z' => 'abc', 'y' => 'def']; $this->assertEquals([], $this->fixture->getAll()); $this->fixture->set('z', 'abc'); $this->assertEquals($expected, $this->fixture->getAll()); $this->fixture->set('y', 'def'); $this->assertEquals($expectedSecondRun, $this->fixture->getAll()); } /** * @covers ::set */ public function testSetItemsWithEmptyKeyShouldThrowException() : void { $this->expectException('InvalidArgumentException'); $this->fixture->set('', 'abc'); } /** * @covers ::offsetSet */ public function testSetItemsUsingOffsetSetWithEmptyKeyShouldThrowException() : void { $this->expectException('InvalidArgumentException'); $this->fixture->offsetSet('', 'abc'); } /** * @covers ::get * @covers ::__get * @covers ::offsetGet */ public function testRetrievalOfItems() : void { $this->fixture['a'] = 'abc'; $this->assertEquals('abc', $this->fixture->__get('a')); $this->assertEquals('abc', $this->fixture['a']); $this->assertEquals('abc', $this->fixture->get('a')); $this->assertCount(1, $this->fixture); $this->assertEquals('def', $this->fixture->fetch(1, 'def')); $this->assertCount(2, $this->fixture); } /** * @covers ::getAll */ public function testRetrieveAllItems() : void { $this->fixture['a'] = 'abc'; $this->assertSame(['a' => 'abc'], $this->fixture->getAll()); } /** * @covers ::getIterator */ public function testGetIterator() : void { $this->fixture['a'] = 'abc'; $this->assertInstanceOf('ArrayIterator', $this->fixture->getIterator()); $this->assertSame(['a' => 'abc'], $this->fixture->getIterator()->getArrayCopy()); } /** * @covers ::count * @covers ::offsetUnset */ public function testCountReturnsTheNumberOfElements() : void { $this->assertCount(0, $this->fixture); $this->assertEquals(0, $this->fixture->count()); $this->fixture[0] = 'abc'; $this->assertCount(1, $this->fixture); $this->assertEquals(1, $this->fixture->count()); $this->fixture[1] = 'def'; $this->assertCount(2, $this->fixture); $this->assertEquals(2, $this->fixture->count()); unset($this->fixture[0]); $this->assertCount(1, $this->fixture); $this->assertEquals(1, $this->fixture->count()); } /** * @covers ::clear */ public function testClearingTheCollection() : void { $this->fixture[1] = 'a'; $this->fixture[2] = 'b'; $this->assertCount(2, $this->fixture); $this->fixture->clear(); $this->assertCount(0, $this->fixture); } /** * @covers ::offsetExists */ public function testIfExistingElementsAreDetected() : void { $this->assertArrayNotHasKey(0, $this->fixture); $this->assertFalse($this->fixture->offsetExists(0)); $this->fixture[0] = 'abc'; $this->assertArrayHasKey(0, $this->fixture); $this->assertTrue($this->fixture->offsetExists(0)); } /** * @covers ::merge */ public function testIfAfterMergeCollectionContainsAllItems() : void { $expected = [0 => 'a', 1 => 'b', 2 => 'c']; $this->fixture[1] = 'a'; $this->fixture[2] = 'b'; $collection2 = new Collection(); $collection2[4] = 'c'; $result = $this->fixture->merge($collection2); $this->assertSame($expected, $result->getAll()); } /** * @covers ::filter */ public function testFilterReturnsOnlyInstancesOfCertainType() : void { $expected = [0 => new stdClass()]; $this->fixture[0] = new stdClass(); $this->fixture[1] = false; $this->fixture[2] = 'string'; $result = $this->fixture->filter(stdClass::class)->getAll(); $this->assertEquals($expected, $result); } }
Java
"use strict"; define("ace/snippets/scala", ["require", "exports", "module"], function (require, exports, module) { "use strict"; exports.snippetText = undefined; exports.scope = "scala"; });
Java
<?php /** * Helper. * * @copyright Ralf Koester (RK) * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License * @author Ralf Koester <ralf@familie-koester.de>. * @link http://k62.de * @link http://zikula.org * @version Generated by ModuleStudio (https://modulestudio.de). */ namespace RK\HelperModule\Controller\Base; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Zikula\Core\Controller\AbstractController; use Zikula\Core\Response\PlainResponse; /** * Controller for external calls base class. */ abstract class AbstractExternalController extends AbstractController { /** * Displays one item of a certain object type using a separate template for external usages. * * @param Request $request The current request * @param string $objectType The currently treated object type * @param int $id Identifier of the entity to be shown * @param string $source Source of this call (contentType or scribite) * @param string $displayMode Display mode (link or embed) * * @return string Desired data output */ public function displayAction(Request $request, $objectType, $id, $source, $displayMode) { $controllerHelper = $this->get('rk_helper_module.controller_helper'); $contextArgs = ['controller' => 'external', 'action' => 'display']; if (!in_array($objectType, $controllerHelper->getObjectTypes('controllerAction', $contextArgs))) { $objectType = $controllerHelper->getDefaultObjectType('controllerAction', $contextArgs); } $component = 'RKHelperModule:' . ucfirst($objectType) . ':'; if (!$this->hasPermission($component, $id . '::', ACCESS_READ)) { return ''; } $entityFactory = $this->get('rk_helper_module.entity_factory'); $repository = $entityFactory->getRepository($objectType); // assign object data fetched from the database $entity = $repository->selectById($id); if (null === $entity) { return new Response($this->__('No such item.')); } $template = $request->query->has('template') ? $request->query->get('template', null) : null; if (null === $template || $template == '') { $template = 'display.html.twig'; } $templateParameters = [ 'objectType' => $objectType, 'source' => $source, $objectType => $entity, 'displayMode' => $displayMode ]; $contextArgs = ['controller' => 'external', 'action' => 'display']; $templateParameters = $this->get('rk_helper_module.controller_helper')->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs); return $this->render('@RKHelperModule/External/' . ucfirst($objectType) . '/' . $template, $templateParameters); } /** * Popup selector for Scribite plugins. * Finds items of a certain object type. * * @param Request $request The current request * @param string $objectType The object type * @param string $editor Name of used Scribite editor * @param string $sort Sorting field * @param string $sortdir Sorting direction * @param int $pos Current pager position * @param int $num Amount of entries to display * * @return output The external item finder page * * @throws AccessDeniedException Thrown if the user doesn't have required permissions */ public function finderAction(Request $request, $objectType, $editor, $sort, $sortdir, $pos = 1, $num = 0) { $assetHelper = $this->get('zikula_core.common.theme.asset_helper'); $cssAssetBag = $this->get('zikula_core.common.theme.assets_css'); $cssAssetBag->add($assetHelper->resolve('@RKHelperModule:css/style.css')); $activatedObjectTypes = $this->getVar('enabledFinderTypes', []); if (!in_array($objectType, $activatedObjectTypes)) { if (!count($activatedObjectTypes)) { throw new AccessDeniedException(); } // redirect to first valid object type $redirectUrl = $this->get('router')->generate('rkhelpermodule_external_finder', ['objectType' => array_shift($activatedObjectTypes), 'editor' => $editor]); return new RedirectResponse($redirectUrl); } if (!$this->hasPermission('RKHelperModule:' . ucfirst($objectType) . ':', '::', ACCESS_COMMENT)) { throw new AccessDeniedException(); } if (empty($editor) || !in_array($editor, ['ckeditor', 'quill', 'summernote', 'tinymce'])) { return new Response($this->__('Error: Invalid editor context given for external controller action.')); } $repository = $this->get('rk_helper_module.entity_factory')->getRepository($objectType); if (empty($sort) || !in_array($sort, $repository->getAllowedSortingFields())) { $sort = $repository->getDefaultSortingField(); } $sdir = strtolower($sortdir); if ($sdir != 'asc' && $sdir != 'desc') { $sdir = 'asc'; } // the current offset which is used to calculate the pagination $currentPage = (int) $pos; // the number of items displayed on a page for pagination $resultsPerPage = (int) $num; if ($resultsPerPage == 0) { $resultsPerPage = $this->getVar('pageSize', 20); } $templateParameters = [ 'editorName' => $editor, 'objectType' => $objectType, 'sort' => $sort, 'sortdir' => $sdir, 'currentPage' => $currentPage, 'onlyImages' => false, 'imageField' => '' ]; $searchTerm = ''; $formOptions = [ 'object_type' => $objectType, 'editor_name' => $editor ]; $form = $this->createForm('RK\HelperModule\Form\Type\Finder\\' . ucfirst($objectType) . 'FinderType', $templateParameters, $formOptions); if ($form->handleRequest($request)->isValid()) { $formData = $form->getData(); $templateParameters = array_merge($templateParameters, $formData); $currentPage = $formData['currentPage']; $resultsPerPage = $formData['num']; $sort = $formData['sort']; $sdir = $formData['sortdir']; $searchTerm = $formData['q']; $templateParameters['onlyImages'] = isset($formData['onlyImages']) ? (bool)$formData['onlyImages'] : false; $templateParameters['imageField'] = isset($formData['imageField']) ? $formData['imageField'] : ''; } $where = ''; $orderBy = $sort . ' ' . $sdir; $qb = $repository->getListQueryBuilder($where, $orderBy); if (true === $templateParameters['onlyImages'] && $templateParameters['imageField'] != '') { $imageField = $templateParameters['imageField']; $orX = $qb->expr()->orX(); foreach (['gif', 'jpg', 'jpeg', 'jpe', 'png', 'bmp'] as $imageExtension) { $orX->add($qb->expr()->like('tbl.' . $imageField, $qb->expr()->literal('%.' . $imageExtension))); } $qb->andWhere($orX); } if ($searchTerm != '') { $qb = $this->get('rk_helper_module.collection_filter_helper')->addSearchFilter($objectType, $qb, $searchTerm); } $query = $repository->getQueryFromBuilder($qb); list($entities, $objectCount) = $repository->retrieveCollectionResult($query, true); $templateParameters['items'] = $entities; $templateParameters['finderForm'] = $form->createView(); $contextArgs = ['controller' => 'external', 'action' => 'display']; $templateParameters = $this->get('rk_helper_module.controller_helper')->addTemplateParameters($objectType, $templateParameters, 'controllerAction', $contextArgs); $templateParameters['pager'] = [ 'numitems' => $objectCount, 'itemsperpage' => $resultsPerPage ]; $output = $this->renderView('@RKHelperModule/External/' . ucfirst($objectType) . '/find.html.twig', $templateParameters); return new PlainResponse($output); } }
Java
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "errors" "go/build" "testing" "github.com/golang/dep/internal/gps" "github.com/golang/dep/internal/gps/pkgtree" ) func TestInvalidEnsureFlagCombinations(t *testing.T) { ec := &ensureCommand{ update: true, add: true, } if err := ec.validateFlags(); err == nil { t.Error("-add and -update together should fail validation") } ec.vendorOnly, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -update should fail validation") } ec.add, ec.update = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -add should fail validation") } ec.noVendor, ec.add = true, false if err := ec.validateFlags(); err == nil { t.Error("-vendor-only with -no-vendor should fail validation") } ec.noVendor = false // Also verify that the plain ensure path takes no args. This is a shady // test, as lots of other things COULD return errors, and we don't check // anything other than the error being non-nil. For now, it works well // because a panic will quickly result if the initial arg length validation // checks are incorrectly handled. if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil { t.Errorf("no args to plain ensure with -vendor-only") } ec.vendorOnly = false if err := ec.runDefault(nil, []string{"foo"}, nil, nil, gps.SolveParameters{}); err == nil { t.Errorf("no args to plain ensure") } } func TestCheckErrors(t *testing.T) { tt := []struct { name string fatal bool pkgOrErrMap map[string]pkgtree.PackageOrErr }{ { name: "noErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "mypkg": { P: pkgtree.Package{}, }, }, }, { name: "hasErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, { name: "onlyGoErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "onlyBuildErrors", fatal: false, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { P: pkgtree.Package{}, }, }, }, { name: "allGoErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, }, }, { name: "allMixedErrors", fatal: true, pkgOrErrMap: map[string]pkgtree.PackageOrErr{ "github.com/me/pkg": { Err: &build.NoGoError{}, }, "github.com/someone/pkg": { Err: errors.New("code is busted"), }, }, }, } for _, tc := range tt { t.Run(tc.name, func(t *testing.T) { fatal, err := checkErrors(tc.pkgOrErrMap) if tc.fatal != fatal { t.Fatalf("expected fatal flag to be %T, got %T", tc.fatal, fatal) } if err == nil && fatal { t.Fatal("unexpected fatal flag value while err is nil") } }) } }
Java
'use strict'; module.exports = { set: function (v) { this.setProperty('src', v); }, get: function () { return this.getPropertyValue('src'); }, enumerable: true };
Java
<?php namespace App\Modules\OAuth\Controllers; use App\Http\Controllers\Controller; use App\Modules\Users\Controllers\UserController; use App\Modules\Users\Models\User; use App\Modules\Users\Supports\MailCheckSupport; use Laravel\Socialite\Facades\Socialite as Socialite; use Illuminate\Http\Request; use Tymon\JWTAuth\JWTAuth; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenExpiredException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; /** * Class LoginController * @package App\Modules\OAuth\Controllers */ class LoginController extends Controller { /** * @var JWTAuth */ protected $jwt; /** * @var UserController */ public $userController; /** * LoginController constructor. * @param JWTAuth $jwt * @param UserController $userController */ public function __construct(JWTAuth $jwt, UserController $userController) { $this->jwt = $jwt; $this->userController = $userController; } /** * @param $provider * @return mixed */ public function redirectToProvider($provider) { return Socialite::driver($provider) ->stateless() ->redirect(); } /** * @param $provider * @return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory */ public function handleProviderCallback($provider) { try { /** * get user infos with callback provider token */ $user = Socialite::driver($provider) ->stateless() ->user(); /** * check if user email exists in database */ if(!MailCheckSupport::userEmailCheck($user->email)) { /** * create user array infos to save in database */ $userInfos = [ 'name' => $user->name, 'email' => $user->email, 'password' => null, 'remember_token' => str_random(10), 'provider' => $provider, 'provider_id' => $user->id, 'avatar_url' => $user->avatar ]; /** * generate a personal token access from this new user */ $token = $this->userController->createUserFromProvider($userInfos); } else { /** * search existent user in database and generate your personal token access */ $existsUser = User::where('email',$user->email)->first(); $token = $this->jwt->fromUser($existsUser); } if ( env('REDIR_URL') ) { if (env('REDIR_TOKEN_AS_PARAM')) { $redirWithToken = env('REDIR_URL') . "/token:{$token}"; } else { $redirWithToken = env('REDIR_URL') . "?token={$token}"; } return redirect($redirWithToken); } return response()->json(compact('token')); } catch (\Exception $ex) { return response($ex->getMessage(),500); } } /** * @param Request $request * @return \Illuminate\Http\JsonResponse */ public function authenticate(Request $request) { $this->validate($request, [ 'email' => 'required|email|max:255', 'password' => 'required', ]); try { if (! $token = $this->jwt->attempt($request->only('email', 'password'))) { return response()->json(['user_not_found'], 404); } } catch (TokenExpiredException $e) { return response()->json(['token_expired'], $e->getStatusCode()); } catch (TokenInvalidException $e) { return response()->json(['token_invalid'], $e->getStatusCode()); } catch (JWTException $e) { return response()->json(['token_absent' => $e->getMessage()], $e->getStatusCode()); } return response()->json(compact('token')); } }
Java
body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .bar { fill: steelblue; } g.orbit, g.main { cursor: pointer; pointer-events: all; }
Java
#!/bin/sh # Compile script to compile against Elysion library # Works for Mac OS X and Linux FPC_BIN=`which fpc` BIN_FOLDER="../bin" LIB_FOLDER="../lib" RES_FOLDER="../resources" SRC_FOLDER="../source" # Info.plist constants BUNDLE_REGION="English" BUNDLE_ICON="logo.icns" BUNDLE_IDENT="com.mycompanyname" BUNDLE_SIGNATURE="????" BUNDLE_VERSION="1.0" SRC_MAIN="main.lpr" BIN_MAIN=`basename ${SRC_MAIN} .lpr` CONFIG_FILE="@config.cfg" EXEC_NAME="myapp" APP_NAME="My App Title" cd ${SRC_FOLDER} if [ -f /System/Library/Frameworks/Cocoa.framework/Cocoa ] then SDL_PATH= SDL_MIXER_PATH= SDL_TTF_PATH= SDL_NET_PATH= DEV_LINK_PPC= DEV_LINK_INTEL32= DEV_LINK_INTEL64= MIN_PPC= MIN_INTEL32= MIN_INTEL64= if [ -d /Library/Frameworks/SDL.framework ] then SDL_PATH="/Library/Frameworks/SDL.framework" elif [ -d ~/Library/Frameworks/SDL.framework ] then SDL_PATH="~/Library/Frameworks/SDL.framework" else echo "SDL not detected. Please check: https://github.com/freezedev/elysion/wiki/Setting-up-our-development-environment" exit 1 fi if [ -d /Library/Frameworks/SDL_mixer.framework ] then SDL_MIXER_PATH="/Library/Frameworks/SDL_mixer.framework" elif [ -d ~/Library/Frameworks/SDL_mixer.framework ] then SDL_MIXER_PATH="~/Library/Frameworks/SDL_mixer.framework" fi if [ -d /Library/Frameworks/SDL_ttf.framework ] then SDL_TTF_PATH="/Library/Frameworks/SDL_ttf.framework" elif [ -d ~/Library/Frameworks/SDL_ttf.framework ] then SDL_TTF_PATH="~/Library/Frameworks/SDL_ttf.framework" fi if [ -d /Library/Frameworks/SDL_net.framework ] then SDL_NET_PATH="/Library/Frameworks/SDL_net.framework" elif [ -d ~/Library/Frameworks/SDL_net.framework ] then SDL_NET_PATH="~/Library/Frameworks/SDL_net.framework" fi if [ [ -d /Developer/SDKs/MacOSX10.7.sdk ] || [ -d /Developer/SDKs/MacOSX10.6.sdk ] || [ -d /Developer/SDKs/MacOSX10.5.sdk ] || [ -d /Developer/SDKs/MacOSX10.4u.sdk ] ] then echo "At least one Mac OS X SDK found" else echo "XCode does not seem be installed. Please install XCode." exit 1 fi if [ -d "/Developer/SDKs/MacOSX10.7.sdk" ] then DEV_LINK_PPC= DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.7.sdk" DEV_LINK_INTEL64="/Developer/SDKs/MacOSX10.7.sdk" MIN_INTEL32="10.7.0" MIN_INTEL64="10.7.0" fi if [ -d "/Developer/SDKs/MacOSX10.6.sdk" ] then DEV_LINK_PPC= DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.6.sdk" DEV_LINK_INTEL64="/Developer/SDKs/MacOSX10.6.sdk" MIN_INTEL32="10.6.0" MIN_INTEL64="10.6.0" fi if [ -d "/Developer/SDKs/MacOSX10.5.sdk" ] then DEV_LINK_PPC="/Developer/SDKs/MacOSX10.5.sdk" DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.5.sdk" MIN_INTEL32="10.5.0" fi if [ -d "/Developer/SDKs/MacOSX10.4u.sdk" ] then DEV_LINK_PPC="/Developer/SDKs/MacOSX10.4u.sdk" DEV_LINK_INTEL32="/Developer/SDKs/MacOSX10.4u.sdk" MIN_PPC="10.4.0" MIN_INTEL32="10.4.0" fi FPC_BIN=`which ppc386` # Compiling Intel x86 binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_INTEL32} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu FPC_BIN=`which ppcx64` # Compiling Intel x64 binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_INTEL64} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu FPC_BIN=`which ppcppc` # Compiling PowerPC binary ${FPC_BIN} ${CONFIG_FILE} -XR${DEV_LINK_PPC} -k"-L${LIB_FOLDER}/MacOSX -L/usr/X11R6/lib" ${SRC_MAIN} mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${BIN_MAIN}-ppc" rm ${BIN_FOLDER}/*.o ${BIN_FOLDER}/*.ppu # Creating universal binary # Strip executables if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" fi if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" fi if [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then strip "${BIN_FOLDER}/${BIN_MAIN}-ppc" fi # All three compilers are here... yeah, universal binary de luxe (Intel 32, Intel 64 + PowerPC 32) if [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" "${BIN_FOLDER}/${BIN_MAIN}-ppc" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-ppc" # PowerPC 32 + Intel 32 elif [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-ppc" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-ppc" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-ppc" # Intel 32 + Intel 64 elif [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" ] && [ -f "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" ] then lipo -create "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" -output "${BIN_FOLDER}/${EXEC_NAME}" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" rm -rf "${BIN_FOLDER}/${BIN_MAIN}-intel_x64" else strip "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" mv "${BIN_FOLDER}/${BIN_MAIN}-intel_x86" "${BIN_FOLDER}/${EXEC_NAME}" fi if [ -d "${BIN_FOLDER}/${APP_NAME}.app" ] then echo " ... Removing old application" rm -rf "${BIN_FOLDER}/${APP_NAME}.app" fi echo " ... Creating Application Bundle" mkdir "${BIN_FOLDER}/${APP_NAME}.app" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/MacOS" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/Resources" mkdir "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks" cp -R "${RES_FOLDER}/" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Resources/" # Copy frameworks from System cp -R "${SDL_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_MIXER_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_TTF_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" cp -R "${SDL_NET_PATH}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/Frameworks/" mv "${BIN_FOLDER}/${EXEC_NAME}" "${BIN_FOLDER}/${APP_NAME}.app/Contents/MacOS/" echo "<?xml version='1.0' encoding='UTF-8'?>\ <!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\ <plist version=\"1.0\">\ <dict>\ <key>CFBundleDevelopmentRegion</key>\ <string>${BUNDLE_REGION}</string>\ <key>CFBundleExecutable</key>\ <string>${EXEC_NAME}</string>\ <key>CFBundleIconFile</key>\ <string>${BUNDLE_ICON}</string>\ <key>CFBundleIdentifier</key>\ <string>${BUNDLE_IDENT}</string>\ <key>CFBundleInfoDictionaryVersion</key>\ <string>6.0</string>\ <key>CFBundleName</key>\ <string>${APP_NAME}</string>\ <key>CFBundlePackageType</key>\ <string>APPL</string>\ <key>CFBundleSignature</key>\ <string>${BUNDLE_SIGNATURE}</string>\ <key>CFBundleVersion</key>\ <string>${BUNDLE_VERSION}</string>\ <key>CSResourcesFileMapped</key>\ <true/>\ <key>LSMinimumSystemVersionByArchitecture</key>\ <dict>\ <key>x86_64</key>\ <string>${MIN_INTEL64}</string>\ <key>i386</key>\ <string>${MIN_INTEL32}</string>\ <key>ppc</key>\ <string>${MIN_PPC}</string>\ </dict>\ </dict>\ </plist>" >> "${BIN_FOLDER}/${APP_NAME}.app/Contents/Info.plist" echo "APPL${BUNDLE_SIGNATURE}" >> "${BIN_FOLDER}/${APP_NAME}.app/Contents/PkgInfo" else ${FPC_BIN} ${CONFIG_FILE} ${SRC_MAIN} if [ -f "${BIN_FOLDER}/${BIN_MAIN}" ] then mv "${BIN_FOLDER}/${BIN_MAIN}" "${BIN_FOLDER}/${EXEC_NAME}" fi fi
Java
# Tablespoon **This repository is no longer being maintained. Please use [https://github.com/mhkeller/tablespoon2](https://github.com/mhkeller/tablespoon2).** Easily query spreadsheet-like or json data with SQLite or PostgreSQL. Built around[ node-postgres](https://github.com/brianc/node-postgres) and [node-sqlite3](https://github.com/mapbox/node-sqlite3). ### Installation To install as a Node.js module ```` npm install tablespoon ```` To use Tablespoon's command line interface, install with the global flag ```` npm install tablespoon -g ```` If you want to use Tablespoon in both circumstances, run both commands. ### Documentation Check out [the wiki](https://github.com/ajam/tablespoon/wiki) for the latest documentation and the [FAQ](https://github.com/ajam/tablespoon/wiki/Faq), which includes [helpful tips](https://github.com/ajam/tablespoon/wiki/Faq#wiki-how-do-i-convert-csv-tsv-or-some-other-data-format-into-json) on how to load in `csv` or `tsv` data into Node.js. ### Example usage See more [examples](https://github.com/ajam/tablespoon/tree/master/examples). ````js var ts = require('tablespoon.js').pgsql(); var data = [ { city: "New York", temp: [0,35], country: 'USA' }, { city: 'Los Angeles', temp: [15,35], country: 'USA' }, { city: 'Paris', temp: [2,33], country: 'France' }, { city: 'Marseille', temp: [5,27], country: 'France' }, { city: 'London', temp: [2,25], country: 'UK' } ] ts.createTable(data, 'cities') // Get the rows that don't have 15 ts.query('SELECT * FROM cities WHERE 15 != ALL (temp)', function(rows){ console.log(rows) /*{ query: 'SELECT * FROM cities WHERE 15 != ALL (temp)', rows: [ { uid: '1', city: 'New York', temp: [0,35], country: 'USA' }, { uid: '3', city: 'Paris', temp: [2,33], country: 'France' }, { uid: '4', city: 'Marseille', temp: [5,27], country: 'France' }, { uid: '5', city: 'London', temp: [2,25], country: 'UK' } ] }*/ }) ```` ### Testing Examples and testing require a `postgres` role unless you change the connection string your own role. Create with `createuser -s -r postgres` from the command line. ### Used in Analysis for [Nominated for the Oscars but failing the Bechdel sexism test](http://america.aljazeera.com/articles/2014/1/17/nominated-for-theoscarsbutfailingthebechdeltest.html) - Al Jazeera America
Java
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <QApplication> #include "bitcoingui.h" #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include "paymentserver.h" #include "splashscreen.h" #include <QMessageBox> #if QT_VERSION < 0x050000 #include <QTextCodec> #endif #include <QLocale> #include <QTimer> #include <QTranslator> #include <QLibraryInfo> #ifdef Q_OS_MAC #include "macdockiconhandler.h" #endif #if defined(BITCOIN_NEED_QT_PLUGINS) && !defined(_BITCOIN_QT_PLUGINS_INCLUDED) #define _BITCOIN_QT_PLUGINS_INCLUDED #define __INSURE__ #include <QtPlugin> Q_IMPORT_PLUGIN(qcncodecs) Q_IMPORT_PLUGIN(qjpcodecs) Q_IMPORT_PLUGIN(qtwcodecs) Q_IMPORT_PLUGIN(qkrcodecs) Q_IMPORT_PLUGIN(qtaccessiblewidgets) #endif // Declare meta types used for QMetaObject::invokeMethod Q_DECLARE_METATYPE(bool*) // Need a global reference for the notifications to find the GUI static BitcoinGUI *guiref; static SplashScreen *splashref; static bool ThreadSafeMessageBox(const std::string& message, const std::string& caption, unsigned int style) { // Message from network thread if(guiref) { bool modal = (style & CClientUIInterface::MODAL); bool ret = false; // In case of modal message, use blocking connection to wait for user to click a button QMetaObject::invokeMethod(guiref, "message", modal ? GUIUtil::blockingGUIThreadConnection() : Qt::QueuedConnection, Q_ARG(QString, QString::fromStdString(caption)), Q_ARG(QString, QString::fromStdString(message)), Q_ARG(unsigned int, style), Q_ARG(bool*, &ret)); return ret; } else { printf("%s: %s\n", caption.c_str(), message.c_str()); fprintf(stderr, "%s: %s\n", caption.c_str(), message.c_str()); return false; } } static bool ThreadSafeAskFee(int64 nFeeRequired) { if(!guiref) return false; if(nFeeRequired < CTransaction::nMinTxFee || nFeeRequired <= nTransactionFee || fDaemon) return true; bool payFee = false; QMetaObject::invokeMethod(guiref, "askFee", GUIUtil::blockingGUIThreadConnection(), Q_ARG(qint64, nFeeRequired), Q_ARG(bool*, &payFee)); return payFee; } static void InitMessage(const std::string &message) { if(splashref) { splashref->showMessage(QString::fromStdString(message), Qt::AlignBottom|Qt::AlignHCenter, QColor(55,55,55)); qApp->processEvents(); } printf("init message: %s\n", message.c_str()); } /* Translate string to current locale using Qt. */ static std::string Translate(const char* psz) { return QCoreApplication::translate("bitcoin-core", psz).toStdString(); } /* Handle runaway exceptions. Shows a message box with the problem and quits the program. */ static void handleRunawayException(std::exception *e) { PrintExceptionContinue(e, "Runaway exception"); QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. Amerios can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning)); exit(1); } #ifndef BITCOIN_QT_TEST int main(int argc, char *argv[]) { // Command-line options take precedence: ParseParameters(argc, argv); #if QT_VERSION < 0x050000 // Internal string conversion is all UTF-8 QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForCStrings(QTextCodec::codecForTr()); #endif Q_INIT_RESOURCE(bitcoin); QApplication app(argc, argv); // Register meta types used for QMetaObject::invokeMethod qRegisterMetaType< bool* >(); // Do this early as we don't want to bother initializing if we are just calling IPC // ... but do it after creating app, so QCoreApplication::arguments is initialized: if (PaymentServer::ipcSendCommandLine()) exit(0); PaymentServer* paymentServer = new PaymentServer(&app); // Install global event filter that makes sure that long tooltips can be word-wrapped app.installEventFilter(new GUIUtil::ToolTipToRichTextFilter(TOOLTIP_WRAP_THRESHOLD, &app)); // ... then bitcoin.conf: if (!boost::filesystem::is_directory(GetDataDir(false))) { // This message can not be translated, as translation is not initialized yet // (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory) QMessageBox::critical(0, "Amerios", QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"]))); return 1; } ReadConfigFile(mapArgs, mapMultiArgs); // Application identification (must be set before OptionsModel is initialized, // as it is used to locate QSettings) QApplication::setOrganizationName("Amerios"); QApplication::setOrganizationDomain("amerios.org"); if(GetBoolArg("-testnet")) // Separate UI settings for testnet QApplication::setApplicationName("Amerios-Qt-testnet"); else QApplication::setApplicationName("Amerios-Qt"); // ... then GUI settings: OptionsModel optionsModel; // Get desired locale (e.g. "de_DE") from command line or use system locale QString lang_territory = QString::fromStdString(GetArg("-lang", QLocale::system().name().toStdString())); QString lang = lang_territory; // Convert to "de" only by truncating "_DE" lang.truncate(lang_territory.lastIndexOf('_')); QTranslator qtTranslatorBase, qtTranslator, translatorBase, translator; // Load language files for configured locale: // - First load the translator for the base language, without territory // - Then load the more specific locale translator // Load e.g. qt_de.qm if (qtTranslatorBase.load("qt_" + lang, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslatorBase); // Load e.g. qt_de_DE.qm if (qtTranslator.load("qt_" + lang_territory, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) app.installTranslator(&qtTranslator); // Load e.g. bitcoin_de.qm (shortcut "de" needs to be defined in bitcoin.qrc) if (translatorBase.load(lang, ":/translations/")) app.installTranslator(&translatorBase); // Load e.g. bitcoin_de_DE.qm (shortcut "de_DE" needs to be defined in bitcoin.qrc) if (translator.load(lang_territory, ":/translations/")) app.installTranslator(&translator); // Subscribe to global signals from core uiInterface.ThreadSafeMessageBox.connect(ThreadSafeMessageBox); uiInterface.ThreadSafeAskFee.connect(ThreadSafeAskFee); uiInterface.InitMessage.connect(InitMessage); uiInterface.Translate.connect(Translate); // Show help message immediately after parsing command-line options (for "-lang") and setting locale, // but before showing splash screen. if (mapArgs.count("-?") || mapArgs.count("--help")) { GUIUtil::HelpMessageBox help; help.showOrPrint(); return 1; } #ifdef Q_OS_MAC // on mac, also change the icon now because it would look strange to have a testnet splash (green) and a std app icon (orange) if(GetBoolArg("-testnet")) { MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet")); } #endif SplashScreen splash(QPixmap(), 0); if (GetBoolArg("-splash", true) && !GetBoolArg("-min")) { splash.show(); splash.setAutoFillBackground(true); splashref = &splash; } app.processEvents(); app.setQuitOnLastWindowClosed(false); try { #ifndef Q_OS_MAC // Regenerate startup link, to fix links to old versions // OSX: makes no sense on mac and might also scan/mount external (and sleeping) volumes (can take up some secs) if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(true); #endif boost::thread_group threadGroup; BitcoinGUI window; guiref = &window; QTimer* pollShutdownTimer = new QTimer(guiref); QObject::connect(pollShutdownTimer, SIGNAL(timeout()), guiref, SLOT(detectShutdown())); pollShutdownTimer->start(200); if(AppInit2(threadGroup)) { { // Put this in a block, so that the Model objects are cleaned up before // calling Shutdown(). optionsModel.Upgrade(); // Must be done after AppInit2 if (splashref) splash.finish(&window); ClientModel clientModel(&optionsModel); WalletModel *walletModel = 0; if(pwalletMain) walletModel = new WalletModel(pwalletMain, &optionsModel); window.setClientModel(&clientModel); if(walletModel) { window.addWallet("~Default", walletModel); window.setCurrentWallet("~Default"); } // If -min option passed, start window minimized. if(GetBoolArg("-min")) { window.showMinimized(); } else { window.show(); } // Now that initialization/startup is done, process any command-line // bitcoin: URIs QObject::connect(paymentServer, SIGNAL(receivedURI(QString)), &window, SLOT(handleURI(QString))); QTimer::singleShot(100, paymentServer, SLOT(uiReady())); app.exec(); window.hide(); window.setClientModel(0); window.removeAllWallets(); guiref = 0; delete walletModel; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); } else { threadGroup.interrupt_all(); threadGroup.join_all(); Shutdown(); return 1; } } catch (std::exception& e) { handleRunawayException(&e); } catch (...) { handleRunawayException(NULL); } return 0; } #endif // BITCOIN_QT_TEST
Java