text
stringlengths
2
1.04M
meta
dict
package com.google.errorprone.refaster.testdata.template; import com.google.errorprone.refaster.annotation.AfterTemplate; import com.google.errorprone.refaster.annotation.BeforeTemplate; import com.google.errorprone.refaster.annotation.Repeated; /** * Example Refaster rule matching varargs. * * @author juanch@google.com (Juan Chen) */ public class VarargTemplate { @BeforeTemplate public String before( String template, @Repeated Object vararg) { return String.format(template, new Object[]{vararg}); } @AfterTemplate public String after( String template, @Repeated Object vararg) { return String.format(template, vararg); } }
{ "content_hash": "05583af528ba6f0af0b36b8f6c9ab308", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 64, "avg_line_length": 25.22222222222222, "alnum_prop": 0.7415565345080763, "repo_name": "Anish2/error-prone", "id": "b52b057e4dc60671f29d52aa0493e3feb8d80a7f", "size": "1294", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/test/java/com/google/errorprone/refaster/testdata/template/VarargTemplate.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "1886" }, { "name": "Java", "bytes": "3658218" }, { "name": "Protocol Buffer", "bytes": "534" }, { "name": "Python", "bytes": "5867" }, { "name": "Shell", "bytes": "2401" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using CyPhy = ISIS.GME.Dsml.CyPhyML.Interfaces; using CyPhyClasses = ISIS.GME.Dsml.CyPhyML.Classes; using GmeCommon = ISIS.GME.Common; using GME.CSharp; namespace CyPhy2CAD_CSharp.DataRep { public class StructuralInterfaceConstraint { public string PortID { get; set; } public string ParentID { get; set; } // GUID public string ParentInstanceGUID { get; set; } // InstanceGUID public Dictionary<string, Datum> DatumList { get; set; } public GmeCommon.Interfaces.FCO CyPhyImpl { get; set; } public int DegreeFreedom { get; set; } public string InterfaceDefinition { get; set; } public KinematicJoint Joint { get; set; } public string Name { get; set; } public CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum? AdjSurfTreatment; // If specified, this'll be different from DEFAULT public List<CADGeometry> Geometry = new List<CADGeometry>(); // If geometries are associated with this interface public StructuralInterfaceConstraint(GmeCommon.Interfaces.FCO impl, string parentID, string parentinstanceGUID) { CyPhyImpl = impl; PortID = impl.ID; ParentID = parentID; ParentInstanceGUID = parentinstanceGUID; DatumList = new Dictionary<string, Datum>(); DegreeFreedom = 0; if (impl is CyPhy.Connector) { InterfaceDefinition = (impl as CyPhy.Connector).Attributes.Definition; Name = impl.Name; } else if (impl is CyPhy.CADDatum) { InterfaceDefinition = (impl as CyPhy.CADDatum).Attributes.Definition; Name = impl.Name; } else { InterfaceDefinition = ""; Name = ""; } } // Sets up joint based on already populated datums // Pre-Condition: DatumList is filled out private void SetupJoint(List<CyPhy.CADDatum> datumlist, List<CyPhy.CADDatum> limitreflist, Dictionary<string, DataRep.Datum> limitrefmap) { if ((CyPhyImpl as CyPhy.Connector).Children.KinematicRevoluteJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicRevoluteJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicCylindricalJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicCylindricalJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicFixedJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicFixedJointCollection.First()); } else if ((CyPhyImpl as CyPhy.Connector).Children.KinematicTranslationalJointCollection.Any()) { Joint = new KinematicJoint((CyPhyImpl as CyPhy.Connector).Children.KinematicTranslationalJointCollection.First()); } // Get the datums to associate with this joint if (Joint != null) { foreach (var cyphydatum in datumlist) { Datum datarepdatum; if (DatumList.TryGetValue(cyphydatum.Name, out datarepdatum)) { // Is datum part of defining the joint? if (cyphydatum.SrcConnections.KinematicJointDefinitionCollection.Any()) { if (cyphydatum is CyPhy.Axis) { Joint.Axis = datarepdatum; } else if (cyphydatum is CyPhy.Surface) { Joint.AlignmentPlane = datarepdatum; } } } } if (limitreflist.Any() && Joint.JointType == KinematicJoint.KinematicJointType.REVOLUTE) { throw new Exception("Limit references for revolute joints are not supported currently. Guides will be used as limit references. Please remove limit references on rvlute joints from your model. Connector: " + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } var guides = datumlist.Where(d => d.Attributes.DefinitionNotes.Contains("GUIDE")); if (guides.Any()) { Logger.Instance.AddLogMessage("Datum is using old guide format. Please use the attribute 'IsGuide'. Connector: " + CyPhyImpl.Path, Severity.Error); return; } guides = datumlist.Where(d => d.Attributes.IsGuide); if (guides.Count() > 1) { throw new Exception("More than one guides in a kinematic joint. This is not supported yet. Connector: " + CyPhyImpl.Path); } else if (guides.Count() == 1) { Joint.RotationDefaultReference = this.DatumList[guides.First().Name]; } foreach (var limitrefdatum in limitreflist) { Datum datarepdatum; if (limitrefmap.TryGetValue(limitrefdatum.Name, out datarepdatum)) { // Is this datum part of defining the limits of the joint? if ((limitrefdatum as CyPhy.Surface).SrcConnections.KinematicTranslationalLimitReferenceCollection.Any()) { var limittype = (limitrefdatum as CyPhy.Surface).SrcConnections.KinematicTranslationalLimitReferenceCollection.First().Attributes.TranslationalLimitReferenceType; // Default if (limittype == CyPhyClasses.KinematicTranslationalLimitReference.AttributesClass.TranslationalLimitReferenceType_enum.NormalExtent) { Joint.TranslationDefaultReference = datarepdatum; } // Min else if (limittype == CyPhyClasses.KinematicTranslationalLimitReference.AttributesClass.TranslationalLimitReferenceType_enum.MinExtent) { throw new Exception("Min and max references are not yet supported. Please remove these." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } // Max else { throw new Exception("Min and max references are not yet supported. Please remove these." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } } } } if ((Joint.RotationLimitMax.HasValue || Joint.RotationLimitMin.HasValue) && !Joint.RotationLimitDefault.HasValue) { throw new Exception("Joint has rotation limit max or min specified, but not default. Please specify default value as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.RotationLimitDefault.HasValue && Joint.RotationDefaultReference == null) { throw new Exception("Joint has rotation limit specified, but there are no guides present to be used as rotation references. Please define guides for the connection as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if ((Joint.TranslationLimitMax.HasValue || Joint.TranslationLimitMin.HasValue) && !Joint.TranslationLimitDefault.HasValue) { throw new Exception("Joint has translation limit max or min specified, but not default. Please specify default value as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.TranslationLimitDefault.HasValue && Joint.TranslationDefaultReference == null) { throw new Exception("Joint has translation limit specified, but there is no limit reference present. Please define limit references in the connection as well." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } if (Joint.RotationLimitMax.HasValue && Joint.RotationLimitMin.HasValue && Joint.RotationLimitMin.Value > Joint.RotationLimitMax.Value) { throw new Exception("Joint rotation limit min > max. Please correct this." + CyPhyImpl.Name + ", Parent: " + CyPhyImpl.ParentContainer.Name); } } } public CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum ImliedSurfTreatment { get { if (Joint == null) { return CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum.Contacted; } else { switch (Joint.JointType) { case KinematicJoint.KinematicJointType.CYLINDRICAL: case KinematicJoint.KinematicJointType.PRISMATIC: case KinematicJoint.KinematicJointType.REVOLUTE: case KinematicJoint.KinematicJointType.SPHERICAL: return CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum.Contacted; case KinematicJoint.KinematicJointType.FIXED: return CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum.Bonded; case KinematicJoint.KinematicJointType.UNDEFINED: return CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum.Contacted; default: return CyPhyClasses.AdjoiningSurfacesTreatment.AttributesClass.Type_enum.Contacted; } } } } public void SetupAdjoiningTreatment() { if (CyPhyImpl is CyPhy.Connector) { foreach (var conn in (CyPhyImpl as CyPhy.Connector).DstConnections.AdjoiningSurfConnectionCollection.Union((CyPhyImpl as CyPhy.Connector).SrcConnections.AdjoiningSurfConnectionCollection)) { var surftreatment = conn.DstEnds.AdjoiningSurfacesTreatment; if (surftreatment == null) { surftreatment = conn.SrcEnds.AdjoiningSurfacesTreatment; } this.AdjSurfTreatment = surftreatment.Attributes.Type; } } } public int GetDegreesOfFreedom() { int AxisCnt = 0, PointCnt = 0, SurfaceCnt = 0, CsysCnt = 0; int count = DatumList.Count(), dof = 0; foreach (KeyValuePair<string, Datum> item in DatumList) { string dtype = item.Value.Type.ToString(); if (dtype == "Axis") AxisCnt++; else if (dtype == "Point") PointCnt++; else if (dtype == "Surface") SurfaceCnt++; else if (dtype == "CoordinateSystem") CsysCnt++; } if (CsysCnt > 0) { switch (count) { case 0: dof = 0; break; case 1: { if (AxisCnt > 0) dof = 4; else dof = 3; } break; case 2: dof = 5; break; case 3: dof = 6; break; default: dof = 6; break; } } else dof = 6; return dof; } public void PopulateStructuralInterface(CyPhy.CADModel cadmodel) { if (CyPhyImpl is CyPhy.Connector) { PopulateStructuralInterface(CyPhyImpl as CyPhy.Connector, cadmodel); } else if (CyPhyImpl is CyPhy.CADDatum) { PopulateStructuralInterface(CyPhyImpl as CyPhy.CADDatum, cadmodel); } } public void PopulateStructuralInterface(CyPhy.CADDatum datum, CyPhy.CADModel acadmodel) { // META-947: Creates a virtual connector Dictionary<string, DataRep.Datum> featuremap = new Dictionary<string, DataRep.Datum>(); FindMatchingDatums(datum, acadmodel, featuremap); this.DatumList = featuremap; this.DegreeFreedom = GetDegreesOfFreedom(); } public void PopulateStructuralInterface(CyPhy.Connector a, CyPhy.CADModel acadmodel) { // META-947: Connector instead of StructuralInterface // [1] Connectors can be nested so find all cad datums within a connector recursively // [2] Find connected datums // Skip Connector without any Datum Ports // Limitref datums won't be considered part of the connection List<CyPhy.CADDatum> CadDatum_List = new List<CyPhy.CADDatum>(); List<CyPhy.CADDatum> LimitRefDatum_List = new List<CyPhy.CADDatum>(); FindCadDatumsInConnector(a, CadDatum_List, LimitRefDatum_List); Dictionary<string, DataRep.Datum> featuremap = new Dictionary<string, DataRep.Datum>(); Dictionary<string, DataRep.Datum> limitrefmap = new Dictionary<string, DataRep.Datum>(); foreach (CyPhy.CADDatum item in CadDatum_List) { FindMatchingDatums(item, acadmodel, featuremap); } foreach (CyPhy.CADDatum item in LimitRefDatum_List) { FindMatchingDatums(item, acadmodel, limitrefmap); } this.DatumList = featuremap; this.DegreeFreedom = GetDegreesOfFreedom(); SetupJoint(CadDatum_List, LimitRefDatum_List, limitrefmap); SetupAdjoiningTreatment(); foreach (var intfgeom in a.SrcConnections.InterfaceGeometryCollection.Union(a.DstConnections.InterfaceGeometryCollection)) { var geom = (intfgeom.SrcEnds.GeometryTypes == null) ? intfgeom.DstEnds.GeometryTypes : intfgeom.SrcEnds.GeometryTypes; if (geom != null) { Geometry.Add(CADGeometry.CreateGeometry(geom)); } } } private bool FindMatchingDatums(CyPhy.CADDatum datum, CyPhy.CADModel cadmodel, Dictionary<string, DataRep.Datum> featuremap) { string cadmodel_id = cadmodel.ID; string alignment = "ALIGN"; string orientation = "NONE"; if (datum.Kind == "Surface") { alignment = (datum as CyPhy.Surface).Attributes.Alignment.ToString(); if (alignment=="MATE") Logger.Instance.AddLogMessage("MATE alignment is used on surface: " + datum.ToHyperLink() + ". This construct is obsolete, please set up the connection as ALIGN.", Severity.Warning); } CadDatumTraversal traversal = new CadDatumTraversal(datum, cadmodel_id); if (traversal.datumFound.Count > 0) { if (traversal.datumFound.Count > 1) { Logger.Instance.AddLogMessage("Connector datum connected to multiple datums in the same CADModel [" + datum.Path + "]", Severity.Error); return true; // Error } // META-3232 /* DataRep.Datum datumRep = new DataRep.Datum(traversal.datumFound.First().Attributes.DatumName, datum.Kind, this.ParentInstanceGUID, guide); */ bool guide = datum.Attributes.DefinitionNotes.Contains("GUIDE"); if (guide) { Logger.Instance.AddLogMessage("Datum is using old guide format. Please use the attribute 'IsGuide'. [" + datum.Path + "]", Severity.Error); return true; // Error } guide |= datum.Attributes.IsGuide; DataRep.Datum datumRep = new DataRep.Datum(traversal.datumFound.First(), this.ParentInstanceGUID, guide); if (datum.Kind == "Surface") { if (traversal.ReverseMap) orientation = "SIDE_B"; else orientation = "SIDE_A"; } if (datum.Kind == "CoordinateSystem") { alignment = "CSYS"; } datumRep.Alignment = alignment; datumRep.Orientation = orientation; if (!featuremap.ContainsKey(datum.Name)) { featuremap[datum.Name] = datumRep; } } return false; } private bool IsLimitRef(CyPhy.CADDatum datum) { return datum is CyPhy.Surface && ((datum as CyPhy.Surface).SrcConnections.KinematicRotationalLimitReferenceCollection.Any() || (datum as CyPhy.Surface).SrcConnections.KinematicTranslationalLimitReferenceCollection.Any()); } // Connectors may be nested in the future! private void FindCadDatumsInConnector(CyPhy.Connector connector, List<CyPhy.CADDatum> caddatum_list, // These datums are part of the interface List<CyPhy.CADDatum> caddatum_list_joint_refs) // These datums are references belonging to joints, not part of the interface { foreach (var datum in connector.Children.CADDatumCollection) { if (!IsLimitRef(datum)) { caddatum_list.Add(datum); } else { caddatum_list_joint_refs.Add(datum); } } } private static bool MatchSIType(string a_original, string b_original) { string a = a_original.ToLower(); string b = b_original.ToLower(); int a_size = a.Count(); int b_size = b.Count(); if (a == b) { return true; } else { if (a_size != b_size) return false; for (int i = 0; i < a_size; i++) { if (a[i] != '*' && b[i] != '*') if (a[i] != b[i]) return false; } return true; } } public static bool MatchStructuralInterfaceDatums(DataRep.StructuralInterfaceConstraint a, DataRep.StructuralInterfaceConstraint b, List<Tuple<DataRep.Datum, DataRep.Datum>> constraintPairs) { string apath = a.CyPhyImpl.Path, bpath = b.CyPhyImpl.Path; // Means no error bool result = false; if (!DataRep.StructuralInterfaceConstraint.MatchSIType(a.InterfaceDefinition, b.InterfaceDefinition)) //if (!MatchSIType(a.InterfaceDefinition, b.InterfaceDefinition)) { Logger.Instance.AddLogMessage("Mismatched Type attribute on connected StructuralInterfaces. Interface 1: [" + a.CyPhyImpl.ToHyperLink() + "] (" + a.InterfaceDefinition + "). Interface 2: [" + b.CyPhyImpl.ToHyperLink() + "] (" + b.InterfaceDefinition + ")", Severity.Error); return true; } List<string> adatumnames = a.DatumList.Keys.ToList(); List<string> bdatumnames = b.DatumList.Keys.ToList(); if (adatumnames.Count() != bdatumnames.Count()) { Logger.Instance.AddLogMessage("Connected StructuralInterfaces have different number of datum ports: [" + a.CyPhyImpl.ToHyperLink() + ", " + b.CyPhyImpl.ToHyperLink() + "]", Severity.Error); return true; } if (adatumnames.Count() > 1 && bdatumnames.Count() > 1) { foreach (KeyValuePair<string, DataRep.Datum> adatum in a.DatumList) { if (b.DatumList.ContainsKey(adatum.Key)) { DataRep.DatumType a_type = adatum.Value.Type; DataRep.DatumType b_type = b.DatumList[adatum.Key].Type; if (a_type != b_type) { Logger.Instance.AddLogMessage("Matching datum ports are different type [" + a.CyPhyImpl.ToHyperLink() + "," + b.CyPhyImpl.ToHyperLink() + "]", Severity.Error); result = true; continue; } else { if (a_type == DataRep.DatumType.Surface) { if (adatum.Value.Alignment != b.DatumList[adatum.Key].Alignment) { Logger.Instance.AddLogMessage("Matching Surface datum ports have different Alignment attributes [" + a.CyPhyImpl.ToHyperLink() + "," + b.CyPhyImpl.ToHyperLink() + "]", Severity.Error); result = true; continue; } } var atumple = new Tuple<DataRep.Datum, DataRep.Datum>(adatum.Value, b.DatumList[adatum.Key]); constraintPairs.Add(atumple); } adatumnames.Remove(adatum.Key); bdatumnames.Remove(adatum.Key); } } if (adatumnames.Any() || bdatumnames.Any()) { Logger.Instance.AddLogMessage(String.Format("Connected connectors contain unmatched named feature ports. Port names must match inside connectors. Connectors are: {0} ({1}) and {2} ({3}).", a.CyPhyImpl.ToHyperLink(), String.Join(",", adatumnames.ToArray()), b.CyPhyImpl.ToHyperLink(), String.Join(",", bdatumnames)), Severity.Error); return true; } } else { var atuple = new Tuple<DataRep.Datum, DataRep.Datum>(a.DatumList.Values.First(), b.DatumList.Values.First()); constraintPairs.Add(atuple); } return result; } public override string ToString() { StringBuilder sbuilder = new StringBuilder(); sbuilder.AppendFormat("\n <SI: {0}, DOF({1}) ", PortID, DegreeFreedom); foreach (var item in DatumList.Values) { sbuilder.AppendFormat("|({0},{1})", item.DatumName, item.Type.ToString()); } sbuilder.AppendFormat(">"); sbuilder.AppendLine(); return sbuilder.ToString(); } } }
{ "content_hash": "d6a33d819b7295bab785d1acb328dabe", "timestamp": "", "source": "github", "line_count": 554, "max_line_length": 352, "avg_line_length": 46.67870036101083, "alnum_prop": 0.4969450889404486, "repo_name": "pombredanne/metamorphosys-desktop", "id": "3170e22d0f23fdb2b3d5266e988130e8f686a906", "size": "28645", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "metamorphosys/META/src/CyPhy2CAD_CSharp/DataRep/CADConstraint.cs", "mode": "33261", "license": "mit", "language": [ { "name": "Arduino", "bytes": "10683" }, { "name": "Assembly", "bytes": "117345" }, { "name": "Awk", "bytes": "3591" }, { "name": "Batchfile", "bytes": "228118" }, { "name": "BitBake", "bytes": "4526" }, { "name": "C", "bytes": "3613212" }, { "name": "C#", "bytes": "11617773" }, { "name": "C++", "bytes": "51448188" }, { "name": "CMake", "bytes": "3055" }, { "name": "CSS", "bytes": "109563" }, { "name": "Clojure", "bytes": "37831" }, { "name": "Eagle", "bytes": "3782687" }, { "name": "Emacs Lisp", "bytes": "8514" }, { "name": "GAP", "bytes": "49124" }, { "name": "Groff", "bytes": "2178" }, { "name": "Groovy", "bytes": "7686" }, { "name": "HTML", "bytes": "4025250" }, { "name": "Inno Setup", "bytes": "35715" }, { "name": "Java", "bytes": "489537" }, { "name": "JavaScript", "bytes": "167454" }, { "name": "Lua", "bytes": "1660" }, { "name": "Makefile", "bytes": "97209" }, { "name": "Mathematica", "bytes": "26" }, { "name": "Matlab", "bytes": "80874" }, { "name": "Max", "bytes": "78198" }, { "name": "Modelica", "bytes": "44541139" }, { "name": "Objective-C", "bytes": "34004" }, { "name": "Perl", "bytes": "19285" }, { "name": "PostScript", "bytes": "400254" }, { "name": "PowerShell", "bytes": "19749" }, { "name": "Processing", "bytes": "1477" }, { "name": "Prolog", "bytes": "3121" }, { "name": "Protocol Buffer", "bytes": "58995" }, { "name": "Python", "bytes": "5517835" }, { "name": "Ruby", "bytes": "4483" }, { "name": "Shell", "bytes": "956773" }, { "name": "Smarty", "bytes": "37892" }, { "name": "TeX", "bytes": "4183594" }, { "name": "Visual Basic", "bytes": "22546" }, { "name": "XSLT", "bytes": "332312" } ], "symlink_target": "" }
#ifndef __H_VHWD_INDEXER_MAP__ #define __H_VHWD_INDEXER_MAP__ #include "vhwd/collection/detail/indexer_container.h" VHWD_ENTER template<typename K,typename V,typename A=def_allocator,typename P=indexer_trait<K,V,int> > class indexer_map : public indexer_container<P,A> { protected: typedef indexer_container<P,A> basetype; typedef typename basetype::impl_type impl_type; using basetype::impl; public: typedef typename impl_type::mapped_type mapped_type; typedef typename impl_type::key_type key_type; typedef typename impl_type::index_type index_type; typedef typename impl_type::value_type value_type; typedef typename impl_type::size_type size_type; typedef typename impl_type::value_proxy value_proxy; indexer_map() {} indexer_map(const indexer_map& o):basetype(o) {} #ifdef VHWD_C11 indexer_map(indexer_map&& o):basetype(o) {} #endif mapped_type& operator[](const key_type& k) { index_type id=impl.find2(k); return this->get(id).second; } const mapped_type& operator[](const key_type& k) const { index_type id=impl.find(k); if(id==impl_type::invalid_pos) Exception::XNotFound(); return this->get(id).second; } }; VHWD_LEAVE #endif
{ "content_hash": "18f70e6d7bc397ae106fbe6e1738e6e2", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 91, "avg_line_length": 24.07843137254902, "alnum_prop": 0.6970684039087948, "repo_name": "xiongqiangcs/vhwd_base", "id": "d9a9208a754942eb68465b7feccae4f75a3e3a15", "size": "1448", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "inc/vhwd/collection/indexer_map.h", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package io.crnk.example.jersey.domain.repository; import io.crnk.core.queryspec.QuerySpec; import io.crnk.core.repository.ResourceRepositoryBase; import io.crnk.example.jersey.domain.model.Project; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; public class ProjectRepositoryImpl extends ResourceRepositoryBase<Project, Long> implements ProjectRepository { private static final AtomicLong ID_GENERATOR = new AtomicLong(124); private Map<Long, Project> projects = new HashMap<>(); public ProjectRepositoryImpl() { super(Project.class); List<String> interests = new ArrayList<>(); interests.add("coding"); interests.add("art"); save(new Project(121L, "Great Project")); save(new Project(122L, "Crnk Project")); save(new Project(123L, "Some Project")); save(new Project(124L, "JSON API Project")); } @Override public synchronized void delete(Long id) { projects.remove(id); } @Override public synchronized <S extends Project> S save(S project) { if (project.getId() == null) { project.setId(ID_GENERATOR.getAndIncrement()); } projects.put(project.getId(), project); return project; } @Override public synchronized ProjectList findAll(QuerySpec querySpec) { ProjectList list = new ProjectList(); list.setMeta(new ProjectListMeta()); list.setLinks(new ProjectListLinks()); querySpec.apply(projects.values(), list); return list; } }
{ "content_hash": "087432d803dcdff309c0cba9fb567112", "timestamp": "", "source": "github", "line_count": 53, "max_line_length": 111, "avg_line_length": 28.07547169811321, "alnum_prop": 0.7466397849462365, "repo_name": "crnk-project/crnk-framework", "id": "085a22a6ca893f1bc76d7ccb17a9ccbc05ae006d", "size": "1488", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "crnk-integration-examples/jersey-example/src/main/java/io/crnk/example/jersey/domain/repository/ProjectRepositoryImpl.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "81023" }, { "name": "Java", "bytes": "4972700" }, { "name": "JavaScript", "bytes": "10403" }, { "name": "SCSS", "bytes": "150107" }, { "name": "Shell", "bytes": "948" }, { "name": "TypeScript", "bytes": "217454" } ], "symlink_target": "" }
package com.meizhuo.etips.db; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.meizhuo.etips.activities.R; import com.meizhuo.etips.activities.R.string; import com.meizhuo.etips.common.ETipsContants; import com.meizhuo.etips.common.ETipsUtils; import com.meizhuo.etips.model.MsgRecord; public class MsgCenterDAO implements BaseDAO { private MsgCenterDBHelper dbHelper = null; private Context context; public MsgCenterDAO(Context context) { dbHelper = new MsgCenterDBHelper(context); this.context = context; } public static ContentValues getContentValues(MsgRecord m) { ContentValues cv = new ContentValues(); cv.put("id", m.id); cv.put("content", m.content); cv.put("type", m.type); cv.put("addTime", m.addTime); return cv; } public List<MsgRecord> query(String selection, String[] selectionArgs) { SQLiteDatabase db = null; List<MsgRecord> list = new ArrayList<MsgRecord>(); try { db = dbHelper.getReadableDatabase(); Cursor c = db.query("msg", null, selection, selectionArgs, null, null, null); int len = c.getColumnCount(); while (c.moveToNext()) { MsgRecord m = new MsgRecord(); for (int i = 0; i < len; i++) { String key = c.getColumnName(i); String value = c.getString(c.getColumnIndex(key)); if (value == null) value = ""; if (key.equals("id")) m.id = Integer.parseInt(value); else if (key.equals("content")) m.content = value; else if (key.equals("type")) m.type = value; else if (key.equals("addTime")) m.addTime = value; } list.add(m); } } catch (Exception e) { } finally { if (db != null) { db.close(); } } return list; } /** * 全部查询 * @return List<MsgRecord> */ public List<MsgRecord> queryAll(){ return this.query(null, null); } @Override public boolean add(ContentValues cv) { SQLiteDatabase db = null; boolean flag = false; try { db = dbHelper.getWritableDatabase(); long id = db.insert("msg", null, cv); flag = (id != -1 ? true : false); } catch (Exception e) { } finally { if (db != null) { db.close(); } } return flag; } /** * 必须添加这一条,就算清空了也要重新加入这条 * @return true if operate successfully */ public boolean addOne(){ ContentValues cv =new ContentValues(); //SharedPreferences sp = context.getSharedPreferences(ETipsContants.SharedPreference_NAME, Context.MODE_PRIVATE); cv.put("id", 0); cv.put("content",context.getString(R.string.MsgCenterTips)); cv.put("type", ETipsContants.TYPE_MsgCenter_System); cv.put("addTime", System.currentTimeMillis()+""); System.out.println((String)cv.get("addTime")); return add(cv); } /** * 删除时请注意,不能删除第0条,系统默认的 * @param */ @Override public boolean delete(String whereClause, String[] whereArgs) { boolean flag = false; SQLiteDatabase db = null; try { db = dbHelper.getWritableDatabase(); int count = db.delete("msg", whereClause, whereArgs); flag = (count > 0 ? true : false); } catch (Exception e) { } finally { if (db != null) { db.close(); } } return flag; } /** * 全部删除时请注意,不能删除第0条,系统默认的 * 全部删除后必须调用addOne() */ @Override public boolean deleteAll() { boolean flag = false; SQLiteDatabase db = null; try { db = dbHelper.getWritableDatabase(); db.execSQL("delete from msg"); flag = true; } catch (Exception e) { e.printStackTrace(); } finally { if (db != null) db.close(); } return flag; } @Override public boolean update(ContentValues cv, String whereClause, String[] whereArgs) { boolean flag = false; SQLiteDatabase db = null; try { db = dbHelper.getWritableDatabase(); int count = db.update("msg", cv, whereClause, whereArgs); // count // 受影响的条数 flag = (count > 0 ? true : false); } catch (Exception e) { e.printStackTrace(); } finally { if (db != null) db.close(); } return flag; } /** * 有多少行数据 * @return RowCount */ public synchronized int getRowCount(){ return queryAll().size(); } }
{ "content_hash": "a1524990e1d30f4442e28d1c26ebac40", "timestamp": "", "source": "github", "line_count": 178, "max_line_length": 116, "avg_line_length": 25.01123595505618, "alnum_prop": 0.6199460916442049, "repo_name": "Jayin/ETips", "id": "ced6591a1abc2305e63778ccf49e2cd4af832999", "size": "4624", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/meizhuo/etips/db/MsgCenterDAO.java", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "714535" }, { "name": "Java", "bytes": "580836" } ], "symlink_target": "" }
package com.twosigma.beaker.table.serializer; import com.twosigma.beaker.table.highlight.HeatmapHighlighter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import java.io.IOException; public class HeatmapHighlighterSerializer<H extends HeatmapHighlighter> extends JsonSerializer<H> { @Override public void serialize(H value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { synchronized (value) { jgen.writeStartObject(); serializeObj(value, jgen, provider); jgen.writeEndObject(); } } protected void serializeObj(H value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeObjectField("type", value.getClass().getSimpleName()); jgen.writeObjectField("colName", value.getColName()); jgen.writeObjectField("style", value.getStyle()); jgen.writeObjectField("minVal", value.getMinVal()); jgen.writeObjectField("maxVal", value.getMaxVal()); jgen.writeObjectField("minColor", value.getMinColor()); jgen.writeObjectField("maxColor", value.getMaxColor()); } }
{ "content_hash": "b5c4da05177aaba28e38fbc7ed74e1ce", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 99, "avg_line_length": 33.714285714285715, "alnum_prop": 0.711864406779661, "repo_name": "ScottPJones/beaker-notebook", "id": "96e30a91a61f68b9c3e1f52b8dc70d9e6b129816", "size": "2038", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "kernel/base/src/main/java/com/twosigma/beaker/table/serializer/HeatmapHighlighterSerializer.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "47603" }, { "name": "C++", "bytes": "9890" }, { "name": "CSS", "bytes": "14836" }, { "name": "HTML", "bytes": "4901" }, { "name": "Java", "bytes": "2257909" }, { "name": "JavaScript", "bytes": "656859" }, { "name": "Jupyter Notebook", "bytes": "1361818" }, { "name": "Python", "bytes": "57917" }, { "name": "Scala", "bytes": "3664" } ], "symlink_target": "" }
from sqlalchemy import (Column, ForeignKey, MetaData, PrimaryKeyConstraint, Table, UniqueConstraint) from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.types import * from sqlalchemy.orm import backref, relationship from pokedex.db import tables as dex_tables from pokedex.db import markdown from pokedex.db.tables import TableBase, create_translation_table pokedex_classes = list(dex_tables.mapped_classes) def make_id(): return Column(Integer, primary_key=True, nullable=False, info=dict(description="A numeric ID")) def make_identifier(length): return Column(Unicode(length), nullable=False, unique=True, index=True, info=dict(description=u"An identifier", format='identifier')) def set_print_sort_key(set_print): if set_print.set.release_date: release_key = set_print.set.release_date.timetuple() else: release_key = (1e100, 1e100) return release_key, set_print.set.identifier, set_print.number class Card(TableBase): __tablename__ = 'tcg_cards' __singlename__ = 'tcg_card' id = make_id() stage_id = Column(Integer, ForeignKey('tcg_stages.id'), nullable=True, info=dict(description="ID of the card's evolution stage, if any")) class_id = Column(Integer, ForeignKey('tcg_classes.id'), nullable=True, index=True, info=dict(description="The ID of the card class")) family_id = Column(Integer, ForeignKey('tcg_card_families.id'), nullable=False, index=True, info=dict(description="ID of the card's family")) hp = Column(Integer, nullable=True, info=dict(description="The card's HP, if any")) retreat_cost = Column(Integer, nullable=True, info=dict(description="The card retreat cost, if any")) # TODO: legal is non-normal, but so far we lack data to compute it legal = Column(Boolean, nullable=False, info=dict(description="The card's legality in Modified")) @property def name(self): return self.family.name @property def types(self): return tuple(ct.type for ct in self.card_types) @property def mechanics(self): return tuple(cm.mechanic for cm in self.card_mechanics) @property def subclasses(self): return tuple(cs.subclass for cs in self.card_subclasses) @property def set_prints(self): set_prints = [sp for p in self.prints for sp in p.set_prints] set_prints.sort(key=set_print_sort_key) return set_prints class Print(TableBase): __tablename__ = 'tcg_prints' __singlename__ = 'tcg_print' id = make_id() card_id = Column(Integer, ForeignKey('tcg_cards.id'), nullable=False, index=True, info=dict(description="The ID of the card")) pokemon_flavor_id = Column(Integer, ForeignKey('tcg_pokemon_flavors.id'), nullable=True, info=dict(description="ID of Pokémon flavor info, if any")) # TODO: Reprint note # TODO: Filename card_release_date = Column(DateTime, nullable=True, info=dict(description="The release date, if different from set")) card_ban_date = Column(DateTime, nullable=True, info=dict(description="Modified ban date, if different from set")) holographic = Column(Boolean, nullable=False, info=dict(description="True iff the card is holographic")) rarity_id = Column(Integer, ForeignKey('tcg_rarities.id'), nullable=True, index=True, info=dict(description="The ID of the rarity")) @property def illustrators(self): return [pi.illustrator for pi in self.print_illustrators] @property def set_prints(self): return sorted(self._set_prints, key=set_print_sort_key) class TCGType(TableBase): __tablename__ = 'tcg_types' __singlename__ = 'tcg_type' load_from_csv = True id = make_id() identifier = make_identifier(10) initial = Column(Unicode(1), nullable=False, unique=True, info=dict(description=u"Unique shorthand initial", format='plaintext')) game_type_id = Column(Integer, ForeignKey(dex_tables.Type.id), nullable=False, index=True, info=dict(description="ID of the type's handheld game counterpart")) create_translation_table('tcg_type_names', TCGType, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The type name", format='plaintext', official=True)), ) class CardType(TableBase): __tablename__ = 'tcg_card_types' card_id = Column(Integer, ForeignKey('tcg_cards.id'), nullable=False, primary_key=True, info=dict(description="The ID of the card")) type_id = Column(Integer, ForeignKey('tcg_types.id'), nullable=False, primary_key=True, index=True, info=dict(description="The ID of the type")) order = Column(Integer, nullable=False, info=dict(description="Type's sort order on the card")) class Class(TableBase): __tablename__ = 'tcg_classes' __singlename__ = 'tcg_class' load_from_csv = True id = make_id() identifier = make_identifier(10) create_translation_table('tcg_class_names', Class, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The class name", format='plaintext', official=True)), ) class Stage(TableBase): __tablename__ = 'tcg_stages' __singlename__ = 'tcg_stage' load_from_csv = True id = make_id() identifier = make_identifier(10) create_translation_table('tcg_stage_names', Stage, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The stage name", format='plaintext', official=True)), ) class Subclass(TableBase): """Trainer type (Item, Stadium, Supporter, ace spec, etc)""" __tablename__ = 'tcg_subclasses' __singlename__ = 'tcg_subclass' id = make_id() identifier = make_identifier(10) create_translation_table('tcg_subclass_names', Subclass, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The class name", format='plaintext', official=True)), ) class CardSubclass(TableBase): __tablename__ = 'tcg_card_subclasses' card_id = Column(Integer, ForeignKey('tcg_cards.id'), nullable=False, primary_key=True, info=dict(description="The ID of the card")) subclass_id = Column(Integer, ForeignKey('tcg_subclasses.id'), nullable=False, primary_key=True, index=True, info=dict(description="The ID of the subclass")) order = Column(Integer, nullable=False, info=dict(description="Order of appearace on card")) class Mechanic(TableBase): # Card Mechanic, Attack, PokéPower, PokéBody, Ability, Poké-Item, Text __tablename__ = 'tcg_mechanics' __singlename__ = 'tcg_mechanic' id = make_id() class_id = Column(Integer, ForeignKey('tcg_mechanic_classes.id'), nullable=False, index=True, info=dict(description="The ID of the mechanic class")) damage_base = Column(Integer, nullable=True, info=dict(description="Base attack damage, if applicable")) damage_modifier = Column(Unicode(1), nullable=True, info=dict(description="Attack damage modifier, if applicable")) @property def cost_string(self): costs = sorted(self.costs, key=lambda cost: cost.order) parts = [] for cost in costs: parts += cost.type.initial * cost.amount return ''.join(parts) create_translation_table('tcg_mechanic_names', Mechanic, 'names', name = Column(Unicode(32), nullable=True, index=True, info=dict(description="The class name", format='plaintext', official=True)), ) create_translation_table('tcg_mechanic_effects', Mechanic, 'effects', effect = Column(Unicode(5120), nullable=True, info=dict(description="A detailed description of the effect", format='markdown', official=True, string_getter=markdown.MarkdownString)), ) class MechanicClass(TableBase): __tablename__ = 'tcg_mechanic_classes' __singlename__ = 'tcg_mechanic_class' load_from_csv = True id = make_id() identifier = make_identifier(10) create_translation_table('tcg_mechanic_class_names', MechanicClass, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The name", format='plaintext', official=True)), ) class Rarity(TableBase): __tablename__ = 'tcg_rarities' __singlename__ = 'tcg_rarity' load_from_csv = True id = make_id() identifier = make_identifier(10) symbol = Column(Unicode(3), nullable=False, info=dict(description=u"A symbol of the rarity, such as ●, ◆, ★")) create_translation_table('tcg_rarity_names', Rarity, 'names', name = Column(Unicode(10), nullable=False, index=True, info=dict(description="The name", format='plaintext', official=True)), ) class MechanicCost(TableBase): __tablename__ = 'tcg_mechanic_costs' __singlename__ = 'tcg_mechanic_cost' mechanic_id = Column(Integer, ForeignKey('tcg_mechanics.id'), primary_key=True, nullable=False, info=dict(description=u"The ID of the mechanic")) type_id = Column(Integer, ForeignKey('tcg_types.id'), primary_key=True, nullable=False, info=dict(description=u"The type of Energy")) amount = Column(Integer, nullable=False, info=dict(description=u"The amount of this Energy required")) order = Column(Integer, primary_key=True, nullable=False, info=dict(description=u"Order of appearance on card.")) class CardMechanic(TableBase): __tablename__ = 'tcg_card_mechanics' card_id = Column(Integer, ForeignKey('tcg_cards.id'), primary_key=True, nullable=False, info=dict(description="The ID of the card")) mechanic_id = Column(Integer, ForeignKey('tcg_mechanics.id'), primary_key=True, nullable=False, index=True, info=dict(description="The ID of the mechanic")) order = Column(Integer, primary_key=True, nullable=False, info=dict(description=u"Order of appearance on card.")) class DamageModifier(TableBase): """Damage modifiers such as Weaknesses and Resistances""" __tablename__ = 'tcg_damage_modifiers' __singlename__ = 'tcg_damage_modifier' card_id = Column(Integer, ForeignKey('tcg_cards.id'), primary_key=True, nullable=False, info=dict(description=u"The ID of the card")) type_id = Column(Integer, ForeignKey('tcg_types.id'), primary_key=True, nullable=False, index=True, info=dict(description=u"The type this card is weak/resistant to")) operation = Column(Unicode(2), nullable=False, info=dict(description=u"The operator in the damage adjustment")) amount = Column(Integer, nullable=False, info=dict(description=u"The number in the damage adjustment")) order = Column(Integer, primary_key=True, nullable=False, info=dict(description=u"Order of appearance on card.")) class PokemonFlavor(TableBase): __tablename__ = 'tcg_pokemon_flavors' __singlename__ = 'tcg_pokemon_flavor' id = make_id() species_id = Column(Integer, ForeignKey(dex_tables.PokemonSpecies.id), nullable=True, info=dict(description=u"The ID of the Pokémon species")) height = Column(Integer, nullable=True, info=dict(description="Height in pounds")) weight = Column(Integer, nullable=True, info=dict(description="Weight in inches")) create_translation_table('tcg_pokemon_flavor', PokemonFlavor, 'flavor', genus = Column(Unicode(16), nullable=True, index=True, info=dict(description="The species, if different from games", format='plaintext', official=True)), dex_entry = Column(Unicode(256), nullable=True, index=True, info=dict(description="The 'dex entry, if different from games", format='plaintext', official=True)), ) class Set(TableBase): __tablename__ = 'tcg_sets' __singlename__ = 'tcg_set' load_from_csv = True id = make_id() identifier = make_identifier(30) total = Column(Integer, nullable=True, info=dict(description="Number of cards in the set, if applicable")) # TODO: sub-sets release_date = Column(Date, nullable=True, info=dict(description="The release date")) ban_date = Column(Date, nullable=True, info=dict(description="Modified ban date")) create_translation_table('tcg_set_names', Set, 'names', name = Column(Unicode(30), nullable=False, index=True, info=dict(description="The name", format='plaintext', official=True)), ) class SetPrint(TableBase): __tablename__ = 'tcg_set_prints' __singlename__ = 'tcg_set_print' set_id = Column(Integer, ForeignKey('tcg_sets.id'), nullable=False, primary_key=True, info=dict(description="The ID of the set")) print_id = Column(Integer, ForeignKey('tcg_prints.id'), nullable=False, primary_key=True, index=True, info=dict(description="The ID of the print")) number = Column(Unicode(5), nullable=True, info=dict(description='The card "number" in the set (may not be actually numeric)')) order = Column(Integer, nullable=True, info=dict(description="Sort order inside the set")) @property def card(self): return self.print_.card class Illustrator(TableBase): __tablename__ = 'tcg_illustrators' __singlename__ = 'tcg_illustrator' id = make_id() identifier = make_identifier(50) name = Column(Unicode(50), nullable=False, info=dict(description="Name of the illustrator")) class PrintIllustrator(TableBase): __tablename__ = 'tcg_print_illustrators' print_id = Column(Integer, ForeignKey('tcg_prints.id'), primary_key=True, nullable=False, info=dict(description="The ID of the print")) illustrator_id = Column(Integer, ForeignKey('tcg_illustrators.id'), primary_key=True, nullable=False, index=True, info=dict(description="The ID of the illustrator")) order = Column(Integer, primary_key=True, nullable=False, info=dict(description=u"Order of appearance on card.")) class Scan(TableBase): __tablename__ = 'tcg_scans' __singlename__ = 'tcg_scan' id = make_id() print_id = Column(Integer, ForeignKey('tcg_prints.id'), nullable=False, index=True, info=dict(description=u"The ID of the print this is a scan of")) filename = Column(Unicode(30), nullable=False, info=dict(description="Filename for this scan")) order = Column(Integer, nullable=False, info=dict(description=u"Order for scan galleries.")) class CardFamily(TableBase): """Set of all cards that share the same name""" # The name of a card is actually important for mechanics, so it seems # a bit icky to stick it on "card" and leave it at the mercy of # translations. So, we have card family objects in the DB. # (Also: less translation needed) __tablename__ = 'tcg_card_families' __singlename__ = 'tcg_card_family' id = make_id() identifier = make_identifier(32) @property def set_prints(self): set_prints = [sp for c in self.cards for p in c.prints for sp in p.set_prints] set_prints.sort(key=set_print_sort_key) return set_prints create_translation_table('tcg_card_family_names', CardFamily, 'names', name = Column(Unicode(32), nullable=False, index=True, info=dict(description="The name", format='plaintext', official=True)), ) class Evolution(TableBase): __tablename__ = 'tcg_evolutions' __singlename__ = 'tcg_evolution' card_id = Column(Integer, ForeignKey('tcg_cards.id'), primary_key=True, nullable=False, info=dict(description=u"The ID of the card the evolution appears on")) family_id = Column(Integer, ForeignKey('tcg_card_families.id'), primary_key=True, nullable=False, index=True, info=dict(description=u"The ID of the family")) family_to_card = Column(Boolean, nullable=False, info=dict(description=u"True for 'evolves from', false for 'evolves to'")) order = Column(Integer, nullable=False, info=dict(description=u"Order of appearance on card.")) _pokedex_classes_set = set(pokedex_classes) tcg_classes = [c for c in dex_tables.mapped_classes if c not in _pokedex_classes_set] Card.class_ = relationship(Class, backref='cards') Card.stage = relationship(Stage, backref='cards') Card.family = relationship(CardFamily, backref='cards') Print.card = relationship(Card, backref='prints') Print.pokemon_flavor = relationship(PokemonFlavor, backref='prints') Print.rarity = relationship(Rarity, backref='prints') TCGType.game_type = relationship(dex_tables.Type) CardType.card = relationship(Card, backref=backref( 'card_types', order_by=CardType.order.asc())) CardType.type = relationship(TCGType, backref='card_types') CardSubclass.card = relationship(Card, backref=backref( 'card_subclasses', order_by=CardSubclass.order.asc())) CardSubclass.subclass = relationship(Subclass, backref='card_subclasses') Mechanic.class_ = relationship(MechanicClass, backref='mechanics') MechanicCost.mechanic = relationship(Mechanic, backref=backref( 'costs', order_by=MechanicCost.order.asc())) MechanicCost.type = relationship(TCGType) DamageModifier.card = relationship(Card, backref=backref( 'damage_modifiers', order_by=DamageModifier.order.asc())) DamageModifier.type = relationship(TCGType, backref='damage_modifiers') CardMechanic.card = relationship(Card, backref=backref( 'card_mechanics', order_by=CardMechanic.order.asc())) CardMechanic.mechanic = relationship(Mechanic, backref='card_mechanics') PokemonFlavor.species = relationship(dex_tables.PokemonSpecies) Set.prints = association_proxy('set_prints', 'print_') SetPrint.print_ = relationship(Print, backref='set_prints') SetPrint.set = relationship(Set, backref=backref( 'set_prints', order_by=(SetPrint.order.asc(), SetPrint.number.asc()))) PrintIllustrator.print_ = relationship(Print, backref='print_illustrators') PrintIllustrator.illustrator = relationship(Illustrator, backref=backref( 'print_illustrators', order_by=(PrintIllustrator.order))) Scan.print_ = relationship(Print, backref=backref( 'scans', order_by=Scan.order.asc())) Evolution.card = relationship(Card, backref=backref( 'evolutions', order_by=Evolution.order.asc())) Evolution.family = relationship(CardFamily, backref='evolutions')
{ "content_hash": "7ee576e3ce7a43d692a1de55de6c8ac3", "timestamp": "", "source": "github", "line_count": 478, "max_line_length": 92, "avg_line_length": 38.91004184100419, "alnum_prop": 0.6775633098553686, "repo_name": "encukou/ptcgdex", "id": "4ce2d74847bb4efd228583e374529fffdfb05649", "size": "18629", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ptcgdex/tcg_tables.py", "mode": "33188", "license": "mit", "language": [ { "name": "Python", "bytes": "60114" } ], "symlink_target": "" }
/* * global.h * * Created on: Apr 5, 2013 * Authors: vgomez, Sep Thijssen */ #ifndef GLOBAL_H_ #define GLOBAL_H_ #include <vector> #include <math.h> #include <iostream> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <ctime> #include <hal_quadrotor/State.h> #define SIZE_MSG 5 using namespace std; // Message structure // IIIII.XXX.xxx.YYY.yyy.ZZZ.zzz.UUU.uuu.VVV.vvv.WWW.vvv // IIIII identifier of the UVA // XXX.xxx position x // YYY.yyy position y // ZZZ.zzz position z // UUU.uuu velocity x // VVV.vvv velocity y // WWW.www velocity z typedef vector<double> vec; typedef vector<vec> vvec; template<typename G> ostream& operator<<(ostream& os, const vector<G>& v) { typename vector<G>::const_iterator it; for (it=v.begin(); it!=v.end(); it++) os << *it << " "; os << endl; return os; } string getState(const hal_quadrotor::State::ConstPtr& msg); #endif /* GLOBAL_H_ */
{ "content_hash": "39d5975e7377bb57f6c845be73dd6dad", "timestamp": "", "source": "github", "line_count": 51, "max_line_length": 59, "avg_line_length": 17.980392156862745, "alnum_prop": 0.6673936750272628, "repo_name": "jiangchenzhu/crates_zhejiang", "id": "aa993eaf1353cac23080f88901a097233979ab3c", "size": "917", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "thirdparty/cm_picontrol/pi/global.h", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "91195" }, { "name": "C++", "bytes": "398461" }, { "name": "CMake", "bytes": "14527" }, { "name": "Protocol Buffer", "bytes": "1645" }, { "name": "Shell", "bytes": "4795" } ], "symlink_target": "" }
package com.github.tomtung.latex2unicode.helper object Style { val alias = Map( "\\bf" -> "\\textbf", "\\cal" -> "\\textcal", "\\it" -> "\\textit", "\\tt" -> "\\texttt" ) val names: Set[String] = alias.keySet def translate(command: String, text: String): String = { if (!names.contains(command)) { throw new IllegalArgumentException(s"Unknown command: $command") } Unary.translate(alias(command), text) } }
{ "content_hash": "3137b9a1dfc709946f23565228b38c34", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 70, "avg_line_length": 22.75, "alnum_prop": 0.6, "repo_name": "tomtung/latex2unicode", "id": "d61ee2947ca223085ab5da81fc49cf6ec6531dbe", "size": "455", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/scala/com/github/tomtung/latex2unicode/helper/Style.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Scala", "bytes": "48035" } ], "symlink_target": "" }
<?php namespace Redmine\Api; /** * Listing issues, searching, editing and closing your projects issues. * * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues * @author Kevin Saliou <kevin at saliou dot name> */ class Issue extends AbstractApi { const PRIO_LOW = 1; const PRIO_NORMAL = 2; const PRIO_HIGH = 3; const PRIO_URGENT = 4; const PRIO_IMMEDIATE = 5; /** * List issues * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues * available $params : * - offset: skip this number of issues in response (optional) * - limit: number of issues per page (optional) * - sort: column to sort with. Append :desc to invert the order. * - project_id: get issues from the project with the given id, where id is either project id or project identifier * - tracker_id: get issues from the tracker with the given id * - status_id: get issues with the given status id only. Possible values: open, closed, * to get open and closed issues, status id * - assigned_to_id: get issues which are assigned to the given user id * - cf_x: get issues with the given value for custom field with an ID of x. (Custom field must have 'used as a filter' checked.) * - query_id : id of the previously saved query * * @param array $params the additional parameters (cf avaiable $params above) * @return array list of issues found */ public function all(array $params = array()) { return $this->retrieveAll('/issues.json', $params); } /** * Get extended information about an issue gitven its id * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Using-JSON * available $params : * include: fetch associated data (optional). Possible values: children, attachments, relations, changesets and journals * * @param string $id the issue id * @param array $params extra associated data * @return array information about the issue */ public function show($id, array $params = array()) { return $this->get('/issues/'.urlencode($id).'.json?'.http_build_query($params)); } /** * Build the XML for an issue * @param array $params for the new/updated issue data * @return SimpleXMLElement */ private function buildXML(array $params = array()) { $xml = new SimpleXMLElement('<?xml version="1.0"?><issue></issue>'); foreach ($params as $k => $v) { if ('custom_fields' === $k && is_array($v)) { $this->attachCustomFieldXML($xml, $v); } elseif ('watcher_user_ids' === $k && is_array($v)) { $watcher_user_ids = $xml->addChild('watcher_user_ids', ''); $watcher_user_ids->addAttribute('type', 'array'); foreach ($v as $watcher) { $watcher_user_ids->addChild('watcher_user_id', (int) $watcher); } } elseif ('uploads' === $k && is_array($v)) { $uploads_item = $xml->addChild('uploads', ''); $uploads_item->addAttribute('type', 'array'); foreach ($v as $upload) { $upload_item = $uploads_item->addChild('upload', ''); foreach ($upload as $upload_k => $upload_v) { $upload_item->addChild($upload_k, $upload_v); } } } else { $xml->addChild($k, $v); } } return $xml; } /** * Create a new issue given an array of $params * The issue is assigned to the authenticated user. * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Creating-an-issue * * @param array $params the new issue data * @return SimpleXMLElement */ public function create(array $params = array()) { $defaults = array( 'subject' => null, 'description' => null, // 'project' => null, // 'category' => null, // 'status' => null, // 'tracker' => null, // 'assigned_to' => null, // 'author' => null, 'project_id' => null, 'category_id' => null, 'priority_id' => null, 'status_id' => null, 'tracker_id' => null, 'assigned_to_id' => null, 'author_id' => null, 'due_date' => null, 'start_date' => null, 'watcher_user_ids' => null, ); $params = $this->cleanParams($params); $params = array_filter(array_merge($defaults, $params)); $xml = $this->buildXML($params); return $this->post('/issues.xml', $xml->asXML()); // $json = json_encode(array('issue' => $params)); // return $this->post('/issues.json', $json); } /** * Update issue information's by username, repo and issue number. Requires authentication. * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Updating-an-issue * * @param string $id the issue number * @param array $params * @return SimpleXMLElement */ public function update($id, array $params) { $defaults = array( 'id' => $id, 'subject' => null, 'notes' => null, // 'project' => null, // 'category' => null, // 'status' => null, // 'tracker' => null, // 'assigned_to' => null, // 'author' => null, 'category_id' => null, 'priority_id' => null, 'status_id' => null, 'tracker_id' => null, 'assigned_to_id' => null, 'due_date' => null, ); $params = $this->cleanParams($params); $params = array_filter(array_merge($defaults, $params)); $xml = $this->buildXML($params); return $this->put('/issues/'.$id.'.xml', $xml->asXML()); } /** * @param int $id * @param string $watcher_user_id * @return void */ public function addWatcher($id, $watcher_user_id) { return $this->post('/issues/'.$id.'/watchers.xml', '<user_id>'.$watcher_user_id.'</user_id>'); } /** * @param int $id * @param string $watcher_user_id * @return void */ public function removeWatcher($id, $watcher_user_id) { return $this->delete('/issues/'.$id.'/watchers/'.$watcher_user_id.'.xml', $xml->asXML()); } /** * @param int $id * @param string $status * @return void */ public function setIssueStatus($id, $status) { $statusId = $this->client->api('issue_status')->getIdByName($status); return $this->update($id, array( 'status_id' => $statusId )); } /** * @param int $id * @param string $note * @return void */ public function addNoteToIssue($id, $note) { return $this->update($id, array( 'notes' => $note )); } /** * Transforms literal identifiers to integer ids * @param array $params * @return array */ private function cleanParams(array $params = array()) { if (isset($params['project'])) { $params['project_id'] = $this->client->api('project')->getIdByName($params['project']); unset($params['project']); if (isset($params['category'])) { $params['category_id'] = $this->client->api('issue_category')->getIdByName($params['project_id'], $params['category']); unset($params['category']); } } if (isset($params['status'])) { $params['status_id'] = $this->client->api('issue_status')->getIdByName($params['status']); unset($params['status']); } if (isset($params['tracker'])) { $params['tracker_id'] = $this->client->api('tracker')->getIdByName($params['tracker']); unset($params['tracker']); } if (isset($params['assigned_to'])) { $params['assigned_to_id'] = $this->client->api('user')->getIdByUsername($params['assigned_to']); unset($params['assigned_to']); } if (isset($params['author'])) { $params['author_id'] = $this->client->api('user')->getIdByUsername($params['author']); unset($params['author']); } return $params; } /** * Attach a file to an issue issue number. Requires authentication. * @link http://www.redmine.org/projects/redmine/wiki/Rest_Issues#Updating-an-issue * * @param string $id the issue number * @param array $attachment * @return bool|string */ public function attach($id, array $attachment) { $request['issue'] = array( 'id' => $id, 'uploads' => array( 'upload' => $attachment ) ); return $this->put('/issues/'.$id.'.json', json_encode($request)); } /** * Remove a issue by issue number * * @param string $id the issue number */ public function remove($id) { return $this->delete('/issues/'.$id.'.xml'); } }
{ "content_hash": "0a1ea7ff26377faa4838bdbff97acd0e", "timestamp": "", "source": "github", "line_count": 281, "max_line_length": 135, "avg_line_length": 34.188612099644125, "alnum_prop": 0.5150411158530238, "repo_name": "BertaOctech/php-redmine-api", "id": "fd962f282e16ae843d8f96f12a0d4d06fa960a3e", "size": "9607", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/Redmine/Api/Issue.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "265226" } ], "symlink_target": "" }
#import <objc/runtime.h> #if ! __has_feature(objc_arc) #warning This file must be compiled with ARC. Use -fobjc-arc flag (or convert project to ARC). #endif @implementation XMPPMessage + (void)initialize { // We use the object_setClass method below to dynamically change the class from a standard NSXMLElement. // The size of the two classes is expected to be the same. // // If a developer adds instance methods to this class, bad things happen at runtime that are very hard to debug. // This check is here to aid future developers who may make this mistake. // // For Fearless And Experienced Objective-C Developers: // It may be possible to support adding instance variables to this class if you seriously need it. // To do so, try realloc'ing self after altering the class, and then initialize your variables. size_t superSize = class_getInstanceSize([NSXMLElement class]); size_t ourSize = class_getInstanceSize([XMPPMessage class]); if (superSize != ourSize) { NSLog(@"Adding instance variables to XMPPMessage is not currently supported!"); exit(15); } } + (XMPPMessage *)messageFromElement:(NSXMLElement *)element { object_setClass(element, [XMPPMessage class]); return (XMPPMessage *)element; } + (XMPPMessage *)message { return [[XMPPMessage alloc] init]; } + (XMPPMessage *)messageWithType:(NSString *)type { return [[XMPPMessage alloc] initWithType:type to:nil]; } + (XMPPMessage *)messageWithType:(NSString *)type to:(XMPPJID *)to { return [[XMPPMessage alloc] initWithType:type to:to]; } + (XMPPMessage *)messageWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid { return [[XMPPMessage alloc] initWithType:type to:jid elementID:eid]; } + (XMPPMessage *)messageWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement { return [[XMPPMessage alloc] initWithType:type to:jid elementID:eid child:childElement]; } + (XMPPMessage *)messageWithType:(NSString *)type elementID:(NSString *)eid { return [[XMPPMessage alloc] initWithType:type elementID:eid]; } + (XMPPMessage *)messageWithType:(NSString *)type elementID:(NSString *)eid child:(NSXMLElement *)childElement { return [[XMPPMessage alloc] initWithType:type elementID:eid child:childElement]; } + (XMPPMessage *)messageWithType:(NSString *)type child:(NSXMLElement *)childElement { return [[XMPPMessage alloc] initWithType:type child:childElement]; } - (id)init { return [self initWithType:nil to:nil elementID:nil child:nil]; } - (id)initWithType:(NSString *)type { return [self initWithType:type to:nil elementID:nil child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid { return [self initWithType:type to:jid elementID:nil child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid { return [self initWithType:type to:jid elementID:eid child:nil]; } - (id)initWithType:(NSString *)type to:(XMPPJID *)jid elementID:(NSString *)eid child:(NSXMLElement *)childElement { if ((self = [super initWithName:@"message"])) { if (type) [self addAttributeWithName:@"type" stringValue:type]; if (jid) [self addAttributeWithName:@"to" stringValue:[jid full]]; if (eid) [self addAttributeWithName:@"id" stringValue:eid]; if (childElement) [self addChild:childElement]; } return self; } - (id)initWithType:(NSString *)type elementID:(NSString *)eid { return [self initWithType:type to:nil elementID:eid child:nil]; } - (id)initWithType:(NSString *)type elementID:(NSString *)eid child:(NSXMLElement *)childElement { return [self initWithType:type to:nil elementID:eid child:childElement]; } - (id)initWithType:(NSString *)type child:(NSXMLElement *)childElement { return [self initWithType:type to:nil elementID:nil child:childElement]; } - (id)initWithXMLString:(NSString *)string error:(NSError *__autoreleasing *)error { if((self = [super initWithXMLString:string error:error])){ self = [XMPPMessage messageFromElement:self]; } return self; } - (id)copyWithZone:(NSZone *)zone { NSXMLElement *element = [super copyWithZone:zone]; return [XMPPMessage messageFromElement:element]; } - (NSString *)body { return [[self elementForName:@"body"] stringValue]; } - (NSString *)thread { return [[self elementForName:@"thread"] stringValue]; } - (void)addBody:(NSString *)body { NSXMLElement *bodyElement = [NSXMLElement elementWithName:@"body" stringValue:body]; [self addChild:bodyElement]; } - (void)addThread:(NSString *)thread { NSXMLElement *threadElement = [NSXMLElement elementWithName:@"thread" stringValue:thread]; [self addChild:threadElement]; } - (BOOL)isChatMessage { return [[[self attributeForName:@"type"] stringValue] isEqualToString:@"chat"]; } - (BOOL)isChatMessageWithBody { if ([self isChatMessage]) { return [self isMessageWithBody]; } return NO; } - (BOOL)isErrorMessage { return [[[self attributeForName:@"type"] stringValue] isEqualToString:@"error"]; } - (NSError *)errorMessage { if (![self isErrorMessage]) { return nil; } NSXMLElement *error = [self elementForName:@"error"]; return [NSError errorWithDomain:@"urn:ietf:params:xml:ns:xmpp-stanzas" code:[error attributeIntValueForName:@"code"] userInfo:[NSDictionary dictionaryWithObject:[error compactXMLString] forKey:NSLocalizedDescriptionKey]]; } - (BOOL)isMessageWithBody { return ([self elementForName:@"body"] != nil); } @end
{ "content_hash": "a26640c35c38b3dd6eb98cbc1b10dd1d", "timestamp": "", "source": "github", "line_count": 208, "max_line_length": 131, "avg_line_length": 27.552884615384617, "alnum_prop": 0.6932472517885185, "repo_name": "supertalent1982/lyphy", "id": "5c5263fef49d2fbeb8da4cf3450806b195647a37", "size": "5808", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Library/xmpp/Core/XMPPMessage.m", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "44570" }, { "name": "JavaScript", "bytes": "8709" }, { "name": "Objective-C", "bytes": "2546109" }, { "name": "Ruby", "bytes": "91" }, { "name": "Shell", "bytes": "5636" } ], "symlink_target": "" }
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>cat.calidos.morfeu</groupId> <artifactId>morfeu-webapp</artifactId> <version>0.8.13-SNAPSHOT</version> <packaging>war</packaging> <name>Morfeu web application</name> <!-- find . -name "*.ts" -exec bash -c 'unexpand -t 4 "$0" > /tmp/a && mv -v /tmp/a "$0"' {} \; --> <description>Morfeu is an application to manage multiple APIs represented as YAML, JSON, JSX or XML documents</description> <inceptionYear>2016</inceptionYear> <properties> <jetty-http-port>8980</jetty-http-port> <jetty-stop-port>8981</jetty-stop-port> <jetty-context-path>/</jetty-context-path> <webapp-prefix>http://localhost:${jetty-http-port}${jetty-context-path}/</webapp-prefix> <resources-prefix>file://${project.basedir}/</resources-prefix> <skip-build-client>false</skip-build-client> <async-timeout>2000</async-timeout> <batik-version>1.14</batik-version> <dagger-2-version>2.35</dagger-2-version> <jackson-2-version>2.12.3</jackson-2-version> <jetty-version>10.0.3</jetty-version> <jtwig-version>5.87.0.RELEASE</jtwig-version> <jupiter-version>5.7.0</jupiter-version> <junit-platform-version>1.7.0</junit-platform-version> <selenide-version>5.20.4</selenide-version> <selenium-version>3.141.59</selenium-version> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <scm.host_>github.com</scm.host_> <developer.id_>danigiri</developer.id_> </properties> <scm> <!-- mvn -B release:prepare release:perform -Darguments=" -Dskip-build-client=true -DskipITs -Djetty.skip -DaltDeploymentRepository=REPO::default::file://$HOME/.m2/repository" --> <connection>scm:git:git@${scm.host_}:${developer.id_}/morfeu.git</connection> <url>scm:git:git@${scm.host_}:${developer.id_}/morfeu.git</url> <developerConnection>scm:git:git@${scm.host_}:${developer.id_}/morfeu.git</developerConnection> <tag>HEAD</tag> </scm> <build> <resources> <!-- skip moving node modules about --> <resource> <directory>src/main/resources</directory> <excludes> <!-- avoid duplicates --> <exclude>angular/</exclude> <exclude>metadata/</exclude> </excludes> </resource> <resource> <directory>src/test/resources</directory> </resource> <resource> <!-- helper scripts, for instance to help with the release process --> <directory>src/main/scripts</directory> <filtering>true</filtering> <targetPath>${project.build.directory}/scripts</targetPath> </resource> <resource> <!-- angular release dist folder extra materials --> <directory>src/main/resources/angular</directory> <targetPath>${project.build.directory}/dist</targetPath> </resource> <resource> <!-- application metadata, like the version, goes to the webapp root --> <directory>src/main/resources/metadata</directory> <filtering>true</filtering> <targetPath>${project.build.outputDirectory}/metadata</targetPath> </resource> </resources> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>11</source> <target>11</target> <annotationProcessorPaths> <path> <groupId>com.google.dagger</groupId> <artifactId>dagger-compiler</artifactId> <version>${dagger-2-version}</version> </path> </annotationProcessorPaths> <!-- FIXME: NEED TO DOUBLE CHECK THIS IS IN CLASSPATH --> <generatedSourcesDirectory>target/generated-sources/annotations</generatedSourcesDirectory> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> <executions> <execution> <goals> <goal>test-jar</goal> </goals> </execution> </executions> </plugin> <plugin> <!-- run test scripts --> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>3.0.0</version> <executions> <execution> <id>build-angular</id> <phase>prepare-package</phase> <goals> <goal>exec</goal> </goals> <configuration> <executable>bash</executable> <workingDirectory /> <skip>${skip-build-client}</skip> <arguments> <argument>-c</argument> <argument>chmod a+x ${project.build.directory}/scripts/angular.sh &amp;&amp; \ ${project.build.directory}/scripts/angular.sh </argument> </arguments> </configuration> </execution> </executions> </plugin> <plugin> <!-- mvn package war:war install -DarchiveClasses=true -DattachClasses=true -DskipITs -DskipTests=true -Djetty.skip --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>3.2.2</version> <configuration> <webResources> <resource> <directory>${project.build.directory}/dist</directory> <!-- add build distribution to root of WAR --> <excludes> <exclude>README</exclude> <!-- originally in the empty dist folder, not needed --> </excludes> </resource> <resource> <directory>${project.build.outputDirectory}/test-resources</directory> <!-- test material for dev env compatibility --> <targetPath>target/test-classes/test-resources</targetPath> </resource> <resource> <directory>${project.build.outputDirectory}/test-resources</directory> <!-- test material for dev env compatibility --> <targetPath>test-resources</targetPath> </resource> <resource> <directory>${project.build.outputDirectory}/metadata</directory> <!-- metadata --> <targetPath>metadata</targetPath> </resource> </webResources> <attachClasses>true</attachClasses> <!-- creates a jar with the classes and attaches an artifact --> </configuration> </plugin> <plugin> <!-- we specift the name of the releases --> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-release-plugin</artifactId> <version>3.0.0-M1</version> <configuration> <tagNameFormat>v@{project.version}</tagNameFormat> </configuration> </plugin> <plugin> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty-version}</version> <dependencies> <!-- to add GZIP compression --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-servlets</artifactId> <version>${jetty-version}</version> </dependency> </dependencies> <configuration> <dumpOnStart>false</dumpOnStart> <!-- set to true for debugging --> <!--scanIntervalSeconds>0</scanIntervalSeconds--> <reload>manual</reload> <stopPort>${jetty-stop-port}</stopPort> <stopKey>STOP</stopKey> <useTestScope>true</useTestScope> <webApp> <contextPath>${jetty-context-path}</contextPath> <!-- we add this extra classpath so jetty loads templates and all jar deps like jackson and stuff --> <!--extraClasspath>${project.build.directory}/${project.artifactId}-${project.version}/WEB-INF/lib</extraClasspath--> <resourceBases> <resourceBase>${project.build.outputDirectory}</resourceBase> <!-- data files for angular app --> <!-- fallback for testing: /morfeu/target/test-classes/test-resources/.. is ok --> <resourceBase>${basedir}</resourceBase> <!-- more data files, compatible with int tests --> <!--resourceBase>${project.build.directory}/dist</resourceBase--> </resourceBases> <webInfIncludeJarPattern>^$</webInfIncludeJarPattern> </webApp> <testClassesDirectory>${project.build.directory}/SKIPSCANTESTCLASSES</testClassesDirectory> <systemProperties> <systemProperty> <name>org.eclipse.jetty.annotations.maxWait</name> <value>60000</value> </systemProperty> <systemProperty> <!-- mvn jetty:run -D__RESOURCES_PREFIX=file://$(PWD)/ --> <name>__RESOURCES_PREFIX</name> <value>${resources-prefix}</value> </systemProperty> <systemProperty> <!-- mvn jetty:run -D__ASYNC_TIMEOUT=1000 --> <name>__ASYNC_TIMEOUT</name> <value>${async-timeout}</value> </systemProperty> </systemProperties> <httpConnector> <port>${jetty-http-port}</port> </httpConnector> </configuration> <executions> <execution> <!-- start jetty when target is integration testing --> <id>start-jetty-integration-test</id> <phase>pre-integration-test</phase> <goals> <goal>run</goal> </goals> <configuration> <scanIntervalSeconds>0</scanIntervalSeconds> <daemon>true</daemon> </configuration> </execution> <execution> <!-- stop jetty when completed integration testing--> <id>stop-jetty</id> <phase>post-integration-test</phase> <goals> <goal>stop</goal> </goals> <configuration> <stopKey>STOP</stopKey> <stopPort>${jetty-stop-port}</stopPort> </configuration> </execution> </executions> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>3.0.0-M4</version> <configuration> <excludes> <!-- no UI/integration tests in unit testing --> <exclude>**/*IntTest*</exclude> <exclude>**/*UITest*</exclude> <exclude>**/*ComponentTest*</exclude> </excludes> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-failsafe-plugin</artifactId> <version>3.0.0-M4</version> <configuration> <systemPropertyVariables> <TMP_FOLDER>${project.build.directory}/integration-tests-tmp</TMP_FOLDER> </systemPropertyVariables> </configuration> <executions> <execution> <goals> <goal>integration-test</goal> <goal>verify</goal> </goals> <configuration> <includes> <include>**/*IntTest*</include> <include>**/*UITest*</include> <include>**/*ComponentTest*</include> </includes> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <!-- DEPENDENCY INJECTION dependencies (optionals not included in the final WAR archive) --> <dependency> <groupId>com.google.dagger</groupId> <artifactId>dagger</artifactId> <version>${dagger-2-version}</version> </dependency> <dependency> <groupId>com.google.dagger</groupId> <artifactId>dagger-producers</artifactId> <version>${dagger-2-version}</version> </dependency> <dependency> <groupId>com.google.dagger</groupId> <artifactId>dagger-compiler</artifactId> <version>${dagger-2-version}</version> <optional>true</optional> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1.0.0.redhat-6</version> <!-- scope>provided</scope --> </dependency> <!-- XML Schema parsing (compatible license, see here https://xsom.java.net) --> <dependency> <groupId>com.sun.xsom</groupId> <artifactId>xsom</artifactId> <version>20140925.0.0.redhat-1</version> </dependency> <!-- Jackson JSON lib stuff --> <!-- the core, which includes Streaming API, shared low-level abstractions (but NOT data-binding) --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson-2-version}</version> </dependency> <!-- Just the annotations; use this dependency if you want to attach annotations to classes without connecting them to the code. --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson-2-version}</version> </dependency> <!-- databinding; ObjectMapper, JsonNode and related classes are here --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson-2-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>${jackson-2-version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jdk8</artifactId> <version>${jackson-2-version}</version> </dependency> <!-- JETTY RUNTIME --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-server</artifactId> <version>${jetty-version}</version> <scope>provided</scope> </dependency> <!-- HELPERS --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpasyncclient</artifactId> <version>4.1.4.redhat-00001</version> </dependency> <dependency><!-- to test dynamic preview with SVG --> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-dom</artifactId> <version>${batik-version}</version> <!-- get rid of java 1.9 module clashing old xml api dupes --> <exclusions> <exclusion> <!-- declare the exclusion here --> <groupId>xml-apis</groupId> <artifactId>xml-apis</artifactId> </exclusion> <exclusion> <!-- declare the exclusion here --> <groupId>xml-apis</groupId> <artifactId>xml-apis-ext</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.xmlgraphics</groupId> <artifactId>batik-svggen</artifactId> <version>${batik-version}</version> </dependency> <dependency> <!-- used to test the code integration --> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.200</version> </dependency> <!-- logging --> <dependency> <groupId>org.eclipse.jetty</groupId> <artifactId>jetty-slf4j-impl</artifactId> <version>${jetty-version}</version> </dependency> <!--dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.3.0-alpha5</version> <scope>provided</scope> </dependency--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>2.0.0-alpha1</version> </dependency> <!-- templating --> <dependency> <groupId>org.jtwig</groupId> <artifactId>jtwig-core</artifactId> <version>${jtwig-version}</version> </dependency> <dependency> <groupId>org.jtwig</groupId> <artifactId>jtwig-reflection</artifactId> <version>${jtwig-version}</version> </dependency> <!-- request proxying --> <dependency> <groupId>org.mitre.dsmiley.httpproxy</groupId> <artifactId>smiley-http-proxy-servlet</artifactId> <version>1.12</version> </dependency> <!-- process execution --> <dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-exec</artifactId> <version>1.12</version> </dependency> <dependency> <groupId>org.zeroturnaround</groupId> <artifactId>zt-process-killer</artifactId> <version>1.10</version> </dependency> <!-- UNIT TESTING --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>${jupiter-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>${jupiter-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> <version>${jupiter-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-launcher</artifactId> <version>${junit-platform-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-runner</artifactId> <version>${junit-platform-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>3.9.0</version> <scope>test</scope> </dependency> <!-- INTEGRATION TESTING --> <dependency> <!-- web driver manager --> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>4.4.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>${selenium-version}</version> <scope>test</scope> <exclusions> <!--exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> </exclusion--> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-firefox-driver</artifactId> </exclusion> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-ie-driver</artifactId> </exclusion> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-iphone-driver</artifactId> </exclusion> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-htmlunit-driver</artifactId> </exclusion> <exclusion> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-android-driver</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-server</artifactId> <version>${selenium-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-chrome-driver</artifactId> <version>${selenium-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>com.codeborne</groupId> <artifactId>selenide</artifactId> <version>${selenide-version}</version> <scope>test</scope> </dependency> <dependency> <groupId>org.xmlunit</groupId> <artifactId>xmlunit-core</artifactId> <version>2.8.2</version> </dependency> <dependency> <groupId>com.tngtech.archunit</groupId> <artifactId>archunit-junit5</artifactId> <version>0.18.0</version> <scope>test</scope> </dependency> </dependencies> <repositories> <!--repository> <id>Maven-Central</id> <name>Maven central</name> <url>https://repo1.maven.org/maven2/</url> </repository--> <repository> <id>Apache-releases</id> <name>Apache releases</name> <url>https://repository.apache.org/content/repositories/releases</url> </repository> <repository> <id>RedHat-GA</id> <name>RedHat GA repository</name> <url>https://maven.repository.redhat.com/ga/</url> </repository> <repository> <id>jcenter</id> <url>https://jcenter.bintray.com/</url> </repository> </repositories> <licenses> <license> <name>The Apache Software License, Version 2.0</name> <url>http://www.apache.org/licenses/LICENSE-2.0</url> <comments>Copyright (C) 2020 Daniel Giribet</comments> </license> </licenses> <developers> <developer> <id>danigiri</id> <name>Daniel Giribet</name> <email>dani AT calidos DOT cat</email> <url>http//dani.calidos.com</url> <roles> <role>creator</role> <role>developer</role> </roles> <timezone>+1</timezone> </developer> </developers> </project>
{ "content_hash": "d00ba5b3398435c9f0d0f8fdd16dc1d7", "timestamp": "", "source": "github", "line_count": 598, "max_line_length": 204, "avg_line_length": 33.30769230769231, "alnum_prop": 0.6689928707701577, "repo_name": "danigiri/morfeu", "id": "a5f674694d0a036935fed2f45f3da72978de7f3e", "size": "19918", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pom.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2492" }, { "name": "Dockerfile", "bytes": "2745" }, { "name": "HTML", "bytes": "14973" }, { "name": "Java", "bytes": "864378" }, { "name": "JavaScript", "bytes": "1882" }, { "name": "Shell", "bytes": "1837" }, { "name": "Twig", "bytes": "11586" }, { "name": "TypeScript", "bytes": "488169" } ], "symlink_target": "" }
package com.gauravbytes.singleton.perclassloader; /** * * @author Mazra, Gaurav Rai * */ public enum Singleton { INSTANCE; public void doStuff() { // } }
{ "content_hash": "8fff042200c15c12c103c43665f6517e", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 49, "avg_line_length": 12.928571428571429, "alnum_prop": 0.5966850828729282, "repo_name": "gauravrmazra/gauravbytes", "id": "fb9a899d67949708d5597c5a1f771a768c530226", "size": "181", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "singleton-java/singleton-java/src/main/java/com/gauravbytes/singleton/perclassloader/Singleton.java", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "80" }, { "name": "HTML", "bytes": "22796" }, { "name": "Java", "bytes": "330904" }, { "name": "JavaScript", "bytes": "18625" }, { "name": "Jupyter Notebook", "bytes": "349173" }, { "name": "TSQL", "bytes": "4487" }, { "name": "TypeScript", "bytes": "31895" } ], "symlink_target": "" }
function Z = projectData(X, U, K) Z = zeros(size(X, 1), K); % ====================== YOUR CODE HERE ====================== % Instructions: Compute the projection of the data using only the top K % eigenvectors in U (first K columns). % For the i-th example X(i,:), the projection on to the k-th % eigenvector is given as follows: % x = X(i, :)'; % projection_k = x' * U(:, k); U_reduce = U(:, 1:K); Z = X*U_reduce; % ============================================================= end
{ "content_hash": "08dd1f8d992d0fc44a8b7dc56c16a1f6", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 75, "avg_line_length": 43.53846153846154, "alnum_prop": 0.42402826855123676, "repo_name": "lirenjie95/DataMining", "id": "36c58c16cdd52a85dbb42ef0ee1e637541961870", "size": "566", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MachineLearning-Stanford/Assignment7/projectData.m", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "30150" }, { "name": "CMake", "bytes": "1153" }, { "name": "HTML", "bytes": "1747384" }, { "name": "Jupyter Notebook", "bytes": "2813084" }, { "name": "Matlab", "bytes": "29585" }, { "name": "Python", "bytes": "15608" }, { "name": "Shell", "bytes": "947" } ], "symlink_target": "" }
var webpack = require('webpack'); var htmlWebpackPlugin = require('html-webpack-plugin') var ExtractTextPlugin = require('extract-text-webpack-plugin'); module.exports = { entry: './src/main.ts', output: { path: './dist', filename: 'app.bundle.js', }, module: { loaders: [ { test: /\.ts$/, loader: 'ts' }, { test: /\.html$/, loader: 'html' }, { test: /\.less$/, loader: 'component-style-loader!css-loader!less-loader', //loader: ExtractTextPlugin.extract('style', 'css!less'), exclude: /node_modules/ }, { test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/, loader: 'file?name=assets/[name].[hash].[ext]' }, ] }, resolveLoader: { alias: { 'component-style-loader': require.resolve('./component-style-loader') } }, resolve: { extensions: ['', '.js', '.ts', '.less'] }, plugins: [ new htmlWebpackPlugin({ template: './src/index.html' }), new ExtractTextPlugin('styles.css') ] };
{ "content_hash": "86424b7a4ed9b8ef33971227439e7b6b", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 81, "avg_line_length": 29.24390243902439, "alnum_prop": 0.48040033361134277, "repo_name": "tariknz/wallofcolours", "id": "b28cb5d0b676459a6c1cfaac031cec3e04ca8114", "size": "1199", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "webpack.config.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "2020" }, { "name": "HTML", "bytes": "1027" }, { "name": "JavaScript", "bytes": "2604" }, { "name": "TypeScript", "bytes": "4661" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>AppcastItem - FAKE - F# Make</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" /> <script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/fake">github page</a></li> </ul> <h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>AppcastItem</h1> <div class="xmldoc"> <p>Download details for the appcast</p> </div> <h3>Record Fields</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Record Field</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1141', 1141)" onmouseover="showTip(event, '1141', 1141)"> dsaSignature </code> <div class="tip" id="1141"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L41-41" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Optional DSA signature for the archive. It is recommended to use this if the app itself is not signed</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1142', 1142)" onmouseover="showTip(event, '1142', 1142)"> length </code> <div class="tip" id="1142"> <strong>Signature:</strong> int64<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L45-45" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Length of the file in bytes</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1143', 1143)" onmouseover="showTip(event, '1143', 1143)"> mimetype </code> <div class="tip" id="1143"> <strong>Signature:</strong> MimeType<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L39-39" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Mime type of the update file, usualy octetstream</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1144', 1144)" onmouseover="showTip(event, '1144', 1144)"> minimumSystemVersion </code> <div class="tip" id="1144"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L43-43" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Optional miminal system version for the update</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1145', 1145)" onmouseover="showTip(event, '1145', 1145)"> pubdate </code> <div class="tip" id="1145"> <strong>Signature:</strong> DateTime<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L30-30" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Date when update is published</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1146', 1146)" onmouseover="showTip(event, '1146', 1146)"> shortVersion </code> <div class="tip" id="1146"> <strong>Signature:</strong> string option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L37-37" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Optional human readable version number. This will be shown to the user if present otherwise the technical version number will be used</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1147', 1147)" onmouseover="showTip(event, '1147', 1147)"> title </code> <div class="tip" id="1147"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L28-28" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>The name of the update</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1148', 1148)" onmouseover="showTip(event, '1148', 1148)"> url </code> <div class="tip" id="1148"> <strong>Signature:</strong> Uri<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L32-32" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>URI where the update files are found</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1149', 1149)" onmouseover="showTip(event, '1149', 1149)"> version </code> <div class="tip" id="1149"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/Appcast.fs#L34-34" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>Machine readable version number used to determine if an update is available by the client (should follow semver)</p> </td> </tr> </tbody> </table> </div> <div class="span3"> <a href="http://fsharp.github.io/FAKE/index.html"> <img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header">FAKE - F# Make</li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li> <li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li> <li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li> <li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li> <li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Tutorials</li> <li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li> <li><a href="http://fsharp.github.io/FAKE/cache.html">Build script caching</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li> <li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li> <li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li> <li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li> <li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li> <li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li> <li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li> <li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li> <li><a href="http://fsharp.github.io/FAKE/soft-dependencies.html">Soft dependencies</a></li> <li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li> <li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li> <li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li> <li><a href="http://fsharp.github.io/FAKE/fluentmigrator.html">FluentMigrator support</a></li> <li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li> <li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li> <li><a href="http://fsharp.github.io/FAKE/wix.html">WiX Setup Generation</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/iis.html">Fake.IIS</a></li> <li class="nav-header">Reference</li> <li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
{ "content_hash": "98da65b91345c647984ea5ff2b31e6cc", "timestamp": "", "source": "github", "line_count": 291, "max_line_length": 209, "avg_line_length": 45.04810996563574, "alnum_prop": 0.5478678770310473, "repo_name": "et1975/FsStorm", "id": "24184d6d92f736a1b613f95280c1d4d59add0f7f", "size": "13109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/build/FAKE/docs/apidocs/fake-appcast-appcastitem.html", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "293" }, { "name": "F#", "bytes": "76953" }, { "name": "Shell", "bytes": "860" } ], "symlink_target": "" }
<?php namespace lukisongroup\purchasing\controllers; use yii; use yii\web\Request; use yii\db\Query; //use yii\data\ActiveDataProvider; use yii\data\ArrayDataProvider; use yii\helpers\ArrayHelper; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use yii\helpers\Json; use yii\helpers\Url; use yii\widgets\Pjax; use lukisongroup\purchasing\models\rpt\PoReportSearch; use lukisongroup\hrd\models\Corp; use kartik\mpdf\Pdf; /** * SalesorderController implements the CRUD actions for Salesorder model. */ class PurchaseCostcenterController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(), 'actions' => [ 'delete' => ['post'], ], ], ]; } /** * Before Action Index * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function beforeAction($action){ if (Yii::$app->user->isGuest) { Yii::$app->user->logout(); $this->redirect(array('/site/login')); // } // Check only when the user is logged in if (!Yii::$app->user->isGuest) { if (Yii::$app->session['userSessionTimeout']< time() ) { // timeout Yii::$app->user->logout(); $this->redirect(array('/site/login')); // } else { //Yii::$app->user->setState('userSessionTimeout', time() + Yii::app()->params['sessionTimeoutSeconds']) ; Yii::$app->session->set('userSessionTimeout', time() + Yii::$app->params['sessionTimeoutSeconds']); return true; } } else { return true; } } private function aryCorpID(){ $datacorp = ArrayHelper::map(Corp::find()->orderBy('SORT')->asArray()->all(), 'CORP_NM','CORP_NM'); return $datacorp; } /** * Index * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionIndex() { $searchModel = new PoReportSearch(); $dataProvider = $searchModel->poReportAll(Yii::$app->request->queryParams); return $this->render('index', [ 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'aryCorpID'=>$this->aryCorpID(), ]); } /** * Creates a new Salesorder model. * If creation is successful, the browser will be redirected to the 'view' page. * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionCreate() { $Detaildinas = new Sadetail(); $dinasHeader = new Salesorder(); return $this->renderAjax('_form', [ 'Detaildinas' => $Detaildinas, 'dinasHeader' => $dinasHeader, ]); } /** * Edit Form - Add Item Barang | Tambah Barang * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionAdditem($kd) { //$Detaildinas = new Sadetail(); $Detaildinas = new AdditemValidation(); $dinasHeader = Salesorder::find()->where(['KD_SA' => $kd])->one(); $detdinas = $dinasHeader->detdinas; $employ = $dinasHeader->employe; $dept = $dinasHeader->dept; /* * Convert $dinasHeader->detdinas to ArrayDataProvider | Identity 'key' => 'ID', * @author ptrnov <piter@lukison.com> * @since 1.1 **/ $detdinasProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$detdinas, 'pagination' => [ 'pageSize' => 10, ], ]); return $this->renderAjax('additem', [ 'dinasHeader' => $dinasHeader, 'Detaildinas' => $Sadetail, 'dataProvider'=>$detdinasProvider, ]); } /** * Add Item Barang to SAVED | AJAX * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionAdditem_dinasved(){ //$Detaildinas = new Sadetail(); $Detaildinas = new AdditemValidation(); if(Yii::$app->request->isAjax){ $Detaildinas->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($Detaildinas)); }else{ if($Detaildinas->load(Yii::$app->request->post())){ if($Detaildinas->additem_dinasved()){ $hsl = \Yii::$app->request->post(); $kdro = $hsl['AdditemValidation']['kD_RO']; return $this->redirect(['/accounting/dinasles-order/edit?kd='.$kdro]); } //Request Result /* $hsl = \Yii::$app->request->post(); $kdRo = $hsl['Sadetail']['KD_SA']; $kdBarang = $hsl['Sadetail']['KD_BARANG']; $nmBarang = Barang::findOne(['KD_BARANG' => $kdBarang]); $kdUnit = $hsl['Sadetail']['UNIT']; $rqty = $hsl['Sadetail']['RQTY']; $note = $hsl['Sadetail']['NOTE']; //Request Put $Detaildinas->CREATED_AT = date('Y-m-d H:i:s'); $Detaildinas->KD_SA = $kdRo; $Detaildinas->KD_BARANG = $kdBarang; $Detaildinas->NM_BARANG = $nmBarang->NM_BARANG; $Detaildinas->UNIT = $kdUnit; $Detaildinas->RQTY = $rqty; $Detaildinas->NOTE = $note; $Detaildinas->STATUS = 0; $Detaildinas->dinasve(); return $this->redirect(['/accounting/dinasles-order/edit?kd='.$kdRo]);*/ } } } /** * actionBrgkat() select2 Kategori mendapatkan barang * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionBrgkat() { $out = []; if (isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if ($parents != null) { $kat_id = $parents[0]; $model = Barang::find()->asArray()->where(['KD_KATEGORI'=>$kat_id])->all(); foreach ($model as $key => $value) { $out[] = ['id'=>$value['KD_BARANG'],'name'=> $value['NM_BARANG']]; } echo json_encode(['output'=>$out, 'selected'=>'']); return; } } echo Json::encode(['output'=>'', 'selected'=>'']); } /** * actionBrgkat() select2 barang mendapatkan unit barang * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionBrgunit() { $out = []; if (isset($_POST['depdrop_parents'])) { $ids = $_POST['depdrop_parents']; $kat_id = empty($ids[0]) ? null : $ids[0]; $brg_id = empty($ids[1]) ? null : $ids[1]; if ($brg_id != null) { $brgu = new Barang(); $model = Barang::find()->where("KD_BARANG='". $brg_id. "'")->one(); $brgUnit = $model->unit; //foreach ($brgUnit as $value) { //$out[] = ['id'=>$value['UNIT'],'name'=> $value['NM_UNIT']]; $out[] = ['id'=>$brgUnit->KD_UNIT,'name'=> $brgUnit->NM_UNIT]; //$out[] = ['id'=>'E07','name'=> $value->NM_UNIT]; // } echo json_encode(['output'=>$out, 'selected'=>'']); return; } } echo Json::encode(['output'=>'', 'selected'=>'']); } /* * actionSimpanfirst() <- actionCreate() * First Create RO | Salesorder | Sadetail * Add: component Yii::$app->getUserOpt->Profile_user() * Add: component \Yii::$app->ambilkonci->getRoCode(); * @author ptrnov <piter@lukison.com> * @since 1.1 **/ public function actionSimpanfirst(){ $cons = \Yii::$app->db_esm; $dinasHeader = new Salesorder(); //$reqorder = new Roatribute(); $Detaildinas = new Sadetail(); $profile= Yii::$app->getUserOpt->Profile_user(); //if($Detaildinas->load(Yii::$app->request->post()) && $Detaildinas->validate()){ if($Detaildinas->load(Yii::$app->request->post())){ $hsl = \Yii::$app->request->post(); $kdUnit = $hsl['Sadetail']['UNIT']; $kdBarang = $hsl['Sadetail']['KD_BARANG']; $nmBarang = Barang::findOne(['KD_BARANG' => $kdBarang]); $rqty = $hsl['Sadetail']['RQTY']; $note = $hsl['Sadetail']['NOTE']; /* * Detail Request Order **/ $Detaildinas->KD_SA = \Yii::$app->ambilkonci->getRoCode(); $Detaildinas->UNIT = $kdUnit; $Detaildinas->CREATED_AT = date('Y-m-d H:i:s'); $Detaildinas->NM_BARANG = $nmBarang->NM_BARANG; $Detaildinas->KD_BARANG = $kdBarang; $Detaildinas->RQTY = $rqty; $Detaildinas->NOTE = $note; $Detaildinas->STATUS = 0; /* * Header Request Order **/ $getkdro=\Yii::$app->ambilkonci->getRoCode(); $dinasHeader->KD_SA =$getkdro; $dinasHeader->CREATED_AT = date('Y-m-d H:i:s'); $dinasHeader->TGL = date('Y-m-d'); $dinasHeader->ID_USER = $profile->emp->EMP_ID; $dinasHeader->EMP_NM = $profile->emp->EMP_NM .' ' .$profile->emp->EMP_NM_BLK; $dinasHeader->KD_CORP = $profile->emp->EMP_CORP_ID; $dinasHeader->KD_DEP = $profile->emp->DEP_ID; $dinasHeader->SIG1_SVGBASE64 = $profile->emp->SIGSVGBASE64; $dinasHeader->SIG1_SVGBASE30 = $profile->emp->SIGSVGBASE30; $dinasHeader->STATUS = 0; $trandinasction = $cons->beginTrandinasction(); try { if (!$Detaildinas->dinasve()) { $trandinasction->rollback(); return false; } if (!$dinasHeader->dinasve()) { $trandinasction->rollback(); return false; } $trandinasction->commit(); } catch (Exception $ex) { //print_r("error"); $trandinasction->rollback(); return false; } //return $this->redirect(['index','param'=>$getkdro]); //return $this->redirect(['index?SalesorderSearch[KD_SA]='.$getkdro]); return $this->redirect(['/accounting/dinasles-order/view?kd='.$getkdro]); }else{ return $this->redirect(['index']); } } /** * Add Request Detail * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionTambah($kd) { $searchModel = new SadetailSearch(); $dataProvider = $searchModel->searchChildRo(Yii::$app->request->queryParams,$kd); $dinasHeader = Salesorder::find()->where(['KD_SA' => $kd])->one(); $Detaildinas = new Sadetail(); return $this->renderAjax('_update', [ 'dinasHeader' => $dinasHeader, 'Detaildinas' => $Sadetail, 'detdinas' => $dinasHeader->detdinas, 'searchModel'=>$searchModel, 'dataProvider'=>$dataProvider ]); } /* * actionSimpansecondt() <- actionTambah($kd) * First Create RO |Sadetail * Add: component Yii::$app->getUserOpt->Profile_user() * Add: component \Yii::$app->ambilkonci->getRoCode(); * @author ptrnov <piter@lukison.com> * @since 1.1 **/ public function actionSimpantambah(){ $Detaildinas = new Sadetail(); if($Detaildinas->load(Yii::$app->request->post()) && $Detaildinas->validate()){ $hsl = \Yii::$app->request->post(); $kdro = $hsl['Sadetail']['KD_SA']; $kdBarang = $hsl['Sadetail']['KD_BARANG']; $nmBarang = Barang::findOne(['KD_BARANG' => $kdBarang]); $kdUnit = $hsl['Sadetail']['UNIT']; $rqty = $hsl['Sadetail']['RQTY']; $note = $hsl['Sadetail']['NOTE']; /* * Detail Request Order **/ $Detaildinas->KD_SA = $kdro; $Detaildinas->CREATED_AT = date('Y-m-d H:i:s'); $Detaildinas->NM_BARANG = $nmBarang->NM_BARANG; $Detaildinas->KD_BARANG = $kdBarang; $Detaildinas->UNIT = $kdUnit; $Detaildinas->RQTY = $rqty; $Detaildinas->NOTE = $note; $Detaildinas->STATUS = 0; $Detaildinas->dinasve(); return $this->redirect(['index?SalesorderSearch[KD_SA]='.$kdro]); }else{ return $this->redirect(['index']); } } /** * View Salesorder & Detail * @param string $id * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionView($kd) { $ro = new Salesorder(); $dinasHeader = Salesorder::find()->where(['KD_SA' => $kd])->one(); if(count($dinasHeader['KD_SA'])<>0){ $detdinas = $dinasHeader->detdinas; $employ = $dinasHeader->employe; $dept = $dinasHeader->dept; /* * Convert $dinasHeader->detdinas to ArrayDataProvider | Identity 'key' => 'ID', * @author ptrnov <piter@lukison.com> * @since 1.1 **/ $detdinasProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$detdinas, 'pagination' => [ 'pageSize' => 10, ], ]); return $this->render('view', [ 'dinasHeader' => $dinasHeader, 'detdinas' => $detdinas, 'employ' => $employ, 'dept' => $dept, 'dataProvider'=>$detdinasProvider, ]); }else{ return $this->redirect('index'); } } /** * Prosess Edit RO | Change Colomn Row | Tambah Row * @param string $id * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionEdit($kd) { /* * Init Models * @author ptrnov <piter@lukison.com> * @since 1.1 **/ $dinasHeader = Salesorder::find()->where(['KD_SA' =>$kd])->one(); if(count($dinasHeader['KD_SA'])<>0){ $detdinas = $dinasHeader->detdinas; $employ = $dinasHeader->employe; $dept = $dinasHeader->dept; /* * Convert $dinasHeader->detdinas to ArrayDataProvider | Identity 'key' => 'ID', * @author ptrnov <piter@lukison.com> * @since 1.1 **/ $detdinasProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$detdinas, 'pagination' => [ 'pageSize' => 10, ], ]); /* * Process Editable Row [Columm SQTY] * @author ptrnov <piter@lukison.com> * @since 1.1 **/ if (Yii::$app->request->post('hasEditable')) { $id = Yii::$app->request->post('editableKey'); $model = Sadetail::findOne($id); $out = Json::encode(['output'=>'', 'mesdinasge'=>'']); $post = []; $posted = current($_POST['Sadetail']); $post['Sadetail'] = $posted; if ($model->load($post)) { $model->dinasve(); $output = ''; if (isset($posted['RQTY'])) { $output = $model->RQTY; } if (isset($posted['SQTY'])) { $output = $model->SQTY; } if (isset($posted['NOTE'])) { // $output = Yii::$app->formatter->asDecimal($model->EMP_NM, 2); $output = $model->NOTE; } $out = Json::encode(['output'=>$output, 'mesdinasge'=>'']); } // return ajax json encoded response and exit echo $out; return; } /* * Render Approved View * @author ptrnov <piter@lukison.com> * @since 1.1 **/ return $this->render('edit', [ 'dinasHeader' => $dinasHeader, 'detdinas' => $detdinas, 'employ' => $employ, 'dept' => $dept, 'dataProvider'=>$detdinasProvider, ]); }else{ return $this->redirect('index'); } } /** * Cetak PDF Approvad * @param string $id * @return mixed * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionCetakpdf($kd,$v){ $dinasHeader = Salesorder::find()->where(['KD_SA' => $kd])->one(); /*Noted check by status approval =1 header table | chek error record jika kosong*/ $detdinas = $dinasHeader->detdinas; $employ = $dinasHeader->employe; $dept = $dinasHeader->dept; if ($v==101){ $filterPdf="KD_SA='".$kd."' AND (STATUS='101' OR STATUS='10')"; }elseif($v!=101){ $filterPdf="KD_SA='".$kd."' AND STATUS<>'3'"; } $Detaildinas = Sadetail::find()->where($filterPdf)->all(); /* PR Filter Status Output to Grid print*/ $dataProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$Detaildinas,//$detdinas, 'pagination' => [ 'pageSize' => 20, ], ]); //PR //$dataProviderFilter = $dataProvider->getModels(); /* $StatusFilter = ["101","10"]; $test1 = ArrayHelper::where($dataProviderFilter, function($key, $StatusFilter) { return is_string($value); }); print_r($test1); */ $content = $this->renderPartial( 'pdfview', [ 'dinasHeader' => $dinasHeader, 'detdinas' => $detdinas, 'employ' => $employ, 'dept' => $dept, 'dataProvider' => $dataProvider, ]); $pdf = new Pdf([ // set to use core fonts only 'mode' => Pdf::MODE_CORE, // A4 paper format 'format' => Pdf::FORMAT_A4, // portrait orientation 'orientation' => Pdf::ORIENT_PORTRAIT, // stream to browser inline 'destination' => Pdf::DEST_BROWSER, // your html content input 'content' => $content, // format content from your own css file if needed or use the // enhanced bootstrap css built by Krajee for mPDF formatting //D:\xampp\htdocs\advanced\lukisongroup\web\widget\pdf-asset 'cssFile' => '@lukisongroup/web/widget/pdf-asset/kv-mpdf-bootstrap.min.css', // any css to be embedded if required 'cssInline' => '.kv-heading-1{font-size:12px}', // set mPDF properties on the fly 'options' => ['title' => 'Form Request Order','subject'=>'ro'], // call mPDF methods on the fly 'methods' => [ 'SetHeader'=>['Copyright@LukisonGroup '.date("r")], 'SetFooter'=>['{PAGENO}'], ] ]); return $pdf->render(); } /** * On Approval View * Approved_Sadetail | Sadetail->ID | $Detaildinas->STATUS = 101; * Approved = 101 * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionApproved_dinasdetail() { if (Yii::$app->request->isAjax) { $request= Yii::$app->request; $id=$request->post('id'); //\Yii::$app->response->format = Response::FORMAT_JSON; $Detaildinas = Sadetail::findOne($id); $Detaildinas->STATUS = 101; //$ro->NM_BARANG='' $Detaildinas->dinasve(); return true; } } /** * On Approval View * Reject_Sadetail | Sadetail->ID | $Sadetail->STATUS = 4; * Reject = 4 * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionReject_dinasdetail() { if (Yii::$app->request->isAjax) { $request= Yii::$app->request; $id=$request->post('id'); $Detaildinas = Sadetail::findOne($id); $Detaildinas->STATUS = 4; $Detaildinas->dinasve(); return true; } } /** * On Approval View * Canclet_Sadetail | Sadetail->ID | $Sadetail->STATUS = 4; * Cancel = 0 * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionCancel_dinasdetail() { if (Yii::$app->request->isAjax) { $request= Yii::$app->request; $id=$request->post('id'); $Detaildinas = Sadetail::findOne($id); $Detaildinas->STATUS = 0; $Detaildinas->dinasve(); return true; } } /** * Hapus Ro * @param string $id * @return mixed * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionHapus_item($kode,$id) { new Sadetail(); $ro = Sadetail::findOne($id); $ro->STATUS = 3; $ro->dinasve(); //$this->findModel($id)->delete(); return $this->redirect(['buatro','id'=>$kode]); } /** * Action Prosess Approval Colomn Row * @param string $id * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function actionApproved($kd) { /* * Init Models * @author ptrnov <piter@lukison.com> * @since 1.1 **/ //$ro = new Salesorder(); $dinasHeader = Salesorder::find()->where(['KD_SA' =>$kd])->one(); $detdinas = $dinasHeader->detdinas; $employ = $dinasHeader->employe; $dept = $dinasHeader->dept; /* * Convert $dinasHeader->detdinas to ArrayDataProvider | Identity 'key' => 'ID', * @author ptrnov <piter@lukison.com> * @since 1.1 **/ $detdinasProvider = new ArrayDataProvider([ 'key' => 'ID', 'allModels'=>$detdinas, 'pagination' => [ 'pageSize' => 10, ], ]); /* * Process Editable Row [Columm SQTY] * @author ptrnov <piter@lukison.com> * @since 1.1 **/ if (Yii::$app->request->post('hasEditable')) { $id = Yii::$app->request->post('editableKey'); $model = Sadetail::findOne($id); $out = Json::encode(['output'=>'', 'mesdinasge'=>'']); $post = []; $posted = current($_POST['Sadetail']); $post['Sadetail'] = $posted; if ($model->load($post)) { $model->dinasve(); $output = ''; if (isset($posted['RQTY'])) { $output = $model->RQTY; } if (isset($posted['SQTY'])) { $output = $model->SQTY; } if (isset($posted['NOTE'])) { // $output = Yii::$app->formatter->asDecimal($model->EMP_NM, 2); $output = $model->NOTE; } $out = Json::encode(['output'=>$output, 'mesdinasge'=>'']); } // return ajax json encoded response and exit echo $out; return; } /* * Render Approved View * @author ptrnov <piter@lukison.com> * @since 1.1 **/ return $this->render('approved', [ 'dinasHeader' => $dinasHeader, 'detdinas' => $detdinas, 'employ' => $employ, 'dept' => $dept, 'dataProvider'=>$detdinasProvider, ]); } public function actionApproved_authorize($kd){ $dinasFormlogin = new LoginForm(); $dinasHeader = Salesorder::find()->where(['KD_SA' =>$kd])->one(); $employe = $dinasHeader->employe; return $this->renderAjax('login_signature', [ 'dinasHeader' => $dinasHeader, 'employe' => $employe, 'dinasFormlogin' => $dinasFormlogin, ]); } /* * Sign Approval Status = 101 * Class Model Salesorder->Status = 101 [Approvad] * Class Model Sadetail->Status = 101 [Approvad] * @author ptrnov <piter@lukison.com> * @since 1.1 **/ //public function actionApproved_sign(){ public function actionApprovedAuthorizeSave(){ $dinasFormlogin = new LoginForm(); /*Ajax Load*/ if(Yii::$app->request->isAjax){ $dinasFormlogin->load(Yii::$app->request->post()); return Json::encode(\yii\widgets\ActiveForm::validate($dinasFormlogin)); }else{ /*Normal Load*/ if($dinasFormlogin->load(Yii::$app->request->post())){ if ($dinasFormlogin->loginformdinas_dinasved()){ $hsl = \Yii::$app->request->post(); $kdro = $hsl['LoginForm']['kdro']; return $this->redirect(['/accounting/dinasles-order/approved','kd'=>$kdro]); } } } } /** * Updates an existing Salesorder model. * If update is successful, the browser will be redirected to the 'view' page. * @param string $id * @return mixed */ public function actionUpdate($id) { $model = $this->findModel($id); if ($model->load(Yii::$app->request->post()) && $model->dinasve()) { return $this->redirect(['view', 'id' => $model->ID]); } else { return $this->render('update', [ 'model' => $model, ]); } } /* * Hapus RO |Header|Detail| * STATUS =3 [DELETE] * @author ptrnov <piter@lukison.com> * @since 1.1 **/ public function actionHapusro($kd) { $model =Salesorder::find()->where(['KD_SA' =>$kd])->one(); $model->STATUS=3; $model->dinasve(); $model =Sadetail::find()->where(['KD_SA' =>$kd])->one(); $model->STATUS=3; $model->dinasve(); return Yii::$app->getResponse()->redirect(['/accounting/dinasles-order/index']); } /** * Deletes an existing Salesorder model. * If deletion is successful, the browser will be redirected to the 'index' page. * @param string $id * @return mixed */ public function actionDelete($id) { $this->findModel($id)->delete(); return $this->redirect(['index']); } public function actionCreatepo() { return $this->render('createpo'); } /** * Finds the Salesorder model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. * @param string $id * @return Salesorder the loaded model * @throws NotFoundHttpException if the model cannot be found */ protected function findModel($id) { if (($model = Salesorder::findOne($id)) !== null) { return $model; } else { throw new NotFoundHttpException('The requested page does not exist.'); } } } ?>
{ "content_hash": "516e53be8431124918755993b9ece19f", "timestamp": "", "source": "github", "line_count": 830, "max_line_length": 154, "avg_line_length": 29.002409638554216, "alnum_prop": 0.5599867065470255, "repo_name": "adem-team/advanced", "id": "d8993a57ead361292760daf1223256002a92b2cb", "size": "24072", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lukisongroup/purchasing/controllers/PurchaseCostcenterController.php", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "ApacheConf", "bytes": "418" }, { "name": "Batchfile", "bytes": "1026" }, { "name": "CSS", "bytes": "6104411" }, { "name": "HTML", "bytes": "273675" }, { "name": "JavaScript", "bytes": "20829127" }, { "name": "PHP", "bytes": "21849498" } ], "symlink_target": "" }
package org.apache.hadoop.examples.priorityiteration; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Iterator; import java.util.StringTokenizer; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.*; import org.apache.hadoop.mapred.FileBasedUpdater; import org.apache.hadoop.mapred.IFile.PriorityQueueWriter; import org.apache.hadoop.mapred.IFile.Writer; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.PrIterBase; import org.apache.hadoop.mapred.Reporter; public class SSSPFileUpdater extends PrIterBase implements FileBasedUpdater<IntWritable, FloatWritable, FloatWritable, LinkArrayWritable> { private int workload = 0; private int iterate = 0; private int startnode; private int partitions; private JobConf job; private class Link{ int node; float weight; public Link(int n, float w){ node = n; weight = w; } } @Override public void configure(JobConf job) { this.job = job; this.startnode = job.getInt(MainDriver.START_NODE, 0); this.partitions = job.getInt("priter.graph.partitions", -1); } @Override public void iterate() { iterate++; System.out.println("iteration " + iterate + " total parsed " + workload); } @Override public FloatWritable resetiState() { return new FloatWritable(Float.MAX_VALUE); } @Override public long initFiles(Writer<IntWritable, FloatWritable> istateWriter, Writer<IntWritable, FloatWritable> cstateWriter, Writer<IntWritable, LinkArrayWritable> staticWriter, PriorityQueueWriter<IntWritable, FloatWritable, LinkArrayWritable> priorityqueueWriter) { String subGraphsDir = job.get(MainDriver.SUBGRAPH_DIR); int taskid = Util.getTaskId(job); Path subgraph = new Path(subGraphsDir + "/part" + taskid); long records = 0; FileSystem hdfs = null; float max = Float.MAX_VALUE; try { hdfs = FileSystem.get(job); FSDataInputStream in = hdfs.open(subgraph); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); boolean hasStart = false; String line; while((line = reader.readLine()) != null){ int index = line.indexOf("\t"); if(index != -1){ int node = Integer.parseInt(line.substring(0, index)); String linkstring = line.substring(index+1); ArrayList<Link> links = new ArrayList<Link>(); StringTokenizer st = new StringTokenizer(linkstring); while(st.hasMoreTokens()){ String link = st.nextToken(); String item[] = link.split(","); Link l = new Link(Integer.parseInt(item[0]), Float.parseFloat(item[1])); links.add(l); } LinkWritable[] links2 = new LinkWritable[links.size()]; for(int i=0; i<links.size(); i++){ links2[i] = new LinkWritable(links.get(i).node, links.get(i).weight); } LinkArrayWritable links3 = new LinkArrayWritable(); links3.set(links2); if(node == startnode){ istateWriter.append(new IntWritable(node), new FloatWritable(0)); cstateWriter.append(new IntWritable(node), new FloatWritable(0)); staticWriter.append(new IntWritable(node), links3); priorityqueueWriter.append(new IntWritable(node), new FloatWritable(0), links3); hasStart = true; }else{ istateWriter.append(new IntWritable(node), new FloatWritable(max)); cstateWriter.append(new IntWritable(node), new FloatWritable(max)); staticWriter.append(new IntWritable(node), links3); } records++; } } //to avoid no priority queue exception if(!hasStart){ LinkWritable[] links2 = new LinkWritable[partitions]; for(int i=0; i<partitions; i++){ //no use, map will skip it links2[i] = new LinkWritable(i, 1000); } LinkArrayWritable links3 = new LinkArrayWritable(); links3.set(links2); priorityqueueWriter.append(new IntWritable(-1), new FloatWritable(0), links3); } System.out.println(istateWriter.getRawLength()); System.out.println(cstateWriter.getRawLength()); System.out.println(staticWriter.getRawLength()); System.out.println(priorityqueueWriter.getRawLength()); reader.close(); } catch (IOException e) { e.printStackTrace(); } return records; } @Override public FloatWritable decidePriority(IntWritable key, FloatWritable iState) { return new FloatWritable(-iState.get()); } @Override public FloatWritable decideTopK(IntWritable key, FloatWritable cState) { return new FloatWritable(-cState.get()); } @Override public FloatWritable updatecState(FloatWritable iState, FloatWritable cState) { float shorter = Math.min(iState.get(), cState.get()); return new FloatWritable(shorter); } @Override public void updateiState(IntWritable key, Iterator<FloatWritable> values, OutputCollector<IntWritable, FloatWritable> output, Reporter reporter) throws IOException { workload++; reporter.setStatus(String.valueOf(workload)); float distance = Float.MAX_VALUE; while(values.hasNext()){ float v = values.next().get(); if(v < distance){ distance = v; } } output.collect(key, new FloatWritable(distance)); } }
{ "content_hash": "4efc2b46c9d2116b9edf2d15b4e84763", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 167, "avg_line_length": 31.089385474860336, "alnum_prop": 0.6799640610961366, "repo_name": "IMCG/priter", "id": "e1d257dad944fb9a6cba346f97030ce58defffd2", "size": "5565", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/examples/org/apache/hadoop/examples/priorityiteration/SSSPFileUpdater.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "631" }, { "name": "C", "bytes": "219670" }, { "name": "C++", "bytes": "629711" }, { "name": "CSS", "bytes": "11037" }, { "name": "GAP", "bytes": "19872" }, { "name": "HTML", "bytes": "130999" }, { "name": "Java", "bytes": "12317199" }, { "name": "JavaScript", "bytes": "3827" }, { "name": "Makefile", "bytes": "9457" }, { "name": "Objective-C", "bytes": "118273" }, { "name": "PHP", "bytes": "503428" }, { "name": "Perl", "bytes": "151118" }, { "name": "Python", "bytes": "897369" }, { "name": "Ruby", "bytes": "28485" }, { "name": "Shell", "bytes": "1151725" }, { "name": "Smalltalk", "bytes": "56562" }, { "name": "TeX", "bytes": "30124" }, { "name": "Thrift", "bytes": "21448" }, { "name": "XSLT", "bytes": "7925" } ], "symlink_target": "" }
This site uses [Jekyll Uptrend](http://jekyll-uptrend.org/).
{ "content_hash": "f4cb08e421b131b4fac77adc4aafacb5", "timestamp": "", "source": "github", "line_count": 1, "max_line_length": 60, "avg_line_length": 61, "alnum_prop": 0.7377049180327869, "repo_name": "baus/jekyll-uptrend", "id": "e5f05c075b865d7608fd4c9490f3c04bf9213785", "size": "61", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_includes/about.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "51130" } ], "symlink_target": "" }
package com.timgroup.karg.reference; public interface Lens<O, T> extends Getter<O, T>, Setter<O, T> { }
{ "content_hash": "40ab4787534e691ad983cdd5a8d19e75", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 66, "avg_line_length": 35, "alnum_prop": 0.7142857142857143, "repo_name": "tim-group/karg", "id": "12a0f378d78d44cf8f2c7954b211b618f089bfa1", "size": "105", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/timgroup/karg/reference/Lens.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "171225" } ], "symlink_target": "" }
@interface MDImageZoomAnimationController : NSObject <UIViewControllerAnimatedTransitioning> // The image view that will be used as the source (zoom in) or destination // (zoom out) of the transition. @property (nonatomic, weak, readonly) UIImageView *referenceImageView; @property (nonatomic, assign) BOOL hideReferenceImageViewWhenZoomIn; // Default is YES. // Initializes the receiver with the specified reference image view to other image view. - (instancetype)initWithReferenceImageView:(UIImageView *)referenceImageView; @end // Support MPresentionAnimatedTransitioning @protocol MDImageZoomViewControllerDelegate <NSObject> @property (nonatomic, weak, readonly) UIImageView *imageView; @end @protocol MDImageContainerViewControllerDelegate <MDImageZoomViewControllerDelegate> @property (nonatomic, weak, readonly) UIView *backgroundView; @property (nonatomic, weak, readonly) UIScrollView *scrollView; @end @interface MDImageZoomAnimationController (MPresentionAnimatedTransitioning)<MPresentionAnimatedTransitioning> + (id<MPresentionAnimatedTransitioning>)animationForPresentOperation:(MDPresentionAnimatedOperation)presentionAnimatedOperation fromViewController:(UIViewController<MDImageZoomViewControllerDelegate> *)fromViewController toViewController:(UIViewController<MDImageZoomViewControllerDelegate> *)toViewController; - (instancetype)initWithPresentionAnimatedOperation:(MDPresentionAnimatedOperation)presentionAnimatedOperation fromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController; @end
{ "content_hash": "5631fdeb1befaef698a55ab6a84d453e", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 310, "avg_line_length": 46.44117647058823, "alnum_prop": 0.8537048765041165, "repo_name": "Modool/MDTransitioning", "id": "74e3313732f868203ea6d670a7a3dd2645c5a98d", "size": "2782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ImagePreview/MDImageZoomAnimationController.h", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "114710" } ], "symlink_target": "" }
using namespace llvm; #define DEBUG_TYPE "si-optimize-exec-masking" namespace { class SIOptimizeExecMasking : public MachineFunctionPass { public: static char ID; public: SIOptimizeExecMasking() : MachineFunctionPass(ID) { initializeSIOptimizeExecMaskingPass(*PassRegistry::getPassRegistry()); } bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI optimize exec mask operations"; } void getAnalysisUsage(AnalysisUsage &AU) const override { AU.setPreservesCFG(); MachineFunctionPass::getAnalysisUsage(AU); } }; } // End anonymous namespace. INITIALIZE_PASS_BEGIN(SIOptimizeExecMasking, DEBUG_TYPE, "SI optimize exec mask operations", false, false) INITIALIZE_PASS_DEPENDENCY(LiveIntervals) INITIALIZE_PASS_END(SIOptimizeExecMasking, DEBUG_TYPE, "SI optimize exec mask operations", false, false) char SIOptimizeExecMasking::ID = 0; char &llvm::SIOptimizeExecMaskingID = SIOptimizeExecMasking::ID; /// If \p MI is a copy from exec, return the register copied to. static unsigned isCopyFromExec(const MachineInstr &MI, const GCNSubtarget &ST) { switch (MI.getOpcode()) { case AMDGPU::COPY: case AMDGPU::S_MOV_B64: case AMDGPU::S_MOV_B64_term: case AMDGPU::S_MOV_B32: case AMDGPU::S_MOV_B32_term: { const MachineOperand &Src = MI.getOperand(1); if (Src.isReg() && Src.getReg() == (ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC)) return MI.getOperand(0).getReg(); } } return AMDGPU::NoRegister; } /// If \p MI is a copy to exec, return the register copied from. static unsigned isCopyToExec(const MachineInstr &MI, const GCNSubtarget &ST) { switch (MI.getOpcode()) { case AMDGPU::COPY: case AMDGPU::S_MOV_B64: case AMDGPU::S_MOV_B32: { const MachineOperand &Dst = MI.getOperand(0); if (Dst.isReg() && Dst.getReg() == (ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC) && MI.getOperand(1).isReg()) return MI.getOperand(1).getReg(); break; } case AMDGPU::S_MOV_B64_term: case AMDGPU::S_MOV_B32_term: llvm_unreachable("should have been replaced"); } return AMDGPU::NoRegister; } /// If \p MI is a logical operation on an exec value, /// return the register copied to. static unsigned isLogicalOpOnExec(const MachineInstr &MI) { switch (MI.getOpcode()) { case AMDGPU::S_AND_B64: case AMDGPU::S_OR_B64: case AMDGPU::S_XOR_B64: case AMDGPU::S_ANDN2_B64: case AMDGPU::S_ORN2_B64: case AMDGPU::S_NAND_B64: case AMDGPU::S_NOR_B64: case AMDGPU::S_XNOR_B64: { const MachineOperand &Src1 = MI.getOperand(1); if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC) return MI.getOperand(0).getReg(); const MachineOperand &Src2 = MI.getOperand(2); if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC) return MI.getOperand(0).getReg(); break; } case AMDGPU::S_AND_B32: case AMDGPU::S_OR_B32: case AMDGPU::S_XOR_B32: case AMDGPU::S_ANDN2_B32: case AMDGPU::S_ORN2_B32: case AMDGPU::S_NAND_B32: case AMDGPU::S_NOR_B32: case AMDGPU::S_XNOR_B32: { const MachineOperand &Src1 = MI.getOperand(1); if (Src1.isReg() && Src1.getReg() == AMDGPU::EXEC_LO) return MI.getOperand(0).getReg(); const MachineOperand &Src2 = MI.getOperand(2); if (Src2.isReg() && Src2.getReg() == AMDGPU::EXEC_LO) return MI.getOperand(0).getReg(); break; } } return AMDGPU::NoRegister; } static unsigned getSaveExecOp(unsigned Opc) { switch (Opc) { case AMDGPU::S_AND_B64: return AMDGPU::S_AND_SAVEEXEC_B64; case AMDGPU::S_OR_B64: return AMDGPU::S_OR_SAVEEXEC_B64; case AMDGPU::S_XOR_B64: return AMDGPU::S_XOR_SAVEEXEC_B64; case AMDGPU::S_ANDN2_B64: return AMDGPU::S_ANDN2_SAVEEXEC_B64; case AMDGPU::S_ORN2_B64: return AMDGPU::S_ORN2_SAVEEXEC_B64; case AMDGPU::S_NAND_B64: return AMDGPU::S_NAND_SAVEEXEC_B64; case AMDGPU::S_NOR_B64: return AMDGPU::S_NOR_SAVEEXEC_B64; case AMDGPU::S_XNOR_B64: return AMDGPU::S_XNOR_SAVEEXEC_B64; case AMDGPU::S_AND_B32: return AMDGPU::S_AND_SAVEEXEC_B32; case AMDGPU::S_OR_B32: return AMDGPU::S_OR_SAVEEXEC_B32; case AMDGPU::S_XOR_B32: return AMDGPU::S_XOR_SAVEEXEC_B32; case AMDGPU::S_ANDN2_B32: return AMDGPU::S_ANDN2_SAVEEXEC_B32; case AMDGPU::S_ORN2_B32: return AMDGPU::S_ORN2_SAVEEXEC_B32; case AMDGPU::S_NAND_B32: return AMDGPU::S_NAND_SAVEEXEC_B32; case AMDGPU::S_NOR_B32: return AMDGPU::S_NOR_SAVEEXEC_B32; case AMDGPU::S_XNOR_B32: return AMDGPU::S_XNOR_SAVEEXEC_B32; default: return AMDGPU::INSTRUCTION_LIST_END; } } // These are only terminators to get correct spill code placement during // register allocation, so turn them back into normal instructions. Only one of // these is expected per block. static bool removeTerminatorBit(const SIInstrInfo &TII, MachineInstr &MI) { switch (MI.getOpcode()) { case AMDGPU::S_MOV_B64_term: case AMDGPU::S_MOV_B32_term: { MI.setDesc(TII.get(AMDGPU::COPY)); return true; } case AMDGPU::S_XOR_B64_term: { // This is only a terminator to get the correct spill code placement during // register allocation. MI.setDesc(TII.get(AMDGPU::S_XOR_B64)); return true; } case AMDGPU::S_XOR_B32_term: { // This is only a terminator to get the correct spill code placement during // register allocation. MI.setDesc(TII.get(AMDGPU::S_XOR_B32)); return true; } case AMDGPU::S_OR_B32_term: { // This is only a terminator to get the correct spill code placement during // register allocation. MI.setDesc(TII.get(AMDGPU::S_OR_B32)); return true; } case AMDGPU::S_ANDN2_B64_term: { // This is only a terminator to get the correct spill code placement during // register allocation. MI.setDesc(TII.get(AMDGPU::S_ANDN2_B64)); return true; } case AMDGPU::S_ANDN2_B32_term: { // This is only a terminator to get the correct spill code placement during // register allocation. MI.setDesc(TII.get(AMDGPU::S_ANDN2_B32)); return true; } default: return false; } } static MachineBasicBlock::reverse_iterator fixTerminators( const SIInstrInfo &TII, MachineBasicBlock &MBB) { MachineBasicBlock::reverse_iterator I = MBB.rbegin(), E = MBB.rend(); for (; I != E; ++I) { if (!I->isTerminator()) return I; if (removeTerminatorBit(TII, *I)) return I; } return E; } static MachineBasicBlock::reverse_iterator findExecCopy( const SIInstrInfo &TII, const GCNSubtarget &ST, MachineBasicBlock &MBB, MachineBasicBlock::reverse_iterator I, unsigned CopyToExec) { const unsigned InstLimit = 25; auto E = MBB.rend(); for (unsigned N = 0; N <= InstLimit && I != E; ++I, ++N) { unsigned CopyFromExec = isCopyFromExec(*I, ST); if (CopyFromExec != AMDGPU::NoRegister) return I; } return E; } // XXX - Seems LivePhysRegs doesn't work correctly since it will incorrectly // report the register as unavailable because a super-register with a lane mask // is unavailable. static bool isLiveOut(const MachineBasicBlock &MBB, unsigned Reg) { for (MachineBasicBlock *Succ : MBB.successors()) { if (Succ->isLiveIn(Reg)) return true; } return false; } bool SIOptimizeExecMasking::runOnMachineFunction(MachineFunction &MF) { if (skipFunction(MF.getFunction())) return false; const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); const SIRegisterInfo *TRI = ST.getRegisterInfo(); const SIInstrInfo *TII = ST.getInstrInfo(); unsigned Exec = ST.isWave32() ? AMDGPU::EXEC_LO : AMDGPU::EXEC; // Optimize sequences emitted for control flow lowering. They are originally // emitted as the separate operations because spill code may need to be // inserted for the saved copy of exec. // // x = copy exec // z = s_<op>_b64 x, y // exec = copy z // => // x = s_<op>_saveexec_b64 y // for (MachineBasicBlock &MBB : MF) { MachineBasicBlock::reverse_iterator I = fixTerminators(*TII, MBB); MachineBasicBlock::reverse_iterator E = MBB.rend(); if (I == E) continue; unsigned CopyToExec = isCopyToExec(*I, ST); if (CopyToExec == AMDGPU::NoRegister) continue; // Scan backwards to find the def. auto CopyToExecInst = &*I; auto CopyFromExecInst = findExecCopy(*TII, ST, MBB, I, CopyToExec); if (CopyFromExecInst == E) { auto PrepareExecInst = std::next(I); if (PrepareExecInst == E) continue; // Fold exec = COPY (S_AND_B64 reg, exec) -> exec = S_AND_B64 reg, exec if (CopyToExecInst->getOperand(1).isKill() && isLogicalOpOnExec(*PrepareExecInst) == CopyToExec) { LLVM_DEBUG(dbgs() << "Fold exec copy: " << *PrepareExecInst); PrepareExecInst->getOperand(0).setReg(Exec); LLVM_DEBUG(dbgs() << "into: " << *PrepareExecInst << '\n'); CopyToExecInst->eraseFromParent(); } continue; } if (isLiveOut(MBB, CopyToExec)) { // The copied register is live out and has a second use in another block. LLVM_DEBUG(dbgs() << "Exec copy source register is live out\n"); continue; } Register CopyFromExec = CopyFromExecInst->getOperand(0).getReg(); MachineInstr *SaveExecInst = nullptr; SmallVector<MachineInstr *, 4> OtherUseInsts; for (MachineBasicBlock::iterator J = std::next(CopyFromExecInst->getIterator()), JE = I->getIterator(); J != JE; ++J) { if (SaveExecInst && J->readsRegister(Exec, TRI)) { LLVM_DEBUG(dbgs() << "exec read prevents saveexec: " << *J << '\n'); // Make sure this is inserted after any VALU ops that may have been // scheduled in between. SaveExecInst = nullptr; break; } bool ReadsCopyFromExec = J->readsRegister(CopyFromExec, TRI); if (J->modifiesRegister(CopyToExec, TRI)) { if (SaveExecInst) { LLVM_DEBUG(dbgs() << "Multiple instructions modify " << printReg(CopyToExec, TRI) << '\n'); SaveExecInst = nullptr; break; } unsigned SaveExecOp = getSaveExecOp(J->getOpcode()); if (SaveExecOp == AMDGPU::INSTRUCTION_LIST_END) break; if (ReadsCopyFromExec) { SaveExecInst = &*J; LLVM_DEBUG(dbgs() << "Found save exec op: " << *SaveExecInst << '\n'); continue; } else { LLVM_DEBUG(dbgs() << "Instruction does not read exec copy: " << *J << '\n'); break; } } else if (ReadsCopyFromExec && !SaveExecInst) { // Make sure no other instruction is trying to use this copy, before it // will be rewritten by the saveexec, i.e. hasOneUse. There may have // been another use, such as an inserted spill. For example: // // %sgpr0_sgpr1 = COPY %exec // spill %sgpr0_sgpr1 // %sgpr2_sgpr3 = S_AND_B64 %sgpr0_sgpr1 // LLVM_DEBUG(dbgs() << "Found second use of save inst candidate: " << *J << '\n'); break; } if (SaveExecInst && J->readsRegister(CopyToExec, TRI)) { assert(SaveExecInst != &*J); OtherUseInsts.push_back(&*J); } } if (!SaveExecInst) continue; LLVM_DEBUG(dbgs() << "Insert save exec op: " << *SaveExecInst << '\n'); MachineOperand &Src0 = SaveExecInst->getOperand(1); MachineOperand &Src1 = SaveExecInst->getOperand(2); MachineOperand *OtherOp = nullptr; if (Src0.isReg() && Src0.getReg() == CopyFromExec) { OtherOp = &Src1; } else if (Src1.isReg() && Src1.getReg() == CopyFromExec) { if (!SaveExecInst->isCommutable()) break; OtherOp = &Src0; } else llvm_unreachable("unexpected"); CopyFromExecInst->eraseFromParent(); auto InsPt = SaveExecInst->getIterator(); const DebugLoc &DL = SaveExecInst->getDebugLoc(); BuildMI(MBB, InsPt, DL, TII->get(getSaveExecOp(SaveExecInst->getOpcode())), CopyFromExec) .addReg(OtherOp->getReg()); SaveExecInst->eraseFromParent(); CopyToExecInst->eraseFromParent(); for (MachineInstr *OtherInst : OtherUseInsts) { OtherInst->substituteRegister(CopyToExec, Exec, AMDGPU::NoSubRegister, *TRI); } } return true; }
{ "content_hash": "afd875b7e998c23d4464e52f17c4de21", "timestamp": "", "source": "github", "line_count": 405, "max_line_length": 80, "avg_line_length": 30.674074074074074, "alnum_prop": 0.6427593978910087, "repo_name": "llvm-mirror/llvm", "id": "cc9b46a755823b7be8d838893fff472bc879873f", "size": "13114", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/Target/AMDGPU/SIOptimizeExecMasking.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "53797008" }, { "name": "Batchfile", "bytes": "9834" }, { "name": "C", "bytes": "852170" }, { "name": "C++", "bytes": "86305007" }, { "name": "CMake", "bytes": "536242" }, { "name": "CSS", "bytes": "12605" }, { "name": "Dockerfile", "bytes": "5884" }, { "name": "Emacs Lisp", "bytes": "10556" }, { "name": "Go", "bytes": "149205" }, { "name": "HTML", "bytes": "37873" }, { "name": "LLVM", "bytes": "139035668" }, { "name": "Logos", "bytes": "28" }, { "name": "OCaml", "bytes": "306665" }, { "name": "Objective-C", "bytes": "10226" }, { "name": "PHP", "bytes": "2667" }, { "name": "Perl", "bytes": "25574" }, { "name": "Python", "bytes": "1014377" }, { "name": "Roff", "bytes": "39" }, { "name": "Shell", "bytes": "97425" }, { "name": "Swift", "bytes": "271" }, { "name": "Vim script", "bytes": "17497" } ], "symlink_target": "" }
function val = normProduct(Ms, xs, g) val = innerprodProduct(Ms, xs, g, g); val = sqrt(val); end
{ "content_hash": "dd823ebb6b8108d89d1c50df503f2876", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 41, "avg_line_length": 26, "alnum_prop": 0.625, "repo_name": "losangle/bfgsManopt", "id": "5572db57fe9bc6e3c994646cd358acd319ccc899", "size": "104", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "constrained/interior_with_ineq/normProduct.m", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "M", "bytes": "1136" }, { "name": "Matlab", "bytes": "413524" } ], "symlink_target": "" }
require "docker/api/entity" module Docker module Api class Service < Entity def inspect_service client.service_inspect(id, self) end def remove client.service_remove(id) end def update(config, params = {}) client.service_update(id, config, params) end end end end
{ "content_hash": "8dd7dfad5fdf71051fd1b21a9c3b5282", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 49, "avg_line_length": 17.789473684210527, "alnum_prop": 0.6094674556213018, "repo_name": "Vince300/docker-swarm-compose", "id": "09409a78a8f71e223a1cffe39b95fe49db0449c7", "size": "338", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/docker/api/service.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "67054" }, { "name": "Shell", "bytes": "131" } ], "symlink_target": "" }
package armeventhub import ( "encoding/json" "fmt" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "reflect" ) // MarshalJSON implements the json.Marshaller interface for type ApplicationGroupProperties. func (a ApplicationGroupProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "clientAppGroupIdentifier", a.ClientAppGroupIdentifier) populate(objectMap, "isEnabled", a.IsEnabled) populate(objectMap, "policies", a.Policies) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type ApplicationGroupProperties. func (a *ApplicationGroupProperties) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", a, err) } for key, val := range rawMsg { var err error switch key { case "clientAppGroupIdentifier": err = unpopulate(val, "ClientAppGroupIdentifier", &a.ClientAppGroupIdentifier) delete(rawMsg, key) case "isEnabled": err = unpopulate(val, "IsEnabled", &a.IsEnabled) delete(rawMsg, key) case "policies": a.Policies, err = unmarshalApplicationGroupPolicyClassificationArray(val) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", a, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type AuthorizationRuleProperties. func (a AuthorizationRuleProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "rights", a.Rights) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type Cluster. func (c Cluster) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "id", c.ID) populate(objectMap, "location", c.Location) populate(objectMap, "name", c.Name) populate(objectMap, "properties", c.Properties) populate(objectMap, "sku", c.SKU) populate(objectMap, "systemData", c.SystemData) populate(objectMap, "tags", c.Tags) populate(objectMap, "type", c.Type) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type ClusterQuotaConfigurationProperties. func (c ClusterQuotaConfigurationProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "settings", c.Settings) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type ConsumerGroupProperties. func (c ConsumerGroupProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populateTimeRFC3339(objectMap, "createdAt", c.CreatedAt) populateTimeRFC3339(objectMap, "updatedAt", c.UpdatedAt) populate(objectMap, "userMetadata", c.UserMetadata) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type ConsumerGroupProperties. func (c *ConsumerGroupProperties) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", c, err) } for key, val := range rawMsg { var err error switch key { case "createdAt": err = unpopulateTimeRFC3339(val, "CreatedAt", &c.CreatedAt) delete(rawMsg, key) case "updatedAt": err = unpopulateTimeRFC3339(val, "UpdatedAt", &c.UpdatedAt) delete(rawMsg, key) case "userMetadata": err = unpopulate(val, "UserMetadata", &c.UserMetadata) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", c, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type EHNamespace. func (e EHNamespace) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "id", e.ID) populate(objectMap, "identity", e.Identity) populate(objectMap, "location", e.Location) populate(objectMap, "name", e.Name) populate(objectMap, "properties", e.Properties) populate(objectMap, "sku", e.SKU) populate(objectMap, "systemData", e.SystemData) populate(objectMap, "tags", e.Tags) populate(objectMap, "type", e.Type) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type EHNamespaceProperties. func (e EHNamespaceProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "alternateName", e.AlternateName) populate(objectMap, "clusterArmId", e.ClusterArmID) populateTimeRFC3339(objectMap, "createdAt", e.CreatedAt) populate(objectMap, "disableLocalAuth", e.DisableLocalAuth) populate(objectMap, "encryption", e.Encryption) populate(objectMap, "isAutoInflateEnabled", e.IsAutoInflateEnabled) populate(objectMap, "kafkaEnabled", e.KafkaEnabled) populate(objectMap, "maximumThroughputUnits", e.MaximumThroughputUnits) populate(objectMap, "metricId", e.MetricID) populate(objectMap, "minimumTlsVersion", e.MinimumTLSVersion) populate(objectMap, "privateEndpointConnections", e.PrivateEndpointConnections) populate(objectMap, "provisioningState", e.ProvisioningState) populate(objectMap, "publicNetworkAccess", e.PublicNetworkAccess) populate(objectMap, "serviceBusEndpoint", e.ServiceBusEndpoint) populate(objectMap, "status", e.Status) populateTimeRFC3339(objectMap, "updatedAt", e.UpdatedAt) populate(objectMap, "zoneRedundant", e.ZoneRedundant) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type EHNamespaceProperties. func (e *EHNamespaceProperties) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", e, err) } for key, val := range rawMsg { var err error switch key { case "alternateName": err = unpopulate(val, "AlternateName", &e.AlternateName) delete(rawMsg, key) case "clusterArmId": err = unpopulate(val, "ClusterArmID", &e.ClusterArmID) delete(rawMsg, key) case "createdAt": err = unpopulateTimeRFC3339(val, "CreatedAt", &e.CreatedAt) delete(rawMsg, key) case "disableLocalAuth": err = unpopulate(val, "DisableLocalAuth", &e.DisableLocalAuth) delete(rawMsg, key) case "encryption": err = unpopulate(val, "Encryption", &e.Encryption) delete(rawMsg, key) case "isAutoInflateEnabled": err = unpopulate(val, "IsAutoInflateEnabled", &e.IsAutoInflateEnabled) delete(rawMsg, key) case "kafkaEnabled": err = unpopulate(val, "KafkaEnabled", &e.KafkaEnabled) delete(rawMsg, key) case "maximumThroughputUnits": err = unpopulate(val, "MaximumThroughputUnits", &e.MaximumThroughputUnits) delete(rawMsg, key) case "metricId": err = unpopulate(val, "MetricID", &e.MetricID) delete(rawMsg, key) case "minimumTlsVersion": err = unpopulate(val, "MinimumTLSVersion", &e.MinimumTLSVersion) delete(rawMsg, key) case "privateEndpointConnections": err = unpopulate(val, "PrivateEndpointConnections", &e.PrivateEndpointConnections) delete(rawMsg, key) case "provisioningState": err = unpopulate(val, "ProvisioningState", &e.ProvisioningState) delete(rawMsg, key) case "publicNetworkAccess": err = unpopulate(val, "PublicNetworkAccess", &e.PublicNetworkAccess) delete(rawMsg, key) case "serviceBusEndpoint": err = unpopulate(val, "ServiceBusEndpoint", &e.ServiceBusEndpoint) delete(rawMsg, key) case "status": err = unpopulate(val, "Status", &e.Status) delete(rawMsg, key) case "updatedAt": err = unpopulateTimeRFC3339(val, "UpdatedAt", &e.UpdatedAt) delete(rawMsg, key) case "zoneRedundant": err = unpopulate(val, "ZoneRedundant", &e.ZoneRedundant) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", e, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type Encryption. func (e Encryption) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "keySource", e.KeySource) populate(objectMap, "keyVaultProperties", e.KeyVaultProperties) populate(objectMap, "requireInfrastructureEncryption", e.RequireInfrastructureEncryption) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type Identity. func (i Identity) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "principalId", i.PrincipalID) populate(objectMap, "tenantId", i.TenantID) populate(objectMap, "type", i.Type) populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type NetworkRuleSetProperties. func (n NetworkRuleSetProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "defaultAction", n.DefaultAction) populate(objectMap, "ipRules", n.IPRules) populate(objectMap, "publicNetworkAccess", n.PublicNetworkAccess) populate(objectMap, "trustedServiceAccessEnabled", n.TrustedServiceAccessEnabled) populate(objectMap, "virtualNetworkRules", n.VirtualNetworkRules) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfiguration. func (n NetworkSecurityPerimeterConfiguration) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "id", n.ID) populate(objectMap, "location", n.Location) populate(objectMap, "name", n.Name) populate(objectMap, "properties", n.Properties) populate(objectMap, "tags", n.Tags) populate(objectMap, "type", n.Type) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfigurationProperties. func (n NetworkSecurityPerimeterConfigurationProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "networkSecurityPerimeter", n.NetworkSecurityPerimeter) populate(objectMap, "profile", n.Profile) populate(objectMap, "provisioningIssues", n.ProvisioningIssues) populate(objectMap, "provisioningState", n.ProvisioningState) populate(objectMap, "resourceAssociation", n.ResourceAssociation) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type NetworkSecurityPerimeterConfigurationPropertiesProfile. func (n NetworkSecurityPerimeterConfigurationPropertiesProfile) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "accessRules", n.AccessRules) populate(objectMap, "accessRulesVersion", n.AccessRulesVersion) populate(objectMap, "name", n.Name) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type NspAccessRuleProperties. func (n NspAccessRuleProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "addressPrefixes", n.AddressPrefixes) populate(objectMap, "direction", n.Direction) populate(objectMap, "fullyQualifiedDomainNames", n.FullyQualifiedDomainNames) populate(objectMap, "networkSecurityPerimeters", n.NetworkSecurityPerimeters) populate(objectMap, "subscriptions", n.Subscriptions) return json.Marshal(objectMap) } // MarshalJSON implements the json.Marshaller interface for type Properties. func (p Properties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "captureDescription", p.CaptureDescription) populateTimeRFC3339(objectMap, "createdAt", p.CreatedAt) populate(objectMap, "messageRetentionInDays", p.MessageRetentionInDays) populate(objectMap, "partitionCount", p.PartitionCount) populate(objectMap, "partitionIds", p.PartitionIDs) populate(objectMap, "status", p.Status) populateTimeRFC3339(objectMap, "updatedAt", p.UpdatedAt) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type Properties. func (p *Properties) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", p, err) } for key, val := range rawMsg { var err error switch key { case "captureDescription": err = unpopulate(val, "CaptureDescription", &p.CaptureDescription) delete(rawMsg, key) case "createdAt": err = unpopulateTimeRFC3339(val, "CreatedAt", &p.CreatedAt) delete(rawMsg, key) case "messageRetentionInDays": err = unpopulate(val, "MessageRetentionInDays", &p.MessageRetentionInDays) delete(rawMsg, key) case "partitionCount": err = unpopulate(val, "PartitionCount", &p.PartitionCount) delete(rawMsg, key) case "partitionIds": err = unpopulate(val, "PartitionIDs", &p.PartitionIDs) delete(rawMsg, key) case "status": err = unpopulate(val, "Status", &p.Status) delete(rawMsg, key) case "updatedAt": err = unpopulateTimeRFC3339(val, "UpdatedAt", &p.UpdatedAt) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", p, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type SchemaGroupProperties. func (s SchemaGroupProperties) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populateTimeRFC3339(objectMap, "createdAtUtc", s.CreatedAtUTC) populate(objectMap, "eTag", s.ETag) populate(objectMap, "groupProperties", s.GroupProperties) populate(objectMap, "schemaCompatibility", s.SchemaCompatibility) populate(objectMap, "schemaType", s.SchemaType) populateTimeRFC3339(objectMap, "updatedAtUtc", s.UpdatedAtUTC) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type SchemaGroupProperties. func (s *SchemaGroupProperties) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", s, err) } for key, val := range rawMsg { var err error switch key { case "createdAtUtc": err = unpopulateTimeRFC3339(val, "CreatedAtUTC", &s.CreatedAtUTC) delete(rawMsg, key) case "eTag": err = unpopulate(val, "ETag", &s.ETag) delete(rawMsg, key) case "groupProperties": err = unpopulate(val, "GroupProperties", &s.GroupProperties) delete(rawMsg, key) case "schemaCompatibility": err = unpopulate(val, "SchemaCompatibility", &s.SchemaCompatibility) delete(rawMsg, key) case "schemaType": err = unpopulate(val, "SchemaType", &s.SchemaType) delete(rawMsg, key) case "updatedAtUtc": err = unpopulateTimeRFC3339(val, "UpdatedAtUTC", &s.UpdatedAtUTC) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", s, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type SystemData. func (s SystemData) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populateTimeRFC3339(objectMap, "createdAt", s.CreatedAt) populate(objectMap, "createdBy", s.CreatedBy) populate(objectMap, "createdByType", s.CreatedByType) populateTimeRFC3339(objectMap, "lastModifiedAt", s.LastModifiedAt) populate(objectMap, "lastModifiedBy", s.LastModifiedBy) populate(objectMap, "lastModifiedByType", s.LastModifiedByType) return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. func (s *SystemData) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", s, err) } for key, val := range rawMsg { var err error switch key { case "createdAt": err = unpopulateTimeRFC3339(val, "CreatedAt", &s.CreatedAt) delete(rawMsg, key) case "createdBy": err = unpopulate(val, "CreatedBy", &s.CreatedBy) delete(rawMsg, key) case "createdByType": err = unpopulate(val, "CreatedByType", &s.CreatedByType) delete(rawMsg, key) case "lastModifiedAt": err = unpopulateTimeRFC3339(val, "LastModifiedAt", &s.LastModifiedAt) delete(rawMsg, key) case "lastModifiedBy": err = unpopulate(val, "LastModifiedBy", &s.LastModifiedBy) delete(rawMsg, key) case "lastModifiedByType": err = unpopulate(val, "LastModifiedByType", &s.LastModifiedByType) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", s, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type ThrottlingPolicy. func (t ThrottlingPolicy) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "metricId", t.MetricID) populate(objectMap, "name", t.Name) populate(objectMap, "rateLimitThreshold", t.RateLimitThreshold) objectMap["type"] = ApplicationGroupPolicyTypeThrottlingPolicy return json.Marshal(objectMap) } // UnmarshalJSON implements the json.Unmarshaller interface for type ThrottlingPolicy. func (t *ThrottlingPolicy) UnmarshalJSON(data []byte) error { var rawMsg map[string]json.RawMessage if err := json.Unmarshal(data, &rawMsg); err != nil { return fmt.Errorf("unmarshalling type %T: %v", t, err) } for key, val := range rawMsg { var err error switch key { case "metricId": err = unpopulate(val, "MetricID", &t.MetricID) delete(rawMsg, key) case "name": err = unpopulate(val, "Name", &t.Name) delete(rawMsg, key) case "rateLimitThreshold": err = unpopulate(val, "RateLimitThreshold", &t.RateLimitThreshold) delete(rawMsg, key) case "type": err = unpopulate(val, "Type", &t.Type) delete(rawMsg, key) } if err != nil { return fmt.Errorf("unmarshalling type %T: %v", t, err) } } return nil } // MarshalJSON implements the json.Marshaller interface for type TrackedResource. func (t TrackedResource) MarshalJSON() ([]byte, error) { objectMap := make(map[string]interface{}) populate(objectMap, "id", t.ID) populate(objectMap, "location", t.Location) populate(objectMap, "name", t.Name) populate(objectMap, "tags", t.Tags) populate(objectMap, "type", t.Type) return json.Marshal(objectMap) } func populate(m map[string]interface{}, k string, v interface{}) { if v == nil { return } else if azcore.IsNullValue(v) { m[k] = nil } else if !reflect.ValueOf(v).IsNil() { m[k] = v } } func unpopulate(data json.RawMessage, fn string, v interface{}) error { if data == nil { return nil } if err := json.Unmarshal(data, v); err != nil { return fmt.Errorf("struct field %s: %v", fn, err) } return nil }
{ "content_hash": "f369a6f6c97af3125d63e43b8b4a8ee8", "timestamp": "", "source": "github", "line_count": 500, "max_line_length": 120, "avg_line_length": 37.3, "alnum_prop": 0.7440214477211796, "repo_name": "Azure/azure-sdk-for-go", "id": "ef09a0cf86534446f3a605c23255ab74d33e9a14", "size": "18989", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sdk/resourcemanager/eventhub/armeventhub/zz_generated_models_serde.go", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "1629" }, { "name": "Bicep", "bytes": "8394" }, { "name": "CSS", "bytes": "6089" }, { "name": "Dockerfile", "bytes": "1435" }, { "name": "Go", "bytes": "5463500" }, { "name": "HTML", "bytes": "8933" }, { "name": "JavaScript", "bytes": "8137" }, { "name": "PowerShell", "bytes": "504494" }, { "name": "Shell", "bytes": "3893" }, { "name": "Smarty", "bytes": "1723" } ], "symlink_target": "" }
import os import subprocess import sys HERE = os.path.abspath(__file__) frag = os.path.splitext(sys.argv[1])[0] + ".frag" print(frag) cmd = os.path.join(os.path.dirname(HERE), "fake_compiler") + " " + frag p = subprocess.run( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, ) if p.returncode != 0: # Interesting: the compiler failed. exit(0) # Boring: the compiler succeeded. exit(1)
{ "content_hash": "9150dea9976710ae980a37f9816cbc23", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 71, "avg_line_length": 18.4, "alnum_prop": 0.6630434782608695, "repo_name": "google/graphicsfuzz", "id": "a5bab7c54a5eb38b3e73dce91347768a30eaa386", "size": "1078", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "graphicsfuzz/src/main/scripts/examples/glsl-reduce-walkthrough/weak_interestingness_test.py", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "21057" }, { "name": "Batchfile", "bytes": "18712" }, { "name": "C", "bytes": "1261" }, { "name": "C++", "bytes": "112737" }, { "name": "CMake", "bytes": "3664" }, { "name": "CSS", "bytes": "6774" }, { "name": "Dockerfile", "bytes": "4035" }, { "name": "GLSL", "bytes": "570713" }, { "name": "HTML", "bytes": "9966" }, { "name": "Java", "bytes": "3314649" }, { "name": "JavaScript", "bytes": "75538" }, { "name": "Python", "bytes": "709540" }, { "name": "Shell", "bytes": "62877" }, { "name": "Thrift", "bytes": "7878" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "5cdbcd5fd387c35562e2599752d8b990", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "8e72924cf4d85b7e1c4d3824d517bb60f3e335e4", "size": "177", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Asterales/Asteraceae/Olearia heleophila/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "232e8c3a57b946cebaf2dbd90ac6b89c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "367345ef907b56738fbd302a135fc505eb9f2cc5", "size": "178", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Celastrales/Celastraceae/Celastrus/Celastrus panamensis/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
from collections import OrderedDict from ..framework import Program __all__ = ['op_freq_statistic'] def op_freq_statistic(program): """ Statistics of Op frequency. Args: program(Program): The current Program. Returns: uni_op_freq(dict): the single op frequency. adj_2_op_freq(dict): the two adjacent ops frequency. Examples: >>> import paddle.fluid as fluid >>> uni_op_freq, adj_2_op_freq = fluid.contrib.op_freq_statistic( >>> fluid.default_main_program()) >>> for op_type, op_num in uni_op_freq: >>> print("%s \t %d" % (op_type, op_num)) >>> for op_type, op_num in adj_2_op_freq: >>> print("%s \t %d" % (op_type, op_num)) """ if not isinstance(program, Program): raise TypeError( "The input type should be Porgram." "But you passed in %s" % (type(program)) ) uni_op_freq = OrderedDict() adj_2_op_freq = OrderedDict() op_in_ops = OrderedDict() parameters = [p.name for p in program.blocks[0].all_parameters()] # get uni_op_freq for op in program.global_block().ops: had_recorded = False for var_name in op.output_arg_names: if var_name in parameters: continue if not had_recorded and uni_op_freq.has_key(op.type): uni_op_freq[op.type] += 1 had_recorded = True elif not had_recorded: uni_op_freq[op.type] = 1 had_recorded = True # get adj_2_op_freq var_gen_op = {} for op in program.global_block().ops: for var_name in op.input_arg_names: if var_name in parameters: continue if var_gen_op.has_key(var_name): assert len(var_gen_op[var_name]) > 0 if op_in_ops.has_key(op.type): op_in_ops[op.type].append(var_gen_op[var_name][-1]) else: op_in_ops[op.type] = [var_gen_op[var_name][-1]] else: print( "Var's generate op is not found,%s, %s" % (var_name, op.type) ) for var_name in op.output_arg_names: if var_gen_op.has_key(var_name): var_gen_op[var_name].append(op.type) else: var_gen_op[var_name] = [op.type] for op, in_ops in op_in_ops.iteritems(): for in_op in in_ops: op_op = in_op + "->" + op if adj_2_op_freq.has_key(op_op): adj_2_op_freq[op_op] += 1 else: adj_2_op_freq[op_op] = 1 uni_op_freq = sorted( uni_op_freq.items(), key=lambda item: item[1], reverse=True ) adj_2_op_freq = sorted( adj_2_op_freq.items(), key=lambda item: item[1], reverse=True ) return uni_op_freq, adj_2_op_freq
{ "content_hash": "6429d295bd61f6a31ece751fbfc2c3ec", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 73, "avg_line_length": 30.96842105263158, "alnum_prop": 0.5129163834126444, "repo_name": "luotao1/Paddle", "id": "ee435ac657af3ed7421312073cef537cde6fd9f3", "size": "3554", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "python/paddle/fluid/contrib/op_frequence.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "58544" }, { "name": "C", "bytes": "210300" }, { "name": "C++", "bytes": "36771446" }, { "name": "CMake", "bytes": "903079" }, { "name": "Cuda", "bytes": "5200715" }, { "name": "Dockerfile", "bytes": "4361" }, { "name": "Go", "bytes": "49796" }, { "name": "Java", "bytes": "16630" }, { "name": "Jinja", "bytes": "23852" }, { "name": "MLIR", "bytes": "39982" }, { "name": "Python", "bytes": "36248258" }, { "name": "R", "bytes": "1332" }, { "name": "Shell", "bytes": "553175" } ], "symlink_target": "" }
@interface ZXRGBLuminanceSourceTestCase : XCTestCase @end
{ "content_hash": "b6b0e6baa998f36fd00692ff4c5de4bf", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 52, "avg_line_length": 12.2, "alnum_prop": 0.819672131147541, "repo_name": "TheLevelUp/ZXingObjC", "id": "fc30b9a081a35a76490445ce737ad7ac4c157218", "size": "658", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "ZXingObjCTests/ZXRGBLuminanceSourceTestCase.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "5874" }, { "name": "Objective-C", "bytes": "2282041" }, { "name": "Ruby", "bytes": "2450" } ], "symlink_target": "" }
<label [attr.for]="inputId" class="mc-checkbox-layout" #label> <div class="mc-checkbox-inner-container" [class.mc-checkbox-inner-container-no-side-margin]="!checkboxLabel.textContent || !checkboxLabel.textContent.trim()"> <input #input type="checkbox" class="mc-checkbox-input cdk-visually-hidden" [id]="inputId" [required]="required" [checked]="checked" [attr.value]="value" [disabled]="disabled" [attr.name]="name" [tabIndex]="tabIndex" [indeterminate]="indeterminate" [attr.aria-label]="ariaLabel || null" [attr.aria-labelledby]="ariaLabelledby" [attr.aria-checked]="getAriaChecked()" (change)="onInteractionEvent($event)" (click)="onInputClick($event)"> <div class="mc-checkbox-frame"> <i class="mc-checkbox-checkmark mc mc-check_16"></i> <i class="mc-checkbox-mixedmark mc mc-minus_16"></i> </div> </div> <span class="mc-checkbox-label" #checkboxLabel (cdkObserveContent)="onLabelTextChange()"> <ng-content></ng-content> </span> </label>
{ "content_hash": "91199333ffd426c6c15121d63ce0d801", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 126, "avg_line_length": 42.89655172413793, "alnum_prop": 0.5554662379421221, "repo_name": "positive-js/mosaic", "id": "11f5334dbcd97bff92313d71a39cd1e2005cd415", "size": "1244", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "packages/mosaic/checkbox/checkbox.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "67679" }, { "name": "Dockerfile", "bytes": "86" }, { "name": "HTML", "bytes": "517657" }, { "name": "Handlebars", "bytes": "1642" }, { "name": "JavaScript", "bytes": "18209" }, { "name": "Makefile", "bytes": "294" }, { "name": "SCSS", "bytes": "720598" }, { "name": "Shell", "bytes": "3928" }, { "name": "TypeScript", "bytes": "4308233" } ], "symlink_target": "" }
Rails.application.routes.draw do resources :delayed_jobs do end resources :genomes do resources :scaffolds do resources :features end resources :features end # You can have the root of your site routed with "root" root 'welcome#index' end
{ "content_hash": "e5fcdbf3b3a823a8f812f1d7cc9a0f77", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 57, "avg_line_length": 18.133333333333333, "alnum_prop": 0.7022058823529411, "repo_name": "audy/genome-explorer", "id": "c41719a89300f3d0aa74f2addff0e18d86ab1cf9", "size": "272", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/routes.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1763" }, { "name": "CoffeeScript", "bytes": "1055" }, { "name": "HTML", "bytes": "14476" }, { "name": "JavaScript", "bytes": "51" }, { "name": "Ruby", "bytes": "51927" }, { "name": "Shell", "bytes": "92" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="15dp" android:background="#8000"> <!--舒适度、洗车指数和运动建议布局--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:layout_marginLeft="15dp" android:text="生活建议" android:textColor="#fff" android:textSize="20sp" /> <TextView android:id="@+id/comfort_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dp" android:textColor="#fff"/> <TextView android:id="@+id/car_wash_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dp" android:textColor="#fff"/> <TextView android:id="@+id/sport_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="15dp" android:textColor="#fff"/> </LinearLayout>
{ "content_hash": "41860cf603fba04729dec1ac897edcd0", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 62, "avg_line_length": 30.75609756097561, "alnum_prop": 0.6352101506740682, "repo_name": "zhfdzh/coolweather", "id": "fe270360129bb6cbc844e6b73b2e95a513345840", "size": "1299", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/suggestion.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "32204" } ], "symlink_target": "" }
package org.apache.helix.filestore; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.helix.HelixDataAccessor; import org.apache.helix.HelixManager; import org.apache.helix.PropertyKey.Builder; import org.apache.helix.controller.HelixControllerMain; import org.apache.helix.model.HelixConfigScope; import org.apache.helix.model.HelixConfigScope.ConfigScopeProperty; import org.apache.helix.model.builder.HelixConfigScopeBuilder; import org.apache.helix.tools.ClusterSetup; import org.apache.helix.zookeeper.zkclient.IDefaultNameSpace; import org.apache.helix.zookeeper.zkclient.ZkClient; import org.apache.helix.zookeeper.zkclient.ZkServer; public class IntegrationTest { public static void main(String[] args) throws InterruptedException { ZkServer server = null; try { String baseDir = "/tmp/IntegrationTest/"; final String dataDir = baseDir + "zk/dataDir"; final String logDir = baseDir + "/tmp/logDir"; FileUtils.deleteDirectory(new File(dataDir)); FileUtils.deleteDirectory(new File(logDir)); IDefaultNameSpace defaultNameSpace = new IDefaultNameSpace() { @Override public void createDefaultNameSpace(ZkClient zkClient) { } }; int zkPort = 2199; final String zkAddress = "localhost:" + zkPort; server = new ZkServer(dataDir, logDir, defaultNameSpace, zkPort); server.start(); ClusterSetup setup = new ClusterSetup(zkAddress); final String clusterName = "file-store-test"; setup.deleteCluster(clusterName); setup.addCluster(clusterName, true); setup.addInstanceToCluster(clusterName, "localhost_12001"); setup.addInstanceToCluster(clusterName, "localhost_12002"); setup.addInstanceToCluster(clusterName, "localhost_12003"); setup.addResourceToCluster(clusterName, "repository", 1, "MasterSlave"); setup.rebalanceResource(clusterName, "repository", 3); // Set the configuration final String instanceName1 = "localhost_12001"; addConfiguration(setup, baseDir, clusterName, instanceName1); final String instanceName2 = "localhost_12002"; addConfiguration(setup, baseDir, clusterName, instanceName2); final String instanceName3 = "localhost_12003"; addConfiguration(setup, baseDir, clusterName, instanceName3); Thread thread1 = new Thread(new Runnable() { @Override public void run() { FileStore fileStore = null; try { fileStore = new FileStore(zkAddress, clusterName, instanceName1); fileStore.connect(); } catch (Exception e) { System.err.println("Exception" + e); fileStore.disconnect(); } } }); // START NODES Thread thread2 = new Thread(new Runnable() { @Override public void run() { FileStore fileStore = new FileStore(zkAddress, clusterName, instanceName2); fileStore.connect(); } }); // START NODES Thread thread3 = new Thread(new Runnable() { @Override public void run() { FileStore fileStore = new FileStore(zkAddress, clusterName, instanceName3); fileStore.connect(); } }); System.out.println("STARTING NODES"); thread1.start(); thread2.start(); thread3.start(); // Start Controller final HelixManager manager = HelixControllerMain.startHelixController(zkAddress, clusterName, "controller", HelixControllerMain.STANDALONE); Thread.sleep(5000); printStatus(manager); listFiles(baseDir); System.out.println("Writing files a.txt and b.txt to current master " + baseDir + "localhost_12001" + "/filestore"); FileUtils.writeStringToFile(new File(baseDir + "localhost_12001" + "/filestore/a.txt"), "some_data in a"); FileUtils.writeStringToFile(new File(baseDir + "localhost_12001" + "/filestore/b.txt"), "some_data in b"); Thread.sleep(10000); listFiles(baseDir); Thread.sleep(5000); System.out.println("Stopping the MASTER node:" + "localhost_12001"); thread1.interrupt(); Thread.sleep(10000); printStatus(manager); System.out.println("Writing files c.txt and d.txt to current master " + baseDir + "localhost_12002" + "/filestore"); FileUtils.writeStringToFile(new File(baseDir + "localhost_12002" + "/filestore/c.txt"), "some_data in c"); FileUtils.writeStringToFile(new File(baseDir + "localhost_12002" + "/filestore/d.txt"), "some_data in d"); Thread.sleep(10000); listFiles(baseDir); System.out.println("Create or modify any files under " + baseDir + "localhost_12002" + "/filestore" + " and it should get replicated to " + baseDir + "localhost_12003" + "/filestore"); } catch (Exception e) { e.printStackTrace(); } finally { if (server != null) { // server.shutdown(); } } Thread.currentThread().join(); } private static void listFiles(String baseDir) { System.out.println("===============FILES==============================="); String[] instances = new String[] { "localhost_12001", "localhost_12002", "localhost_12003" }; for (String instance : instances) { String dir = baseDir + instance + "/filestore"; String[] list = new File(dir).list(); System.out.println(dir + ":" + ((list != null) ? Arrays.toString(list) : "NONE")); } System.out.println("===============FILES==============================="); } private static void printStatus(final HelixManager manager) { System.out.println("CLUSTER STATUS"); HelixDataAccessor helixDataAccessor = manager.getHelixDataAccessor(); Builder keyBuilder = helixDataAccessor.keyBuilder(); System.out.println("External View \n" + helixDataAccessor.getProperty(keyBuilder.externalView("repository"))); } private static void addConfiguration(ClusterSetup setup, String baseDir, String clusterName, String instanceName) throws IOException { Map<String, String> properties = new HashMap<String, String>(); HelixConfigScopeBuilder builder = new HelixConfigScopeBuilder(ConfigScopeProperty.PARTICIPANT); HelixConfigScope instanceScope = builder.forCluster(clusterName).forParticipant(instanceName).build(); properties.put("change_log_dir", baseDir + instanceName + "/translog"); properties.put("file_store_dir", baseDir + instanceName + "/filestore"); properties.put("check_point_dir", baseDir + instanceName + "/checkpoint"); setup.getClusterManagementTool().setConfig(instanceScope, properties); FileUtils.deleteDirectory(new File(properties.get("change_log_dir"))); FileUtils.deleteDirectory(new File(properties.get("file_store_dir"))); FileUtils.deleteDirectory(new File(properties.get("check_point_dir"))); new File(properties.get("change_log_dir")).mkdirs(); new File(properties.get("file_store_dir")).mkdirs(); new File(properties.get("check_point_dir")).mkdirs(); } }
{ "content_hash": "628e4c844002e26ec014c3aa3e0c530c", "timestamp": "", "source": "github", "line_count": 181, "max_line_length": 99, "avg_line_length": 40.14364640883978, "alnum_prop": 0.6663914120561519, "repo_name": "lei-xia/helix", "id": "bafa163d5e6fe32f78350d65d6bc1b01d5f4f58e", "size": "8073", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "recipes/rsync-replicated-file-system/src/main/java/org/apache/helix/filestore/IntegrationTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Assembly", "bytes": "1275" }, { "name": "CSS", "bytes": "8751" }, { "name": "HTML", "bytes": "45086" }, { "name": "Java", "bytes": "6361970" }, { "name": "JavaScript", "bytes": "2052" }, { "name": "Pascal", "bytes": "1940" }, { "name": "Python", "bytes": "185190" }, { "name": "Shell", "bytes": "142958" }, { "name": "SourcePawn", "bytes": "1247" }, { "name": "TypeScript", "bytes": "158324" } ], "symlink_target": "" }
using DKEngine; using DKEngine.Core; using DKEngine.Core.Components; using DKEngine.Core.UI; namespace MarIO.Assets.Scripts { public class GUIUpdateScript : Script { private TextBlock Time; private TextBlock Coins; private TextBlock World; private TextBlock Lives; private TextBlock Score; public GUIUpdateScript(GameObject Parent) : base(Parent) { } protected override void OnColliderEnter(Collider e) { } protected override void Start() { this.World = GameObject.Find<TextBlock>("txt_World"); this.Time = GameObject.Find<TextBlock>("txt_Time"); this.Score = GameObject.Find<TextBlock>("txt_Score"); this.Coins = GameObject.Find<TextBlock>("txt_Coins"); this.Lives = GameObject.Find<TextBlock>("txt_Lives"); this.World.Text = Engine.SceneName; this.Time.Text = string.Format("{0:000}", Shared.Mechanics.TimeLeft.TotalSeconds); this.Score.Text = Shared.Mechanics.GameScoreStr; this.Coins.Text = string.Format("*{0:00}", Shared.Mechanics.CoinsCount); this.Lives.Text = string.Format("*{0:00}", Shared.Mechanics.Lives); } protected override void Update() { this.Time.Text = string.Format("{0:000}", Shared.Mechanics.TimeLeft.TotalSeconds); this.Score.Text = Shared.Mechanics.GameScoreStr; this.Coins.Text = string.Format("*{0:00}", Shared.Mechanics.CoinsCount); this.Lives.Text = string.Format("*{0:00}", Shared.Mechanics.Lives); } } }
{ "content_hash": "6d46ca7bec61c85f9b4080d51b5f4027", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 94, "avg_line_length": 36.44444444444444, "alnum_prop": 0.6207317073170732, "repo_name": "meowside/DKEngine", "id": "0e857a5b24f402d0efc0a07424219205d82f9d24", "size": "1642", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "MarIO/Assets/Scripts/GUIUpdateScript.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "269010" }, { "name": "PowerShell", "bytes": "231" } ], "symlink_target": "" }
class RemoveLikesFromImages < ActiveRecord::Migration def up remove_column :images, :likes end def down add_column :images, :likes, :integer end end
{ "content_hash": "59f296b1bd45bdf69667552dae2033ac", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 53, "avg_line_length": 18.444444444444443, "alnum_prop": 0.7108433734939759, "repo_name": "yangli85/pandora", "id": "6aee9fbe364271c5548c487017f444ea830b77a5", "size": "166", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/pandora/db/migrate/20160529110923_remove_likes_from_images.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "156417" }, { "name": "SQLPL", "bytes": "813" }, { "name": "Shell", "bytes": "520" } ], "symlink_target": "" }
package java.io; import com.jtransc.JTranscArrays; import java.util.Arrays; /** * Wraps an existing {@link InputStream} and adds functionality to "push back" * bytes that have been read, so that they can be read again. Parsers may find * this useful. The number of bytes which may be pushed back can be specified * during construction. If the buffer of pushed back bytes is empty, bytes are * read from the underlying input stream. */ public class PushbackInputStream extends FilterInputStream { /** * The buffer that contains pushed-back bytes. */ protected byte[] buf; /** * The current position within {@code buf}. A value equal to * {@code buf.length} indicates that no bytes are available. A value of 0 * indicates that the buffer is full. */ protected int pos; /** * Constructs a new {@code PushbackInputStream} with the specified input * stream as source. The size of the pushback buffer is set to the default * value of 1 byte. * * <p><strong>Warning:</strong> passing a null source creates an invalid * {@code PushbackInputStream}. All read operations on such a stream will * fail. * * @param in * the source input stream. */ public PushbackInputStream(InputStream in) { super(in); buf = (in == null) ? null : new byte[1]; pos = 1; } /** * Constructs a new {@code PushbackInputStream} with {@code in} as source * input stream. The size of the pushback buffer is set to {@code size}. * * <p><strong>Warning:</strong> passing a null source creates an invalid * {@code PushbackInputStream}. All read operations on such a stream will * fail. * * @param in * the source input stream. * @param size * the size of the pushback buffer. * @throws IllegalArgumentException * if {@code size} is negative. */ public PushbackInputStream(InputStream in, int size) { super(in); if (size <= 0) { throw new IllegalArgumentException("size <= 0"); } buf = (in == null) ? null : new byte[size]; pos = size; } @Override public int available() throws IOException { if (buf == null) { throw new IOException(); } return buf.length - pos + in.available(); } /** * Closes this stream. This implementation closes the source stream * and releases the pushback buffer. * * @throws IOException * if an error occurs while closing this stream. */ @Override public void close() throws IOException { if (in != null) { in.close(); in = null; buf = null; } } /** * Indicates whether this stream supports the {@code mark(int)} and * {@code reset()} methods. {@code PushbackInputStream} does not support * them, so it returns {@code false}. * * @return always {@code false}. * @see #mark(int) * @see #reset() */ @Override public boolean markSupported() { return false; } /** * Reads a single byte from this stream and returns it as an integer in the * range from 0 to 255. If the pushback buffer does not contain any * available bytes then a byte from the source input stream is returned. * Blocks until one byte has been read, the end of the source stream is * detected or an exception is thrown. * * @return the byte read or -1 if the end of the source stream has been * reached. * @throws IOException * if this stream is closed or an I/O error occurs while reading * from this stream. */ @Override public int read() throws IOException { if (buf == null) { throw new IOException(); } // Is there a pushback byte available? if (pos < buf.length) { return (buf[pos++] & 0xFF); } // Assume read() in the InputStream will return low-order byte or -1 // if end of stream. return in.read(); } /** * Reads up to {@code byteCount} bytes from this stream and stores them in * the byte array {@code buffer} starting at {@code byteOffset}. Bytes are read * from the pushback buffer first, then from the source stream if more bytes * are required. Blocks until {@code byteCount} bytes have been read, the end of * the source stream is detected or an exception is thrown. Returns the number of bytes read, * or -1 if the end of the source stream has been reached. * * @throws IndexOutOfBoundsException * if {@code byteOffset < 0 || byteCount < 0 || byteOffset + byteCount > buffer.length}. * @throws IOException * if this stream is closed or another I/O error occurs while * reading from this stream. * @throws NullPointerException * if {@code buffer == null}. */ @Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException { if (buf == null) { throw streamClosed(); } JTranscArrays.checkOffsetAndCount(buffer.length, byteOffset, byteCount); int copiedBytes = 0, copyLength = 0, newOffset = byteOffset; // Are there pushback bytes available? if (pos < buf.length) { copyLength = (buf.length - pos >= byteCount) ? byteCount : buf.length - pos; System.arraycopy(buf, pos, buffer, newOffset, copyLength); newOffset += copyLength; copiedBytes += copyLength; // Use up the bytes in the local buffer pos += copyLength; } // Have we copied enough? if (copyLength == byteCount) { return byteCount; } int inCopied = in.read(buffer, newOffset, byteCount - copiedBytes); if (inCopied > 0) { return inCopied + copiedBytes; } if (copiedBytes == 0) { return inCopied; } return copiedBytes; } private IOException streamClosed() throws IOException { throw new IOException("PushbackInputStream is closed"); } /** * Skips {@code byteCount} bytes in this stream. This implementation skips bytes * in the pushback buffer first and then in the source stream if necessary. * * @return the number of bytes actually skipped. * @throws IOException * if this stream is closed or another I/O error occurs. */ @Override public long skip(long byteCount) throws IOException { if (in == null) { throw streamClosed(); } if (byteCount <= 0) { return 0; } int numSkipped = 0; if (pos < buf.length) { numSkipped += (byteCount < buf.length - pos) ? byteCount : buf.length - pos; pos += numSkipped; } if (numSkipped < byteCount) { numSkipped += in.skip(byteCount - numSkipped); } return numSkipped; } /** * Pushes all the bytes in {@code buffer} back to this stream. The bytes are * pushed back in such a way that the next byte read from this stream is * buffer[0], then buffer[1] and so on. * <p> * If this stream's internal pushback buffer cannot store the entire * contents of {@code buffer}, an {@code IOException} is thrown. Parts of * {@code buffer} may have already been copied to the pushback buffer when * the exception is thrown. * * @param buffer * the buffer containing the bytes to push back to this stream. * @throws IOException * if the free space in the internal pushback buffer is not * sufficient to store the contents of {@code buffer}. */ public void unread(byte[] buffer) throws IOException { unread(buffer, 0, buffer.length); } /** * Pushes a subset of the bytes in {@code buffer} back to this stream. The * subset is defined by the start position {@code offset} within * {@code buffer} and the number of bytes specified by {@code length}. The * bytes are pushed back in such a way that the next byte read from this * stream is {@code buffer[offset]}, then {@code buffer[1]} and so on. * <p> * If this stream's internal pushback buffer cannot store the selected * subset of {@code buffer}, an {@code IOException} is thrown. Parts of * {@code buffer} may have already been copied to the pushback buffer when * the exception is thrown. * * @param buffer * the buffer containing the bytes to push back to this stream. * @param offset * the index of the first byte in {@code buffer} to push back. * @param length * the number of bytes to push back. * @throws IndexOutOfBoundsException * if {@code offset < 0} or {@code length < 0}, or if * {@code offset + length} is greater than the length of * {@code buffer}. * @throws IOException * if the free space in the internal pushback buffer is not * sufficient to store the selected contents of {@code buffer}. */ public void unread(byte[] buffer, int offset, int length) throws IOException { if (length > pos) { throw new IOException("Pushback buffer full"); } JTranscArrays.checkOffsetAndCount(buffer.length, offset, length); if (buf == null) { throw streamClosed(); } System.arraycopy(buffer, offset, buf, pos - length, length); pos = pos - length; } /** * Pushes the specified byte {@code oneByte} back to this stream. Only the * least significant byte of the integer {@code oneByte} is pushed back. * This is done in such a way that the next byte read from this stream is * {@code (byte) oneByte}. * <p> * If this stream's internal pushback buffer cannot store the byte, an * {@code IOException} is thrown. * * @param oneByte * the byte to push back to this stream. * @throws IOException * if this stream is closed or the internal pushback buffer is * full. */ public void unread(int oneByte) throws IOException { if (buf == null) { throw new IOException(); } if (pos == 0) { throw new IOException("Pushback buffer full"); } buf[--pos] = (byte) oneByte; } /** * Marks the current position in this stream. Setting a mark is not * supported in this class; this implementation does nothing. * * @param readlimit * the number of bytes that can be read from this stream before * the mark is invalidated; this parameter is ignored. */ @Override public void mark(int readlimit) { } /** * Resets this stream to the last marked position. Resetting the stream is * not supported in this class; this implementation always throws an * {@code IOException}. * * @throws IOException * if this method is called. */ @Override public void reset() throws IOException { throw new IOException(); } }
{ "content_hash": "86b0a7e78e7a80c79a6f14ec99e9b066", "timestamp": "", "source": "github", "line_count": 320, "max_line_length": 97, "avg_line_length": 36.00625, "alnum_prop": 0.5923450789793439, "repo_name": "intrigus/jtransc", "id": "a271d83828993ad64e9be09b1fc37be54b8dc84f", "size": "12334", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "jtransc-rt/src/java/io/PushbackInputStream.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ActionScript", "bytes": "25729" }, { "name": "Batchfile", "bytes": "745" }, { "name": "C#", "bytes": "13926" }, { "name": "C++", "bytes": "128248" }, { "name": "CMake", "bytes": "838" }, { "name": "D", "bytes": "13519" }, { "name": "Dart", "bytes": "43216" }, { "name": "HTML", "bytes": "23453" }, { "name": "Haxe", "bytes": "69264" }, { "name": "Java", "bytes": "6958464" }, { "name": "JavaScript", "bytes": "37044" }, { "name": "Kotlin", "bytes": "1112086" }, { "name": "PHP", "bytes": "31733" }, { "name": "Shell", "bytes": "254" } ], "symlink_target": "" }
package com.learn_textinput; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "Learn_TextInput"; } }
{ "content_hash": "672b1f52f16f0bd62199c935ae01834e", "timestamp": "", "source": "github", "line_count": 15, "max_line_length": 73, "avg_line_length": 25, "alnum_prop": 0.704, "repo_name": "renxlWin/React-Native_Demo", "id": "0587c23916e3b48c15b36bc2399381049b4e21e7", "size": "375", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Native/Learn_TextInput/android/app/src/main/java/com/learn_textinput/MainActivity.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "23925" }, { "name": "JavaScript", "bytes": "68334" }, { "name": "Objective-C", "bytes": "80604" }, { "name": "Python", "bytes": "31214" }, { "name": "Ruby", "bytes": "710" } ], "symlink_target": "" }
import sys import re import logging import simplejson as json from cgi import escape from datetime import datetime from datetime import timedelta from time import mktime from time import sleep from string import Template from htmlentitydefs import name2codepoint from os import environ from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app from google.appengine.api import urlfetch from google.appengine.api import memcache td = timedelta(hours=7) allurls = re.compile(r'/(.*)') idurls = re.compile(r'[0-9]+') remtags = re.compile(r'<.*?>') remspaces = re.compile(r'\s+') commas = re.compile(',,',re.M) se_break = re.compile('[.!?:]\s+', re.VERBOSE) charrefpat = re.compile(r'&(#(\d+|x[\da-fA-F]+)|[\w.:-]+);?') HTTP_DATE_FMT = "%a, %d %b %Y %H:%M:%S GMT" ATOM_DATE = "%Y-%m-%dT%H:%M:%SZ" homepagetext = """ <html> <head> <title>PlusFeed - Unofficial Google+ User Feeds</title> <link rel="stylesheet" type="text/css" href="/style.css"> <script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script> </head> <body> <div id="gb"> <span>$countmsg</span> <a href="http://plus.google.com">Google+</a> </div> <div id="header"> <h1>PlusFeed</h1> <h2>Unofficial Google+ User Feeds</h2> <span id="plusone"><g:plusone size="tall"></g:plusone></span> </div> <div id="content"> <div id="intro"> <h2> Want a <span class="stress">feed</span> for your Google+ posts? </h2> <div id="inst"> <p> Simply add a Google+ user number to the end of this site's URL to get an Atom feed of <em>public</em> posts. </p> <p> Example: <a href="http://plusfeed.appspot.com/104961845171318028721">http://plusfeed.appspot.com/<strong>104961845171318028721</strong></a> </p> <p> <br/> You can grab the source for this app on GitHub <a href="https://github.com/russellbeattie/plusfeed">here</a>. </p> <p> <em>Originally created by <a href="http://www.russellbeattie.com">Russell Beattie</a></em> </p> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-24604146-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html> """ homepage = Template(homepagetext) noitemstext = """<?xml version="1.0" encoding="utf-8"?> <feed xmlns="http://www.w3.org/2005/Atom"> <title>No Public Items Found</title> <updated>$up</updated> <id>http://plusfeed.appspot.com/$p</id> <entry> <title>No Public Items Found</title> <link href="http://plus.google.com/$p"/> <id>http://plusfeed.appspot.com/$p?lastupdated=$up</id> <updated>$up</updated> <summary>Google+ user $p has not made any posts public.</summary> </entry> </feed> """ noitems = Template(noitemstext) class MainPage(webapp.RequestHandler): def get(self, p): res = self.response out = res.out if p == '': self.doHome() return if p == 'showall': posts = memcache.get('posts') for k,post in sorted(posts.iteritems(), reverse=True): out.write('<p>' + str(k) + ': <a href="' + post['permalink'] + '">Posted on ' + (post['updated'] - td).strftime('%B %d, %Y - %I:%M %p') + ' PST by ' + post['author'] + '</a> <br/>' + post['title'] + '</p>\n') return if p == 'reset': memcache.flush_all() out.write('reset') return if idurls.match(p): # Rate Limit check ip = environ['REMOTE_ADDR'] now = datetime.today() req_count = None try: req_count = memcache.incr(ip) except: req_count = None #logging.info(str(ip) + ' - ' + str(req_count)) if req_count: if req_count > 60: logging.debug('rate limited - returning 403 - ' + str(req_count)) res.set_status(403) out.write('<h1>403</h1> Forbidden: Rate limit exceeded - 60 request per minute maximum. #' + str(req_count)) return #if req_count > 20: # logging.debug('rate limited - pausing 2 seconds - ' + str(req_count)) # sleep(2) else: memcache.set(ip, 1, 60) # If Modified Since check if 'If-Modified-Since' in self.request.headers: try: ud = memcache.get('time_' + p) uds = datetime.strftime(ud, HTTP_DATE_FMT) ud = datetime.strptime(uds, HTTP_DATE_FMT) last_seen = datetime.strptime(self.request.headers['If-Modified-Since'], HTTP_DATE_FMT) if ud and last_seen and ud <= last_seen: logging.debug('returning 304') res.set_status(304) return except: sys.exc_clear() op = memcache.get(p) if op is not None: logging.debug('delivering from cache') res.headers['Content-Type'] = 'application/atom+xml' out.write(op) return self.doFeed(p) return # No matches self.error(404) out.write('<h1>404 Not Found</h1>') def doHome(self): res = self.response out = res.out msg = '' list = memcache.get('list') if list: msg = ' Serving ' + str(len(list)) + ' feeds in the past 24 hours'; out.write(homepage.substitute(countmsg = msg)) def doFeed(self, p): res = self.response out = res.out try: logging.debug('re-requesting feed') url = 'https://plus.google.com/_/stream/getactivities/' + p + '/?sp=[1,2,"' + p + '",null,null,null,null,"social.google.com",[]]' result = '' try: result = urlfetch.fetch(url, deadline=10) except urlfetch.Error: try: result = urlfetch.fetch(url, deadline=10) except urlfetch.Error: self.error(500) out.write('<h1>500 Server Error</h1><p>' + str(err) + '</p>') logging.error(err) return if result.status_code == 200: txt = result.content txt = txt[5:] txt = commas.sub(',null,',txt) txt = commas.sub(',null,',txt) txt = txt.replace('[,','[null,') txt = txt.replace(',]',',null]') obj = json.loads(txt) posts = obj[1][0] if not posts: #self.error(400) #out.write('<h1>400 - No Public Items Found</h1>') logging.debug('No public feeds found') res.headers['Content-Type'] = 'application/atom+xml' updated = datetime.today() upstr = updated.strftime(ATOM_DATE) out.write(noitems.substitute(up = upstr, p = p)) return author = posts[0][3] authorimg = 'https:' + posts[0][18] updated = datetime.fromtimestamp(float(posts[0][5])/1000) feed = '<?xml version="1.0" encoding="UTF-8"?>\n' feed += '<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">\n' feed += '<title>' + author + ' - Google+ User Feed</title>\n' feed += '<link href="https://plus.google.com/' + p + '" rel="alternate"></link>\n' feed += '<link href="http://plusfeed.appspot.com/' + p + '" rel="self"></link>\n' feed += '<id>https://plus.google.com/' + p + '</id>\n' feed += '<updated>' + updated.strftime(ATOM_DATE) + '</updated>\n' feed += '<author><name>' + author + '</name></author>\n' count = 0 for post in posts: count = count + 1 if count > 10: break dt = datetime.fromtimestamp(float(post[5])/1000) id = post[21] permalink = "https://plus.google.com/" + post[21] desc = '' if post[47]: desc = post[47] elif post[4]: desc = post[4] if post[44]: desc = desc + ' <br/><br/><a href="https://plus.google.com/' + post[44][1] + '">' + post[44][0] + '</a> originally shared this post: '; if post[66]: if post[66][0][1]: desc = desc + ' <br/><br/><a href="' + post[66][0][1] + '">' + post[66][0][3] + '</a>' if post[66][0][6]: if post[66][0][6][0][1].find('image') > -1: desc = desc + ' <p><img src="http:' + post[66][0][6][0][2] + '"/></p>' else: try: desc = desc + ' <a href="' + post[66][0][6][0][8] + '">' + post[66][0][6][0][8] + '</a>' except: sys.exc_clear() if desc == '': desc = permalink ptitle = self.htmldecode(desc) ptitle = remtags.sub(' ', ptitle) ptitle = remspaces.sub(' ', ptitle) sentend = 75 m = se_break.split(ptitle) if m: sentend = len(m[0]) + 1 if sentend < 5 or sentend > 75: sentend = 75 feed += '<entry>\n' feed += '<title>' + escape(ptitle[:sentend]) + '</title>\n' feed += '<link href="' + permalink + '" rel="alternate"></link>\n' feed += '<updated>' + dt.strftime(ATOM_DATE) + '</updated>\n' feed += '<id>tag:plus.google.com,' + dt.strftime('%Y-%m-%d') + ':/' + id + '/</id>\n' feed += '<summary type="html">' + escape(desc) + '</summary>\n' feed += '</entry>\n' feed += '</feed>\n' memcache.set(p, feed, 15 * 60) memcache.set('time_' + p, updated) mlist = memcache.get('list') if mlist: if p not in mlist: mlist.append(p) else: mlist = [] mlist.append(p) memcache.set('list', mlist, 60 * 60 * 24) res.headers['Last-Modified'] = updated.strftime(HTTP_DATE_FMT) res.headers['Content-Type'] = 'application/atom+xml' out.write(feed) else: self.error(404) out.write('<h1>404 - Not Found</h1>') logging.debug(p + ' Not Found') except Exception, err: self.error(500) out.write('<h1>500 Server Error</h1><p>' + str(err) + '</p>') logging.error(err) def htmldecode(self, text): if type(text) is unicode: uchr = unichr else: uchr = lambda value: value > 255 and unichr(value) or chr(value) def entitydecode(match, uchr=uchr): entity = match.group(1) if entity.startswith('#x'): return uchr(int(entity[2:], 16)) elif entity.startswith('#'): return uchr(int(entity[1:])) elif entity in name2codepoint: return uchr(name2codepoint[entity]) else: return match.group(0) return charrefpat.sub(entitydecode, text) #### application = webapp.WSGIApplication([(r'/(.*)', MainPage)],debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main()
{ "content_hash": "1376a5e77658245f4c617ad224ec7b4f", "timestamp": "", "source": "github", "line_count": 401, "max_line_length": 212, "avg_line_length": 26.129675810473817, "alnum_prop": 0.5736781828593243, "repo_name": "jamesward/plusfeed", "id": "713faead8c6024759b3783756baa8b8565e3e9c2", "size": "10478", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "plusfeed.py", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
<?php namespace CP\Bundle\TermsBundle\Propel\Behavior\Tos; use Behavior; use ForeignKey; class TosBehavior extends Behavior { protected $objectBuilderModifier; protected $queryBuilderModifier; public function getObjectBuilderModifier() { if (is_null($this->objectBuilderModifier)) { $this->objectBuilderModifier = new TosBehaviorObjectBuilderModifier($this); } return $this->objectBuilderModifier; } public function getQueryBuilderModifier() { if (is_null($this->queryBuilderModifier)) { $this->queryBuilderModifier = new TosBehaviorQueryBuilderModifier($this); } return $this->queryBuilderModifier; } public function modifyTable() { $table = $this->getTable(); $database = $table->getDatabase(); $agreementTable = $database->getTable('cp_terms_agreement'); $fkEntity = new ForeignKey('FI_cp_terms_agreement_entity'); $fkEntity->setForeignTableCommonName($table->getCommonName()); $fkEntity->setForeignSchemaName($table->getSchema()); $fkEntity->addReference('entity_id', $table->getFirstPrimaryKeyColumn()->getName()); $fkEntity->setPhpName('Entity'); $agreementTable->addForeignKey($fkEntity); } }
{ "content_hash": "e5b53dbc3b81bbffe2f4793b19e63254", "timestamp": "", "source": "github", "line_count": 50, "max_line_length": 92, "avg_line_length": 26.06, "alnum_prop": 0.6615502686108979, "repo_name": "coopers-peele/CPTermsBundle", "id": "e31629bc44d3958237f58e6e94c77be321947fde", "size": "1303", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Propel/Behavior/Tos/TosBehavior.php", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3098" }, { "name": "HTML", "bytes": "24039" }, { "name": "JavaScript", "bytes": "10470" }, { "name": "PHP", "bytes": "58183" } ], "symlink_target": "" }
package org.apache.uima.caseditor.ide; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectNature; import org.eclipse.core.runtime.CoreException; public final class NlpProject implements IProjectNature { private IProject project; @Override public void configure() throws CoreException { } @Override public void deconfigure() throws CoreException { } @Override public IProject getProject() { return project; } @Override public void setProject(IProject project) { this.project = project; } }
{ "content_hash": "8ce21c68775047b4d8ee2aa180904b91", "timestamp": "", "source": "github", "line_count": 30, "max_line_length": 57, "avg_line_length": 18.9, "alnum_prop": 0.7477954144620811, "repo_name": "apache/uima-uimaj", "id": "ca6b0e19d3729593c354b2f7e9dc7c06b7ddced9", "size": "1374", "binary": false, "copies": "2", "ref": "refs/heads/main", "path": "uimaj-ep-cas-editor-ide/src/main/java/org/apache/uima/caseditor/ide/NlpProject.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "34274" }, { "name": "HTML", "bytes": "97356" }, { "name": "Java", "bytes": "15703955" }, { "name": "JavaScript", "bytes": "4760" }, { "name": "Rich Text Format", "bytes": "716" }, { "name": "Shell", "bytes": "33783" }, { "name": "TypeScript", "bytes": "41803" }, { "name": "XSLT", "bytes": "9770" } ], "symlink_target": "" }
import {Component, Input, OnDestroy, OnInit} from '@angular/core'; import {ParamMap, ActivatedRoute} from "@angular/router"; import {UsersRemoteService} from "./users-remote-service"; /** * This class represents the lazy loaded HomeComponent. */ @Component({ moduleId: module.id, selector: 'user-info', templateUrl: 'user-info.component.html', styleUrls: ['user-info.component.css'], }) export class UserInfoComponent implements OnInit,OnDestroy { private userId: any; private sub: any; selected_user={}; params_id:string=''; constructor(private remoteService: UsersRemoteService,private router: ActivatedRoute) { } //Get user by ID GetUserById(){ this.remoteService.getUserById(this.userId).then(res => { this.selected_user = res; }); // return this.selected_user; } ngOnInit() { this.sub = this.router.params.subscribe(params => { this.userId = params['userId']; // (+) converts string 'id' to a number this.GetUserById(); }); } ngOnDestroy() { this.sub.unsubscribe(); } SaveChanges(){ // need to save last update // this.selected_user.lastUpdated = Date.now(); //TODO -- to complete this one after integration with the server this.remoteService.updateUser(this.selected_user); //todo NEED TO CHECK THE REULST -- if success or not } ClearChanges(){ this.GetUserById(); } }
{ "content_hash": "2955ea7f8b8c552ce186658293012f06", "timestamp": "", "source": "github", "line_count": 63, "max_line_length": 89, "avg_line_length": 22.19047619047619, "alnum_prop": 0.6723891273247496, "repo_name": "zedany7/omroqha-admin", "id": "970a24308f8e16b701897706d8d4f39dd9a213e5", "size": "1398", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/app/users/user-info.component.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10076" }, { "name": "HTML", "bytes": "34950" }, { "name": "JavaScript", "bytes": "7251" }, { "name": "Nginx", "bytes": "1052" }, { "name": "TypeScript", "bytes": "62690" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "a0b605acc042edd5a5c7b8e5bafa848c", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "45389cf51b1b3bd4a2a4e41a8dc1cf3c6e34d58e", "size": "176", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Liliopsida/Asparagales/Asparagaceae/Albuca/Albuca oligophylla/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package examples.todolist.persistence.runtime import cats.Monad import doobie.implicits._ import doobie.util.transactor.Transactor import examples.todolist.model.AppModel import examples.todolist.persistence.AppRepository class AppRepositoryHandler[F[_]: Monad](implicit T: Transactor[F]) extends AppRepository.Handler[F] { import examples.todolist.persistence.runtime.queries.AppQueries._ def list: F[List[AppModel]] = listQuery.to[List].transact(T) }
{ "content_hash": "b9b0f4079a2cdfdb6453da323044bfa2", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 67, "avg_line_length": 26.166666666666668, "alnum_prop": 0.7940552016985138, "repo_name": "frees-io/freestyle", "id": "c5700a69aeb8823bf9bd87f0653c5efb48552c05", "size": "1098", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/examples/todolist-lib/src/main/scala/todo/persistence/runtime/AppRepositoryHandler.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2127" }, { "name": "Scala", "bytes": "423439" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_demo1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Start"/> </LinearLayout>
{ "content_hash": "4b65c8b8906620d91378fa8e127e8d7b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 72, "avg_line_length": 34.23076923076923, "alnum_prop": 0.6292134831460674, "repo_name": "SethWen/LearningDemo", "id": "4ce73eaebb90e64ac7c1cb92a7f605d7152ef552", "size": "445", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rxjava2demo/src/main/res/layout/activity_demo1.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "244830" } ], "symlink_target": "" }
package com.kekexun.soochat.smack; import java.io.IOException; import org.jivesoftware.smack.SmackException; import org.jivesoftware.smack.provider.IQProvider; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; public class CustomIQProvider extends IQProvider<CustomIQ> { private CustomIQ myIQ; public CustomIQProvider(CustomIQ myIQ) { this.myIQ = myIQ; } @Override public CustomIQ parse(XmlPullParser parser, int initialDepth) throws XmlPullParserException, IOException, SmackException { return myIQ; } }
{ "content_hash": "272a4b454d61396508e11ca9ab922c1a", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 123, "avg_line_length": 25.217391304347824, "alnum_prop": 0.7724137931034483, "repo_name": "Soo000/SooChat", "id": "6a2c2cf0dce76dc23cdafd30fa0788e10e86c575", "size": "580", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/kekexun/soochat/smack/CustomIQProvider.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "530" }, { "name": "Java", "bytes": "3038446" } ], "symlink_target": "" }
package com.googlesource.gerrit.plugins.importer; import static com.google.gerrit.httpd.restapi.RestApiServlet.JSON_MAGIC; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.apache.http.client.methods.CloseableHttpResponse; public class RestResponse extends HttpResponse { RestResponse(CloseableHttpResponse response) { super(response); } @Override public Reader getReader() throws IllegalStateException, IOException { if (reader == null && response.getEntity() != null) { reader = new InputStreamReader(response.getEntity().getContent()); reader.skip(JSON_MAGIC.length); } return reader; } }
{ "content_hash": "8ba4a6be063e35117c5220783c46065c", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 72, "avg_line_length": 28.375, "alnum_prop": 0.7547723935389133, "repo_name": "GerritCodeReview/plugins_importer", "id": "27ca57068ec946b9120d9410a897d6e4abb5f3d0", "size": "1290", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/googlesource/gerrit/plugins/importer/RestResponse.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "1646" }, { "name": "Java", "bytes": "251407" }, { "name": "JavaScript", "bytes": "5522" }, { "name": "Python", "bytes": "2449" }, { "name": "Shell", "bytes": "1193" } ], "symlink_target": "" }
namespace INMOST { class SolverSUPERLU : public SolverInterface { private: #if defined(USE_SOLVER_SUPERLU_DIST) dLUstruct_t LUstruct; dSOLVEstruct_t SOLVEstruct; dScalePermstruct_t ScalePermstruct; gridinfo_t grid; superlu_dist_options_t options_; SuperLUStat_t stat_; int g_size; #else //USE_SOLVER_SUPERLU_DIST int * perm_r; int * perm_c; int * remap; superlu_options_t options; SuperLUStat_t stat; #endif //USE_SOLVER_SUPERLU_DIST int a_size, info; SuperMatrix A, L, U; public: SolverSUPERLU(); virtual SolverInterface *Copy(const SolverInterface *other); virtual void Assign(const SolverInterface *other); virtual void Setup(int *argc, char ***argv, SolverParameters &p); virtual void SetMatrix(Sparse::Matrix &A, bool ModifiedPattern, bool OldPreconditioner); virtual bool Solve(INMOST::Sparse::Vector &RHS, INMOST::Sparse::Vector &SOL); virtual bool Clear(); virtual bool isMatrixSet(); virtual std::string GetParameter(std::string name) const; virtual void SetParameter(std::string name, std::string value); virtual INMOST_DATA_ENUM_TYPE Iterations() const; virtual INMOST_DATA_REAL_TYPE Residual() const; virtual const std::string ReturnReason() const; virtual const std::string SolverName() const; virtual void Finalize(); virtual ~SolverSUPERLU(); }; } #endif //INMOST_SOLVERSUPERLU_H
{ "content_hash": "428d49989b392dca4af011998fd2c008", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 96, "avg_line_length": 25.383333333333333, "alnum_prop": 0.659881812212738, "repo_name": "INMOST-DEV/INMOST", "id": "801008d9f1e7f978ea7a35323d3deff6301a46e2", "size": "1735", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Source/Solver/solver_superlu/SolverSUPERLU.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "11682" }, { "name": "C++", "bytes": "5404585" }, { "name": "CMake", "bytes": "125470" }, { "name": "XSLT", "bytes": "2311" } ], "symlink_target": "" }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using Cryptany.Core.Router.Data; using System.Diagnostics; using System.Threading; using Cryptany.Common.Utils; using Cryptany.Core.Monitoring; namespace Cryptany.Core.Router.Data { partial class ServiceBlock { //public static ServiceBlock CreateTestServiceBlock() //{ // Block SMS2 = new SendSMSAsync("[SMS2]", null, null); // Block SMS1 = new SendSMSAsync("[SMS1]", SMS2, null); // Block Cond = new ConditionBlock("[Condition]", SMS1, null); // var res = new ServiceBlock(); // res.startBlock = Cond; // //res.EnterCondition = new ConditionBlock("[EnterCondition]", SMS1, null); // return res; //} Dictionary<Guid, Block> _Blocks; /// <summary> /// Список блоков текущего сервисного блока /// </summary> public Dictionary<Guid, Block> Blocks { get { if (_Blocks == null) { _Blocks = (from be in DBCache.BlockEntries.Values where be.ServiceBlockId == this.Id select Block.CreateBlock(be)).ToDictionary(a => a.Id); foreach (Block a in _Blocks.Values) a.ServiceBlock = this; } return _Blocks; } } List<Block> _EnterConditions; /// <summary> /// Набор проверочных блоков для входа в сервисный блок /// </summary> public List<Block> EnterConditions { get { if (_EnterConditions == null) { _EnterConditions = (from be in DBCache.BlockEntries.Values where be.ServiceBlockId == Id && be.IsVerification select Blocks[be.BlockId]).ToList(); } return _EnterConditions; } } /// <summary> /// Проверяет условие входа в сервисный блок. /// </summary> /// <param name="msg">Проверяемое сообщение</param> /// <returns>Возвращает true в случае успешного выполнения всех блоков EnterCondition</returns> public bool Check(Message msg) { foreach (Block b in EnterConditions) if (b.Perform(msg).Count() == 0) // Предполагается, что у проверочных блоков пустой OutFalse return false; return true; } Block _StartBlock = null; /// <summary> /// Входной блок для данной сервисной группы /// </summary> public Block StartBlock { get { if (_StartBlock == null) { // Должен быть сиротой и не быть проверочным /*_StartBlock = (from b in Blocks.Values where b.Parents.Count == 0 && !b.IsVerification select b).First(); */ _StartBlock = EnterConditions.First(); } return _StartBlock; } } public TVService TVService { get { return DBCache.Services[ServiceId]; } } /// <summary> /// Используя поиск в ширину выполняет все дочерние блоки. Останавливается на асинхронных блоках /// </summary> /// <param name="msg">Обрабатываемое сообщение</param> /// <param name="src">Блок с которого начинаем выполнять</param> /// <returns>Список асинхронных блоков на которых остановилась обработка</returns> static AsyncBlock[] PerformBlockRecursively(Message msg, Block src) { // Очередь в которую попадают блоки которые нужно обработать Queue<Block> queue = new Queue<Block>(); // Возвращаемое значение List<AsyncBlock> result = new List<AsyncBlock>(); // Кладем в очередь на обработку первый блок queue.Enqueue((Block)src.Clone()); // и поехали // Пока очередь обработки не пуста while (queue.Count > 0) { // Достаем блок Block cur = queue.Dequeue(); Block[] tmp; try { // Выполняем его tmp = cur.Perform(msg); } catch (Exception e) { //Tracer.Write(msg + " Ошибка при обработке блока " + cur.Name + " типа " + cur.BlockType + ". Дальнейшая обработка блока не производится: " + e); Functions.AddEvent("Ошибка обработки входящего сообщения", "Ошибка обработки входящего сообщения " + msg, EventType.Error, null, e); throw; //Console.WriteLine(e.StackTrace); } // Если блок асинхронный и может повлечь выполнение других блоков, то добавляем его в результат if (cur is AsyncBlock && (cur.OutTrue.Count > 0 || cur.OutFalse.Count > 0)) result.Add((AsyncBlock)cur); // В противном случае всех полученых детей данного блока закидываем в очередь на обработку else foreach (var b in tmp) queue.Enqueue((Block)b.Clone()); } return result.ToArray(); } /// <summary> /// Выполняет набор блоков и всех их детишек /// </summary> /// <param name="msg">Обрабатываемое сообщение</param> /// <param name="srcs">Набор блоков для выполнения</param> /// <returns></returns> static AsyncBlock[] PerformBlocksRecursively(Message msg, Block[] srcs) { List<AsyncBlock> result = new List<AsyncBlock>(); foreach (var src in srcs) { // Объеденяем результаты индивидуальной обработки всех блоков result.AddRange(PerformBlockRecursively(msg, src)); } return result.ToArray(); } /// <summary> /// Обрабатывает внутреннее сообщение роутера, проверяет асинхронные блоки на готовность /// </summary> /// <param name="msg">Обрабатываемое сообщение</param> /// <param name="blocks">Список выполняющихся аснинхронных блоков</param> static public void ProcessInnerMessage(Message msg, List<AsyncBlock> blocks) { // Блоки которые будут удалены из списка List<AsyncBlock> toDelete = new List<AsyncBlock>(); // Блоки, которые будут добавлены в список List<AsyncBlock> toAdd = new List<AsyncBlock>(); foreach (var block in blocks) { // Проверяем готовность асинхронного блока AsyncState state = block.IsReady(msg); switch (state.Status) { // Если блок завершил выполнение case AsyncStatus.Completed: // То выполняем всех его дочерних AsyncBlock[] addBlocks = PerformBlocksRecursively(msg, state.NextBlocks); // Добавляем результаты выполнения в список добавляемых toAdd.AddRange(addBlocks); // И удаляем завершенный блок из списка toDelete.Add(block); break; case AsyncStatus.Expired: //Tracer.Write("Блок [" + block.Name + "] из сервисного блока [" + block.ServiceBlock.Name + "] протух и будет удален"); toDelete.Add(block); break; } } foreach (var b in toDelete) blocks.Remove(b); blocks.AddRange(toAdd); } /// <summary> /// Первичная обработка собщения в сервисном блоке /// </summary> /// <param name="msg">Обрабатываемое сообщение</param> /// <returns>Список выполняющихся аснинхронных блоков</returns> public AsyncBlock[] ProcessInputMessage(Message msg) { return PerformBlockRecursively(msg, StartBlock); } } }
{ "content_hash": "c7067ed0c6ef61693fcc3f277a61135a", "timestamp": "", "source": "github", "line_count": 224, "max_line_length": 166, "avg_line_length": 38.151785714285715, "alnum_prop": 0.5134565878773695, "repo_name": "erupakov/legacy", "id": "304bc3c7e64f362f4aa411f7a30d5e21452fbb03", "size": "10707", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Core/Cryptany.Core.Router.Data/ServiceBlock.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "8848" }, { "name": "C#", "bytes": "2866779" }, { "name": "CSS", "bytes": "12790" }, { "name": "HTML", "bytes": "8454" }, { "name": "JavaScript", "bytes": "1321" } ], "symlink_target": "" }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddHotNewRecommendArticle extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('articles', function (Blueprint $table) { $table->tinyInteger('hot')->default(0)->comment('热门'); $table->tinyInteger('new')->default(0)->comment('最新'); $table->tinyInteger('recommend')->default(0)->comment('推荐'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('articles', function (Blueprint $table) { $table->dropColumn(['hot', 'new', 'recommend']); }); } }
{ "content_hash": "6a6173c829681e60e4c3c79716c670cc", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 72, "avg_line_length": 24.41176470588235, "alnum_prop": 0.5710843373493976, "repo_name": "moore0903/laravel-shop", "id": "7285763b73c0262cf1a390a10beda719fcbc54cf", "size": "842", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "database/migrations/2017_03_09_062923_add_hot_new_recommend_article.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "Batchfile", "bytes": "58" }, { "name": "CSS", "bytes": "36705" }, { "name": "HTML", "bytes": "111763" }, { "name": "JavaScript", "bytes": "1221490" }, { "name": "PHP", "bytes": "680945" }, { "name": "Shell", "bytes": "191" }, { "name": "Vue", "bytes": "563" } ], "symlink_target": "" }
package sagan.site.projects; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; @Repository public interface ReleaseRepository extends JpaRepository<Release, Long> { @Query("SELECT r FROM Release r LEFT JOIN FETCH r.project p WHERE p.id =:projectId AND r.version =:version") Release findRelease(@Param("projectId") String projectId, @Param("version") Version version); @Query("SELECT r FROM Release r LEFT JOIN FETCH r.project p WHERE p.id =:projectId AND r.isCurrent = TRUE") Release findCurrentRelease(@Param("projectId") String projectId); }
{ "content_hash": "f879a52f020797850034fe1efc519643", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 109, "avg_line_length": 45.25, "alnum_prop": 0.7969613259668509, "repo_name": "spring-io/sagan", "id": "491dd0baf90a86a4ea07121255164cb17eaefde5", "size": "724", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "sagan-site/src/main/java/sagan/site/projects/ReleaseRepository.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "140396" }, { "name": "HTML", "bytes": "528355" }, { "name": "Java", "bytes": "525276" }, { "name": "JavaScript", "bytes": "27144" }, { "name": "SCSS", "bytes": "20658" }, { "name": "Shell", "bytes": "3126" }, { "name": "Vim Snippet", "bytes": "124" } ], "symlink_target": "" }
<?php /* This document is meant to follow PSR-1 and PSR-2 php-fig standards http://www.php-fig.org/psr/psr-1/ http://www.php-fig.org/psr/psr-2/ */ /** * The Event System Aware Interface * * This file contains the AwareInterface. Objects that are 'aware' * of the Universal Event (library) have a tracker in them. This tracker * can have listeners added to it (with getTracker()), thus event-izing * the object * * @copyright Copyright 2015 Asher Wolfstein * @author Asher Wolfstein <asherwunk@gmail.com> * @link http://wunk.me/ The author's URL * @link http://www.furdev.com/primus-artificial-intelligence-framework/ Framework URL * @license http://opensource.org/licenses/MIT * @package Event * @subpackage EventObjects * @category Generic * */ /** * Falcraft Libraries Event Resource Namespace * */ namespace Falcraft\Event\Resource { require_once(realpath( __DIR__ . '/../../') . '/falcraftLoad.php'); /* TrackerInterface.php - An event aware object contains a tracker that can be attached to */ $includes = array('/Event/Resource/AbstractEvent.php',); falcraftLoad($includes, __FILE__); use Falcraft\Event\Resource as EventResource; /** * Aware Interface - Defines functions for being event aware * * This interface enforces two functions setTracker and getTracker * These functions 'ensure' that a tracker exists inside a class * (object instanceof AwareInterface), and if that exists we can * get the tracker, and add listeners to it outside of the class * * CHANGELOG * * 1.0 Documented Aware Interface - October 7th, 2013 * 2.0 Integrated into Primus2 - September 13th, 2015 * * @version 2.0 */ interface FilterInterface { /** * Test Event Applicability * * @return Falcraft\Event\TrackerInterface * */ public function isApplicable(EventResource\AbstractEvent $event); } }
{ "content_hash": "02ddc37f3189460ac6ba54a1911f4f96", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 86, "avg_line_length": 29.36231884057971, "alnum_prop": 0.6535044422507403, "repo_name": "asherwunk/primus2", "id": "00075016efbb41c85e46c248f83e04a3506f8aec", "size": "2026", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Falcraft/Event/Resource/FilterInterface.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "974595" } ], "symlink_target": "" }
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "9e0ffed54f8d51699b8dcf9b7cf4bc8b", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.307692307692308, "alnum_prop": 0.6940298507462687, "repo_name": "mdoering/backbone", "id": "e70b1149ab70953f5574f1610dada92831e5cb06", "size": "202", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Bryophyta/Bryopsida/Bryales/Bryaceae/Bryum/Bryum laevigatum/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.apache.ignite.internal.processors.cache.distributed.dht; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.ignite.Ignite; import org.apache.ignite.IgniteCache; import org.apache.ignite.cache.CacheRebalanceMode; import org.apache.ignite.cache.affinity.Affinity; import org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction; import org.apache.ignite.cluster.ClusterNode; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.events.Event; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionFullMap; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPartitionMap; import org.apache.ignite.internal.processors.cache.distributed.dht.preloader.GridDhtPreloader; import org.apache.ignite.internal.util.typedef.F; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.lang.IgnitePredicate; import org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi; import org.apache.ignite.spi.discovery.tcp.ipfinder.TcpDiscoveryIpFinder; import org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.cache.CacheRebalanceMode.ASYNC; import static org.apache.ignite.cache.CacheRebalanceMode.SYNC; import static org.apache.ignite.cache.CacheWriteSynchronizationMode.FULL_SYNC; import static org.apache.ignite.configuration.CacheConfiguration.DFLT_REBALANCE_BATCH_SIZE; import static org.apache.ignite.configuration.DeploymentMode.CONTINUOUS; import static org.apache.ignite.events.EventType.EVTS_CACHE_REBALANCE; import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.MOVING; import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.OWNING; import static org.apache.ignite.internal.processors.cache.distributed.dht.GridDhtPartitionState.RENTING; /** * Test cases for partitioned cache {@link GridDhtPreloader preloader}. */ public class GridCacheDhtPreloadSelfTest extends GridCommonAbstractTest { /** Flag to print preloading events. */ private static final boolean DEBUG = false; /** */ private static final long TEST_TIMEOUT = 5 * 60 * 1000; /** Default backups. */ private static final int DFLT_BACKUPS = 1; /** Partitions. */ private static final int DFLT_PARTITIONS = 521; /** Preload batch size. */ private static final int DFLT_BATCH_SIZE = DFLT_REBALANCE_BATCH_SIZE; /** Number of key backups. Each test method can set this value as required. */ private int backups = DFLT_BACKUPS; /** Preload mode. */ private CacheRebalanceMode preloadMode = ASYNC; /** */ private int preloadBatchSize = DFLT_BATCH_SIZE; /** Number of partitions. */ private int partitions = DFLT_PARTITIONS; /** IP finder. */ private TcpDiscoveryIpFinder ipFinder = new TcpDiscoveryVmIpFinder(true); /** * */ public GridCacheDhtPreloadSelfTest() { super(false /*start grid. */); } /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName); TcpDiscoverySpi disco = new TcpDiscoverySpi(); disco.setIpFinder(ipFinder); cfg.setDiscoverySpi(disco); cfg.setCacheConfiguration(cacheConfiguration(igniteInstanceName)); cfg.setDeploymentMode(CONTINUOUS); return cfg; } /** * Gets cache configuration for grid with given name. * * @param igniteInstanceName Ignite instance name. * @return Cache configuration. */ protected CacheConfiguration cacheConfiguration(String igniteInstanceName) { CacheConfiguration cacheCfg = defaultCacheConfiguration(); cacheCfg.setCacheMode(PARTITIONED); cacheCfg.setRebalanceBatchSize(preloadBatchSize); cacheCfg.setWriteSynchronizationMode(FULL_SYNC); cacheCfg.setRebalanceMode(preloadMode); cacheCfg.setAffinity(new RendezvousAffinityFunction(false, partitions)); cacheCfg.setBackups(backups); cacheCfg.setOnheapCacheEnabled(onheapCacheEnabled()); return cacheCfg; } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { backups = DFLT_BACKUPS; partitions = DFLT_PARTITIONS; preloadMode = ASYNC; preloadBatchSize = DFLT_BATCH_SIZE; } /** {@inheritDoc} */ @Override protected long getTestTimeout() { return TEST_TIMEOUT; } /** * @return {@code True} if on-heap cache is enabled. */ protected boolean onheapCacheEnabled() { return false; } /** * @throws Exception If failed. */ public void testActivePartitionTransferSyncSameCoordinator() throws Exception { preloadMode = SYNC; checkActivePartitionTransfer(1000, 4, true, false); } /** * @throws Exception If failed. */ public void testActivePartitionTransferAsyncSameCoordinator() throws Exception { checkActivePartitionTransfer(1000, 4, true, false); } /** * @throws Exception If failed. */ public void testActivePartitionTransferSyncChangingCoordinator() throws Exception { preloadMode = SYNC; checkActivePartitionTransfer(1000, 4, false, false); } /** * @throws Exception If failed. */ public void testActivePartitionTransferAsyncChangingCoordinator() throws Exception { checkActivePartitionTransfer(1000, 4, false, false); } /** * @throws Exception If failed. */ public void testActivePartitionTransferSyncRandomCoordinator() throws Exception { preloadMode = SYNC; checkActivePartitionTransfer(1000, 4, false, true); } /** * @throws Exception If failed. */ public void testActivePartitionTransferAsyncRandomCoordinator() throws Exception { checkActivePartitionTransfer(1000, 4, false, true); } /** * @param keyCnt Key count. * @param nodeCnt Node count. * @param sameCoord Same coordinator flag. * @param shuffle Shuffle flag. * @throws Exception If failed. */ private void checkActivePartitionTransfer(int keyCnt, int nodeCnt, boolean sameCoord, boolean shuffle) throws Exception { try { Ignite ignite1 = startGrid(0); IgniteCache<Integer, String> cache1 = ignite1.cache(DEFAULT_CACHE_NAME); putKeys(cache1, keyCnt); checkKeys(cache1, keyCnt, F.asList(ignite1)); List<Ignite> ignites = new ArrayList<>(nodeCnt + 1); startGrids(nodeCnt, 1, ignites); // Check all nodes. for (Ignite g : ignites) { IgniteCache<Integer, String> c = g.cache(DEFAULT_CACHE_NAME); checkKeys(c, keyCnt, ignites); } if (shuffle) Collections.shuffle(ignites); if (sameCoord) // Add last. ignites.add(ignite1); else // Add first. ignites.add(0, ignite1); if (!sameCoord && shuffle) Collections.shuffle(ignites); checkActiveState(ignites); info(">>> Finished checking nodes [keyCnt=" + keyCnt + ", nodeCnt=" + nodeCnt + ", grids=" + U.grids2names(ignites) + ']'); Ignite last = F.last(ignites); for (Iterator<Ignite> it = ignites.iterator(); it.hasNext(); ) { Ignite g = it.next(); if (!it.hasNext()) { assert last == g; break; } checkActiveState(ignites); it.remove(); info("Before grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites)); stopGrid(g.name()); info("After grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites)); // Check all left nodes. checkActiveState(ignites); awaitPartitionMapExchange(); // Need wait, otherwise test logic is broken if EVT_NODE_FAILED exchanges are merged. } info("Finished waiting for preload futures."); assert last != null; IgniteCache<Integer, String> lastCache = last.cache(DEFAULT_CACHE_NAME); GridDhtCacheAdapter<Integer, String> dht = dht(lastCache); Affinity<Integer> aff = affinity(lastCache); info("Finished waiting for all exchange futures..."); for (int i = 0; i < keyCnt; i++) { if (aff.mapPartitionToPrimaryAndBackups(aff.partition(i)).contains(last.cluster().localNode())) { GridDhtPartitionTopology top = dht.topology(); for (GridDhtLocalPartition p : top.localPartitions()) { Collection<ClusterNode> moving = top.moving(p.id()); assert moving.isEmpty() : "Nodes with partition in moving state [part=" + p + ", moving=" + moving + ']'; assert OWNING == p.state() : "Invalid partition state for partition [part=" + p + ", map=" + top.partitionMap(false) + ']'; } } } checkActiveState(ignites); } catch (Error | Exception e) { error("Test failed.", e); throw e; } finally { stopAllGrids(); } } /** * @param grids Grids. */ private void checkActiveState(Iterable<Ignite> grids) { // Check that nodes don't have non-active information about other nodes. for (Ignite g : grids) { IgniteCache<Integer, String> c = g.cache(DEFAULT_CACHE_NAME); GridDhtCacheAdapter<Integer, String> dht = dht(c); GridDhtPartitionFullMap allParts = dht.topology().partitionMap(false); for (GridDhtPartitionMap parts : allParts.values()) { if (!parts.nodeId().equals(g.cluster().localNode().id())) { for (Map.Entry<Integer, GridDhtPartitionState> e : parts.entrySet()) { int p = e.getKey(); GridDhtPartitionState state = e.getValue(); assert state == OWNING || state == MOVING || state == RENTING : "Invalid state [igniteInstanceName=" + g.name() + ", part=" + p + ", state=" + state + ", parts=" + parts + ']'; assert state.active(); } } } } } /** * @throws Exception If failed. */ public void testMultiplePartitionBatchesSyncPreload() throws Exception { preloadMode = SYNC; preloadBatchSize = 100; partitions = 2; checkNodes(1000, 1, true, false); } /** * @throws Exception If failed. */ public void testMultiplePartitionBatchesAsyncPreload() throws Exception { preloadBatchSize = 100; partitions = 2; checkNodes(1000, 1, true, false); } /** * @throws Exception If failed. */ public void testMultipleNodesSyncPreloadSameCoordinator() throws Exception { preloadMode = SYNC; checkNodes(1000, 4, true, false); } /** * @throws Exception If failed. */ public void testMultipleNodesAsyncPreloadSameCoordinator() throws Exception { checkNodes(1000, 4, true, false); } /** * @throws Exception If failed. */ public void testMultipleNodesSyncPreloadChangingCoordinator() throws Exception { preloadMode = SYNC; checkNodes(1000, 4, false, false); } /** * @throws Exception If failed. */ public void testMultipleNodesAsyncPreloadChangingCoordinator() throws Exception { checkNodes(1000, 4, false, false); } /** * @throws Exception If failed. */ public void testMultipleNodesSyncPreloadRandomCoordinator() throws Exception { preloadMode = SYNC; checkNodes(1000, 4, false, true); } /** * @throws Exception If failed. */ public void testMultipleNodesAsyncPreloadRandomCoordinator() throws Exception { checkNodes(1000, 4, false, true); } /** * @param cnt Number of grids. * @param startIdx Start node index. * @param list List of started grids. * @throws Exception If failed. */ private void startGrids(int cnt, int startIdx, Collection<Ignite> list) throws Exception { for (int i = 0; i < cnt; i++) { final Ignite g = startGrid(startIdx++); if (DEBUG) g.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event evt) { info("\n>>> Preload event [igniteInstanceName=" + g.name() + ", evt=" + evt + ']'); return true; } }, EVTS_CACHE_REBALANCE); list.add(g); } } /** * @param grids Grids to stop. */ private void stopGrids(Iterable<Ignite> grids) { for (Ignite g : grids) stopGrid(g.name()); } /** * @param keyCnt Key count. * @param nodeCnt Node count. * @param sameCoord Same coordinator flag. * @param shuffle Shuffle flag. * @throws Exception If failed. */ private void checkNodes(int keyCnt, int nodeCnt, boolean sameCoord, boolean shuffle) throws Exception { try { Ignite ignite1 = startGrid(0); IgniteCache<Integer, String> cache1 = ignite1.cache(DEFAULT_CACHE_NAME); putKeys(cache1, keyCnt); checkKeys(cache1, keyCnt, F.asList(ignite1)); List<Ignite> ignites = new ArrayList<>(nodeCnt + 1); startGrids(nodeCnt, 1, ignites); // Check all nodes. for (Ignite g : ignites) { IgniteCache<Integer, String> c = g.cache(DEFAULT_CACHE_NAME); checkKeys(c, keyCnt, ignites); } if (shuffle) Collections.shuffle(ignites); if (sameCoord) // Add last. ignites.add(ignite1); else // Add first. ignites.add(0, ignite1); if (!sameCoord && shuffle) Collections.shuffle(ignites); info(">>> Finished checking nodes [keyCnt=" + keyCnt + ", nodeCnt=" + nodeCnt + ", grids=" + U.grids2names(ignites) + ']'); Ignite last = null; for (Iterator<Ignite> it = ignites.iterator(); it.hasNext(); ) { Ignite g = it.next(); if (!it.hasNext()) { last = g; break; } final UUID nodeId = g.cluster().localNode().id(); it.remove(); info("Before grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites)); stopGrid(g.name()); info(">>> Waiting for preload futures [leftNode=" + g.name() + ", remaining=" + U.grids2names(ignites) + ']'); awaitPartitionMapExchange(); info("After grid stop [name=" + g.name() + ", fullTop=" + top2string(ignites)); // Check all left nodes. for (Ignite gg : ignites) { IgniteCache<Integer, String> c = gg.cache(DEFAULT_CACHE_NAME); checkKeys(c, keyCnt, ignites); } } assert last != null; IgniteCache<Integer, String> lastCache = last.cache(DEFAULT_CACHE_NAME); GridDhtCacheAdapter<Integer, String> dht = dht(lastCache); Affinity<Integer> aff = affinity(lastCache); for (int i = 0; i < keyCnt; i++) { if (aff.mapPartitionToPrimaryAndBackups(aff.partition(i)).contains(last.cluster().localNode())) { GridDhtPartitionTopology top = dht.topology(); for (GridDhtLocalPartition p : top.localPartitions()) { Collection<ClusterNode> moving = top.moving(p.id()); assert moving.isEmpty() : "Nodes with partition in moving state [part=" + p + ", moving=" + moving + ']'; assert OWNING == p.state() : "Invalid partition state for partition [part=" + p + ", map=" + top.partitionMap(false) + ']'; } } } } catch (Error | Exception e) { error("Test failed.", e); throw e; } finally { stopAllGrids(); } } /** * @param c Cache. * @param cnt Key count. */ private void putKeys(IgniteCache<Integer, String> c, int cnt) { for (int i = 0; i < cnt; i++) c.put(i, Integer.toString(i)); } /** * @param cache Cache. * @param cnt Key count. * @param grids Grids. */ private void checkKeys(IgniteCache<Integer, String> cache, int cnt, Iterable<Ignite> grids) { Affinity<Integer> aff = affinity(cache); Ignite ignite = cache.unwrap(Ignite.class); ClusterNode loc = ignite.cluster().localNode(); boolean sync = cache.getConfiguration(CacheConfiguration.class).getRebalanceMode() == SYNC; for (int i = 0; i < cnt; i++) { Collection<ClusterNode> nodes = ignite.cluster().nodes(); Collection<ClusterNode> affNodes = aff.mapPartitionToPrimaryAndBackups(aff.partition(i)); assert !affNodes.isEmpty(); if (affNodes.contains(loc)) { String val = sync ? cache.localPeek(i) : cache.get(i); ClusterNode primaryNode = F.first(affNodes); assert primaryNode != null; boolean primary = primaryNode.equals(loc); assertEquals("Key check failed [igniteInstanceName=" + ignite.name() + ", cache=" + cache.getName() + ", key=" + i + ", expected=" + i + ", actual=" + val + ", part=" + aff.partition(i) + ", primary=" + primary + ", affNodes=" + U.nodeIds(affNodes) + ", locId=" + loc.id() + ", allNodes=" + U.nodeIds(nodes) + ", allParts=" + top2string(grids) + ']', Integer.toString(i), val); } } } /** * @param grids Grids * @return String representation of all partitions and their state. */ @SuppressWarnings({"ConstantConditions"}) private String top2string(Iterable<Ignite> grids) { Map<String, String> map = new HashMap<>(); for (Ignite g : grids) { IgniteCache<Integer, String> c = g.cache(DEFAULT_CACHE_NAME); GridDhtCacheAdapter<Integer, String> dht = dht(c); GridDhtPartitionFullMap fullMap = dht.topology().partitionMap(false); map.put(g.name(), DEBUG ? fullMap.toFullString() : fullMap.toString()); } return "Grid partition maps [" + map.toString() + ']'; } }
{ "content_hash": "37541c11d0e3fa3f9f099dc6b310ab3c", "timestamp": "", "source": "github", "line_count": 612, "max_line_length": 130, "avg_line_length": 32.55065359477124, "alnum_prop": 0.5895286381205763, "repo_name": "amirakhmedov/ignite", "id": "23ba4b31b4e0aa2d776a8ae16fd2ca094ebdf11c", "size": "20723", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "modules/core/src/test/java/org/apache/ignite/internal/processors/cache/distributed/dht/GridCacheDhtPreloadSelfTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "52347" }, { "name": "C", "bytes": "5286" }, { "name": "C#", "bytes": "6034276" }, { "name": "C++", "bytes": "3477717" }, { "name": "CSS", "bytes": "294151" }, { "name": "Dockerfile", "bytes": "14742" }, { "name": "Groovy", "bytes": "15081" }, { "name": "HTML", "bytes": "1435826" }, { "name": "Java", "bytes": "35885427" }, { "name": "JavaScript", "bytes": "2099977" }, { "name": "M4", "bytes": "14696" }, { "name": "Makefile", "bytes": "114524" }, { "name": "PHP", "bytes": "11079" }, { "name": "PowerShell", "bytes": "12344" }, { "name": "SQLPL", "bytes": "307" }, { "name": "Scala", "bytes": "1000810" }, { "name": "Shell", "bytes": "599596" }, { "name": "Smalltalk", "bytes": "1908" }, { "name": "TypeScript", "bytes": "4522" } ], "symlink_target": "" }
""" Dependencies register functions. --- type: python_module validation_level: v00_minimum protection: k00_public copyright: "Copyright 2016 High Integrity Artificial Intelligence Systems" license: "Licensed under the Apache License, Version 2.0 (the License); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License." ... """ import difflib import io import json import os import os.path import git import da.check.constants import da.register import da.util # ----------------------------------------------------------------------------- @da.util.coroutine def coro(dirpath_lwc_root, build_monitor): """ Check the dependencies register for nonconformities. """ while True: build_unit = (yield) if not build_unit['filepath'].endswith('dependencies.register.json'): continue reg = _load_register(dirpath_lwc_root) _check_register_format(reg, build_monitor) _compare_with_filesystem(reg, build_monitor, dirpath_lwc_root) # ----------------------------------------------------------------------------- def _load_register(dirpath_lwc_root): """ Return collated and loaded dependencies register file information. """ dirpath = da.lwc.discover.path(key = 'registry', dirpath_lwc_root = dirpath_lwc_root) filepath = os.path.join(dirpath, 'dependencies.register.json') with open(filepath, 'r') as file: json_text = file.read() data = json.loads(json_text) return { 'filepath': filepath, 'text': json_text, 'data': data } # ----------------------------------------------------------------------------- def _compare_with_filesystem(reg, build_monitor, dirpath_lwc_root): """ Compare the content of the dependencies register with the filesystem. Is the dependencies register consistent with the content of the depencencies directories (a0_env) on the filesystem. """ rootpath_env = da.lwc.discover.path( key = 'env', dirpath_lwc_root = dirpath_lwc_root) rootpath_env_src = os.path.join(rootpath_env, 'src') regdata = da.lwc.env.dependencies_register( dirpath_lwc_root = dirpath_lwc_root) dirpath_curr_env = da.lwc.discover.path( key = 'current_env', dirpath_lwc_root = dirpath_lwc_root) # Missing configuration. set_src = {it.name for it in os.scandir(rootpath_env_src) if it.is_dir()} set_bin = {it.name for it in os.scandir(dirpath_curr_env) if it.is_dir()} set_cfg = {it['dirname'] for it in regdata.values()} on_disc = (set_src | set_bin) no_cfg = on_disc - set_cfg for name in sorted(no_cfg): message = 'No dependency configuration for {name}'.format(name = name) build_monitor.report_nonconformity( tool = 'da.check.dependencies', msg_id = da.check.constants.DEP_NO_CONFIG, msg = message, path = reg['filepath']) # Repositories used. for (key, value) in regdata.items(): relpath_src = os.path.join(value['dirname'], value['policy']) dirpath_src = os.path.join(rootpath_env_src, relpath_src) # Mercurial? dirpath_hg = os.path.join(dirpath_src, '.hg') if os.path.isdir(dirpath_hg): if value['config']['url'] == 'TBD': message = 'No mercurial url for {key}'.format(key = key) build_monitor.report_nonconformity( tool = 'da.check.dependencies', msg_id = da.check.constants.DEP_NO_HG_URL, msg = message, path = reg['filepath']) # hg paths # Git? dirpath_git = os.path.join(dirpath_src, '.git') if os.path.isdir(dirpath_git): repo = git.Repo(dirpath_src) if len(repo.remotes) == 0: continue url = repo.remotes.origin.url if url != value['config']['url']: message = 'Bad git url for {key}'.format(key = key) build_monitor.report_nonconformity( tool = 'da.check.dependencies', msg_id = da.check.constants.DEP_NO_GIT_URL, msg = message, path = reg['filepath']) # regdata = # for key, dep in regdata.items(): # dirname_dep = dep['dirname'] # dirname_pol = dep['policy'] # dirpath_src = os.path.join(dirpath_env_src, dirname_dep, dirname_pol) # if not os.path.isdir(dirpath_src): # raise RuntimeError('PATH NOT FOUOND: {path}'.format( # path = dirpath_src)) # dirpath_env_bin = os.path.join(dirpath_env, # 'e00_x86_64_linux_ubuntu_xenial') # ----------------------------------------------------------------------------- def _check_register_format(reg, build_monitor): """ Check the register format. We do this by generating a perfectly formatted version and then comparing it to the version on disc. Any discrepancy will be reported as a design nonconformity. """ register_text = reg['text'] reference_text = _format_register(reg['data']) if reference_text != register_text: reference_lines = reference_text.splitlines() register_lines = register_text.splitlines() iline = 0 for iline, lines in enumerate(zip(reference_lines, register_lines)): (ref_line, reg_line) = lines if ref_line != reg_line: break diff_text = '\n'.join((line for line in difflib.context_diff( reference_lines, register_lines, 'reference_format', 'current_register'))) msg = 'Dependencies register format error '\ 'on line {line}:\n{diff}'.format(line = iline, diff = diff_text) build_monitor.report_nonconformity( tool = 'da.check.dependencies', msg_id = da.check.constants.DEP_REGISTER_FORMAT, msg = msg, path = reg['filepath']) # ----------------------------------------------------------------------------- def _format_register(register_data): """ Return a formatted register document. """ json_doc = VerticallyAlignedJSON() json_doc >>= None json_doc = _add_register_header(json_doc, register_data) json_doc >>= 'register' for (name, entry) in sorted(register_data['register'].items()): json_doc += None json_doc >>= name json_doc = _add_register_entry(json_doc, entry) json_doc <<= name json_doc <<= 'register' json_doc <<= None return str(json_doc) # ----------------------------------------------------------------------------- def _add_register_header(json_doc, register_data): """ Add the dependencies register header information to the supplied JSON doc. """ json_doc += None json_doc += ('title', register_data['title']) json_doc += None json_doc += ('introduction', register_data['introduction']) json_doc += None return json_doc # ----------------------------------------------------------------------------- def _add_register_entry(json_doc, entry): """ Add a single dependencies registry entry to the supplied JSON doc. """ json_doc += ('desc', entry['desc']) json_doc += ('notes', entry['notes']) json_doc += ('dirname', entry['dirname']) json_doc += ('policy', entry['policy']) json_doc = _add_api_section( json_doc, entry) json_doc = _add_cli_section( json_doc, entry) json_doc = _add_gui_section( json_doc, entry) json_doc = _add_config_section( json_doc, entry) json_doc = _add_build_section( json_doc, entry) return json_doc # ----------------------------------------------------------------------------- def _add_api_section(json_doc, entry): """ Add an API section to the supplied JSON doc. """ json_doc >>= 'api' for (api_name, api_path) in sorted(entry['api'].items()): json_doc += (api_name, api_path) json_doc <<= 'api' return json_doc # ----------------------------------------------------------------------------- def _add_cli_section(json_doc, entry): """ Add a CLI section to the supplied JSON doc. """ json_doc >>= 'cli' for (cli_name, cli_path) in sorted(entry['cli'].items()): json_doc += (cli_name, cli_path) json_doc <<= 'cli' return json_doc # ----------------------------------------------------------------------------- def _add_gui_section(json_doc, entry): """ Add a GUI section to the supplied JSON doc. """ json_doc >>= 'gui' for (gui_name, gui_path) in sorted(entry['gui'].items()): json_doc += (gui_name, gui_path) json_doc <<= 'gui' return json_doc # ----------------------------------------------------------------------------- def _add_config_section(json_doc, entry): """ Add a config section to the supplied JSON doc. """ json_doc >>= 'config' json_doc += ('method', entry['config']['method']) json_doc += ('tool', entry['config']['tool']) json_doc += ('url', entry['config']['url']) json_doc <<= 'config' return json_doc # ----------------------------------------------------------------------------- def _add_build_section(json_doc, entry): """ Add a build section to the supplied JSON doc. """ json_doc >>= 'build' json_doc += ('method', entry['build']['method']) json_doc += ('tool', entry['build']['tool']) json_doc <<= 'build' return json_doc # ============================================================================= # disabled pylint rule R0903 - too-few-public-methods # because this class mainly uses operator overloading # rather than traditional methods. Probably not OK for # safety critical stuff -- but fine for formatting # configuration files as we are doing here. (IMHO). # class VerticallyAlignedJSON(): # pylint: disable=R0903 """ Vertically aligned JSON serialisation. This class is used to feed my OCD by generating JSON format configuration files with content that is nicely vertically aligned for human comprehension. """ # ------------------------------------------------------------------------- def __init__(self, indent_size = 4, content_col = 32): """ Return a newly constructed inprint.Doc class. """ self.indent_size = indent_size self.content_col = content_col # The very first '{' in the file does not # need to be preceeded by a newline. # self.newline_needed = False # The brace character that opens a new # section does not need to be followed # by a comma, and neither does the last # item in the section. # self.comma_needed = False self.stack = [] self.buffer = io.StringIO() # ------------------------------------------------------------------------- def __str__(self): """ Return document content as a string. """ self.buffer.write('\n') return self.buffer.getvalue() # ------------------------------------------------------------------------- def __irshift__(self, name): """ Add a new section to the document and return self. The operator >>= function adds a new section with the specified name to the document and increases the indentation level. The parameter on the RHS can be set to None to add an anonymous section. """ if name is not None: self.buffer.write('{newline}{indent}"{name}": {{'.format( newline = self._get_newline(), indent = self._get_indent(), name = name)) else: self.buffer.write('{newline}{indent}{{'.format( newline = self._get_newline(), indent = self._get_indent())) self.stack.append(name) self.comma_needed = False return self # ------------------------------------------------------------------------- def __ilshift__(self, name): """ Set the end of the current section and return self. The operator <<= function ends the current section and reduces the indentation level. If the parameter on the RHS of the operator is not None, then it is compared with the current section and an exception raised in the case of a mismatch. """ prev = self.stack.pop() self.comma_needed = False self.buffer.write('{newline}{indent}}}'.format( newline = self._get_newline(), indent = self._get_indent())) self.comma_needed = True if name is not None: assert prev == name return self # ------------------------------------------------------------------------- def __iadd__(self, item): """ Add an item to the document and return self. The operator += function adds the specified item to the document. """ if item is None: self.buffer.write('{newline}'.format( newline = self._get_newline())) self.comma_needed = False else: assert len(item) == 2 self._add_key_value_pair(key = item[0], value = item[1]) self.comma_needed = True return self # ------------------------------------------------------------------------- def _add_key_value_pair(self, key, value): """ Add a key-value pair to the document. """ assert len(self.stack) > 0 assert isinstance(key, str) key = '{indent}"{key}": '.format( indent = self._get_indent(), key = key) tab = self.content_col - len(key) if tab > 0: key += (' ' * tab) # Currently I'm only envisaging doing this # with simple key-value pairs where key and # value are both strings. This function could # be extended in future to handle different # types, but for the moment we just return # an error. # assert isinstance(value, str) self.buffer.write('{newline}{key}"{value}"'.format( newline = self._get_newline(), key = key, value = value)) # ------------------------------------------------------------------------- def _get_newline(self): """ Return an appropriate line termination and newline as a string. """ # The very first '{' in the file does not # need to be preceeded by a newline. # if not self.newline_needed: self.newline_needed = True return '' if self.comma_needed: return ',\n' else: return '\n' # ------------------------------------------------------------------------- def _get_indent(self): """ Return the current top-level indent as a string. """ num_indents = len(self.stack) num_spaces = num_indents * self.indent_size indent = ' ' * num_spaces return indent
{ "content_hash": "0f509e4eec052288408b660d2b738556", "timestamp": "", "source": "github", "line_count": 502, "max_line_length": 79, "avg_line_length": 34.23107569721115, "alnum_prop": 0.47794459962756053, "repo_name": "wtpayne/hiai", "id": "ce9091bf02face3ce4c8eb9e4258808356d8c0ca", "size": "17208", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "a3_src/h70_internal/da/check/dependencies.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "255" }, { "name": "Python", "bytes": "894704" }, { "name": "Shell", "bytes": "18289" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#fff"> <RelativeLayout android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"> <TextView android:id="@+id/title_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:textColor="#fff" android:textSize="20sp"/> <Button android:id="@+id/back_button" android:layout_width="25dp" android:layout_height="25dp" android:layout_marginLeft="10dp" android:layout_alignParentLeft="true" android:background="@drawable/ic_back"/> </RelativeLayout> <ListView android:id="@+id/list_view" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
{ "content_hash": "111ff403991d860ae37827587855adc7", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 72, "avg_line_length": 33.57142857142857, "alnum_prop": 0.6204255319148936, "repo_name": "hln0408/coolweather", "id": "4a30b49c9c392bd48056506f22bc98a4230e97cb", "size": "1175", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/res/layout/choose_area.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "34665" } ], "symlink_target": "" }
import express from 'express' import consign from 'consign' import bodyParser from 'body-parser' import expressValidator from 'express-validator' module.exports = () => { const app = express() app.set('port', process.env.PORT || 3000) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({extended: true})) app.use(expressValidator()) consign({ verbose: false}) .include('controllers') .then('persistence') .into(app) return app }
{ "content_hash": "b66b54b735532f67eff5e470744f5201", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 49, "avg_line_length": 20.636363636363637, "alnum_prop": 0.7136563876651982, "repo_name": "RafaelPaulo/payfast", "id": "0715429e285683e87e3a3b5f85ec9de3e53a8343", "size": "454", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "config/custom-express.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "4514" } ], "symlink_target": "" }
package uk.ac.ebi.quickgo.rest.search.query; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.mockito.Mockito.verify; /** * Tests the behaviour of the {@link ContainsFieldQuery}. */ @RunWith(MockitoJUnitRunner.class) public class ContainsFieldQueryTest { @Mock private uk.ac.ebi.quickgo.rest.search.query.QueryVisitor visitor; @Test(expected = IllegalArgumentException.class) public void nullFieldThrowsException() throws Exception { String field = null; String value = "value"; new ContainsFieldQuery(field, value); } @Test(expected = IllegalArgumentException.class) public void emptyFieldThrowsException() throws Exception { String field = ""; String value = "value"; new ContainsFieldQuery(field, value); } @Test(expected = IllegalArgumentException.class) public void nullValueThrowsException() throws Exception { String field = "field"; String value = null; new ContainsFieldQuery(field, value); } @Test(expected = IllegalArgumentException.class) public void emptyValueThrowsException() throws Exception { String field = "field"; String value = ""; new ContainsFieldQuery(field, value); } @Test public void createFieldAndValueQuery() throws Exception { String field = "field"; String value = "myName"; ContainsFieldQuery query = new ContainsFieldQuery(field, value); assertThat(query.field(), is(equalTo(field))); assertThat(query.value(), is(equalTo(value))); } @Test public void visitorIsCalledCorrectly() throws Exception { ContainsFieldQuery query = new ContainsFieldQuery("field1", "value1"); query.accept(visitor); verify(visitor).visit(query); } }
{ "content_hash": "cb9b6bbccda4a14d5213c892077cdc1f", "timestamp": "", "source": "github", "line_count": 72, "max_line_length": 69, "avg_line_length": 28.958333333333332, "alnum_prop": 0.6820143884892086, "repo_name": "ebi-uniprot/QuickGOBE", "id": "3ae26cc8c87bc901d86af9f06cccd4611589097f", "size": "2085", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "rest-common/src/test/java/uk/ac/ebi/quickgo/rest/search/query/ContainsFieldQueryTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "11025" }, { "name": "HTML", "bytes": "8766" }, { "name": "Java", "bytes": "3320880" }, { "name": "JavaScript", "bytes": "64224" }, { "name": "Kotlin", "bytes": "5054" }, { "name": "Shell", "bytes": "75212" }, { "name": "XSLT", "bytes": "74769" } ], "symlink_target": "" }
<?php namespace Webmozart\Expression\Comparison; use Webmozart\Expression\Expression; use Webmozart\Expression\Logic\Literal; use Webmozart\Expression\Util\StringUtil; /** * Checks that a value has a given suffix. * * @since 1.0 * * @author Bernhard Schussek <bschussek@gmail.com> */ final class EndsWith extends Literal { /** * @var string */ private $acceptedSuffix; /** * Creates the expression. * * @param string $acceptedSuffix The accepted suffix. */ public function __construct($acceptedSuffix) { $this->acceptedSuffix = $acceptedSuffix; } /** * Returns the accepted suffix. * * @return string The accepted suffix. */ public function getAcceptedSuffix() { return $this->acceptedSuffix; } /** * {@inheritdoc} */ public function evaluate($value) { return $this->acceptedSuffix === substr($value, -strlen($this->acceptedSuffix)); } /** * {@inheritdoc} */ public function equivalentTo(Expression $other) { // Since this class is final, we can check with instanceof return $other instanceof $this && $this->acceptedSuffix == $other->acceptedSuffix; } /** * {@inheritdoc} */ public function toString() { return 'endsWith('.StringUtil::formatValue($this->acceptedSuffix).')'; } }
{ "content_hash": "f251fbb8bac08a3ad309df1376ef3aba", "timestamp": "", "source": "github", "line_count": 69, "max_line_length": 90, "avg_line_length": 20.47826086956522, "alnum_prop": 0.6086341118188252, "repo_name": "tgalopin/expression", "id": "10dbcaa3f82d15944f1134f56f211ad7e18d9468", "size": "1657", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Comparison/EndsWith.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "187625" } ], "symlink_target": "" }
ActiveRecord::Schema.define(version: 20141112070817) do # These are extensions that must be enabled in order to support this database enable_extension "plpgsql" create_table "blockqueues", force: true do |t| t.integer "task" t.integer "user_id" t.datetime "created_at" t.datetime "updated_at" t.integer "troll_id" end add_index "blockqueues", ["troll_id"], name: "index_blockqueues_on_troll_id", using: :btree add_index "blockqueues", ["user_id"], name: "index_blockqueues_on_user_id", using: :btree create_table "delayed_jobs", force: true do |t| t.integer "priority", default: 0, null: false t.integer "attempts", default: 0, null: false t.text "handler", null: false t.text "last_error" t.datetime "run_at" t.datetime "locked_at" t.datetime "failed_at" t.string "locked_by" t.string "queue" t.datetime "created_at" t.datetime "updated_at" end add_index "delayed_jobs", ["priority", "run_at"], name: "delayed_jobs_priority", using: :btree create_table "lists", force: true do |t| t.string "name" t.string "description" t.datetime "created_at" t.datetime "updated_at" t.integer "owner_id" t.boolean "auto_add_new_blocks" t.text "block_list" end add_index "lists", ["owner_id"], name: "index_lists_on_owner_id", using: :btree create_table "lists_users", id: false, force: true do |t| t.integer "list_id", null: false t.integer "user_id", null: false end add_index "lists_users", ["list_id"], name: "index_lists_users_on_list_id", using: :btree add_index "lists_users", ["user_id"], name: "index_lists_users_on_user_id", using: :btree create_table "trolls", force: true do |t| t.string "name", default: "Unknown..." t.string "screen_name", default: "unknown" t.string "image_url", default: "https://pbs.twimg.com/profile_images/523989065352232961/ZF2MvbfP_bigger.png" t.datetime "created_at" t.datetime "updated_at" t.integer "uid", limit: 8 t.boolean "checked", default: false t.datetime "last_checked" t.boolean "suspended", default: false t.boolean "notfound", default: false end create_table "users", force: true do |t| t.string "access_token" t.string "access_secret" t.string "email" t.datetime "created_at" t.datetime "updated_at" t.string "image_url" t.string "screen_name" t.string "name" t.boolean "declined", default: false t.text "friend_list" t.integer "uid", limit: 8 t.text "block_list" t.boolean "oversized", default: false t.boolean "suspended", default: false t.boolean "notfound", default: false t.text "own_blocks" end end
{ "content_hash": "fabdd9b585e5eade9049c1aab31a8a34", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 127, "avg_line_length": 34.63529411764706, "alnum_prop": 0.6005434782608695, "repo_name": "gyardley/knowntroll", "id": "aa905e45598c3737f9396ef09b9cd1f35e4d77d4", "size": "3685", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "db/schema.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "20890" }, { "name": "JavaScript", "bytes": "14842" }, { "name": "Ruby", "bytes": "112132" } ], "symlink_target": "" }
// Copyright 2010-2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * 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. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.mozc.android.inputmethod.japanese.testing; import org.mozc.android.inputmethod.japanese.MozcLog; import org.mozc.android.inputmethod.japanese.MozcUtil; import org.mozc.android.inputmethod.japanese.stresstest.StressTest; import android.os.Build; import android.os.Bundle; import android.test.AndroidTestRunner; import android.test.InstrumentationTestRunner; import android.test.suitebuilder.TestSuiteBuilder; import dalvik.system.PathClassLoader; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Method; /** * This is basic Mozc TestRunner which runs test methods that don't have StressTest * annotation. * */ public class MozcTestRunner extends InstrumentationTestRunner { /** * This is test runner class which filter test cases. */ public static class TestRunner extends AndroidTestRunner { private static Method toMethod(TestCase testCase) { try { return testCase.getClass().getMethod(testCase.getName()); } catch (NoSuchMethodException e) { return null; } } private static boolean hasSupportedApiLevel(AnnotatedElement element) { ApiLevel apiLevelAnnotation = element.getAnnotation(ApiLevel.class); if (apiLevelAnnotation == null) { // There is no ApiLevel annotation, so all platform should support this. return true; } return Build.VERSION.SDK_INT >= apiLevelAnnotation.value(); } protected boolean filterTestMethod(Method method) { return hasSupportedApiLevel(method); } public Test filterTest(Test test) { // If the test class's ApiLevel value is larger than the environment's API Level, // skip the test. // On Dalvik VM, the class verification has not done yet (it will be done lazily) // so ClassNotFound will not be thrown even if the class contains newer API // than the runtime environment. // This mechanism is highly dependent on VM's implementation (but doesn't violate the spec) // but to simplify the code we use this. if (!hasSupportedApiLevel(test.getClass())) { return null; } if (test instanceof TestSuite) { TestSuite testSuite = TestSuite.class.cast(test); TestSuite dstSuite = new TestSuite(testSuite.getName()); for (int i = 0; i < testSuite.testCount(); i++) { Test testat = testSuite.testAt(i); Test filteredtest = filterTest(testat); if (filteredtest != null) { dstSuite.addTest(filteredtest); } } if (dstSuite.countTestCases() == 0) { return null; } return dstSuite; } if (test instanceof TestCase){ Method method = toMethod(TestCase.class.cast(test)); if (method == null || !filterTestMethod(method)) { return null; } return test; } return test; } @Override public void setTest(Test test) { super.setTest(filterTest(test)); } } private static final String ROOT_TARGET_PACKAGE = "org.mozc.android.inputmethod.japanese"; private static final String[] SUB_PACKAGE_NAME_LIST = { "accessibility", "emoji", "hardwarekeyboard", "keyboard", "model", "mushroom", "nativecallback", "preference", "session", "stresstest", "testing", "ui", "userdictionary", "util", "view", }; private static final String XML_FILE_NAME = "gtest-report.xml"; private MozcTestListener xmlListener; @Override public TestSuite getAllTests() { // NOTE: due to the dalvik VM implementation, memory allocation during code verification // would be failed on Android 2.1 (fixed at Android 2.2). // The memory allocation is stick to ClassLoader. So, as a work around, we use different // ClassLoaders for each packages heuristically, as a HACK. // TODO(hidehiko): make package management automatically. TestSuite result = new TestSuite(); ClassLoader parentLoader = getTargetContext().getClassLoader(); String apkPath = getContext().getApplicationInfo().sourceDir; String name = getClass().getName(); // Add tests in the root package. { TestSuiteBuilder builder = new TestSuiteBuilder(name, new PathClassLoader(apkPath, parentLoader)); builder.includePackages(ROOT_TARGET_PACKAGE); for (String packageName : SUB_PACKAGE_NAME_LIST) { builder.excludePackages(ROOT_TARGET_PACKAGE + "." + packageName); } result.addTest(builder.build()); } // Add tests in the sub packages. for (String packageName : SUB_PACKAGE_NAME_LIST) { TestSuiteBuilder builder = new TestSuiteBuilder(name, new PathClassLoader(apkPath, parentLoader)); builder.includePackages(ROOT_TARGET_PACKAGE + "." + packageName); result.addTest(builder.build()); } return result; } @Override protected AndroidTestRunner getAndroidTestRunner() { AndroidTestRunner runner = new TestRunner(){ @Override public boolean filterTestMethod(Method method){ return super.filterTestMethod(method) && method.getAnnotation(StressTest.class) == null; } }; runner.addTestListener(xmlListener); return runner; } @Override public void onCreate(Bundle arguments) { try { // Note that unit test runs on "target context"'s process so we cannot write anything // in /data/data/org.mozc.android.inputmethod.japanese.tests directory. File reportingXmlFile = new File(getTargetContext().getApplicationInfo().dataDir, XML_FILE_NAME); MozcLog.i("reporting XML is at " + reportingXmlFile.getAbsolutePath()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(reportingXmlFile), "UTF-8")); xmlListener = new MozcTestListener(writer, "gtest-report"); } catch (IOException e) { MozcLog.e(e.getMessage(), e); } // Invoke super.onCreate here (not the head of this method) // because super.onCreate starts unit testing internally so // after returning from it what we do will affect nothing. super.onCreate(arguments); } @Override public void finish(int resultCode, Bundle results) { if (xmlListener != null) { try { // Close the listener to make the lister close XML document correctly. MozcUtil.close(xmlListener, true); } catch (IOException e) { MozcLog.e(e.getMessage(), e); } } super.finish(resultCode, results); } }
{ "content_hash": "f48f9a1c10bd1fa20bbe3379eb8552d3", "timestamp": "", "source": "github", "line_count": 228, "max_line_length": 97, "avg_line_length": 36.5921052631579, "alnum_prop": 0.6974709337168884, "repo_name": "takahashikenichi/mozc", "id": "28f9bccf4bdc1cacaef6b8f365c37b3b9a0ced37", "size": "8343", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "src/android/tests/src/com/google/android/inputmethod/japanese/testing/MozcTestRunner.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "200335" }, { "name": "C++", "bytes": "10808666" }, { "name": "CSS", "bytes": "26088" }, { "name": "Emacs Lisp", "bytes": "80074" }, { "name": "HTML", "bytes": "266980" }, { "name": "Java", "bytes": "2751856" }, { "name": "JavaScript", "bytes": "919906" }, { "name": "Makefile", "bytes": "3754" }, { "name": "Objective-C", "bytes": "34833" }, { "name": "Objective-C++", "bytes": "227200" }, { "name": "Protocol Buffer", "bytes": "112300" }, { "name": "Python", "bytes": "1056960" }, { "name": "QMake", "bytes": "861" }, { "name": "Shell", "bytes": "9928" }, { "name": "Yacc", "bytes": "2104" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <resources> <!-- Used for accessibility to describe the button on the payment sheet list of options to add a new payment method. --> <string name="add_new_payment_method">Agregar un nuevo método de pago</string> <!-- Description of a saved bank account. E.g. 'Bank account ending in 4242' --> <string name="bank_account_ending_in">Elimina la cuenta bancaria que termina en %s</string> <!-- Text providing link to terms for ACH payments --> <string name="stripe_paymentsheet_ach_continue_mandate"><![CDATA[Al continuar, aceptas autorizar pagos conforme a <terms>estas condiciones</terms>.]]></string> <!-- Mandate text with link to terms when saving a bank account payment method to a merchant (merchant name replaces %@). --> <string name="stripe_paymentsheet_ach_save_mandate"><![CDATA[Al guardar tu cuenta bancaria para %s, aceptas autorizar pagos conforme a estas <terms>condiciones</terms>.]]></string> <!-- Text for a button that, when tapped, displays another screen where the customer can add payment method details --> <string name="stripe_paymentsheet_add_payment_method_button_label">Agregar otro</string> <!-- Title shown above a form where the customer can enter payment information like credit card details, email, billing address, etc. --> <string name="stripe_paymentsheet_add_payment_method_title">Agrega la información de pago</string> <string name="stripe_paymentsheet_close">Cerrar</string> <!-- Prompt for microdeposit verification before completing purchase with merchant. %@ will be replaced by merchant business name --> <string name="stripe_paymentsheet_microdeposit">Stripe depositará $0.01 en tu cuenta dentro de 1 o 2 días hábiles. Luego, recibirás un correo electrónico con instrucciones para completar el pago de %s.</string> <!-- Title of a section containing multiple payment methods that can selected and will collect the payment information from the user. --> <string name="stripe_paymentsheet_or_pay_using">O pagar con</string> <!-- Title of a section containing a card form that will collect the payment information from the user. --> <string name="stripe_paymentsheet_or_pay_with_card">O pagar con tarjeta</string> <!-- Label for a button that starts processing the payment. --> <string name="stripe_paymentsheet_pay_button_label">Pagar</string> <!-- Title shown above a section containing various payment options --> <string name="stripe_paymentsheet_pay_using">Pagar con</string> <!-- Label of a button that, when tapped, initiates payment, becomes disabled, and displays this text --> <string name="stripe_paymentsheet_primary_button_processing">Procesando...</string> <!-- Content for alert popup prompting to confirm removing saved payment method. --> <string name="stripe_paymentsheet_remove_pm">Elimina %s</string> <!-- The label of a switch indicating whether to save the payment method for future payments. --> <string name="stripe_paymentsheet_save_for_future_payments">Guardar para futuros pagos</string> <!-- The label of a switch indicating whether to save the user&apos;s card for future payments to this merchant --> <string name="stripe_paymentsheet_save_this_card_with_merchant_name">Guardar esta tarjeta para futuros pagos de %s</string> <!-- Title shown above a carousel containing the customer&apos;s payment methods --> <string name="stripe_paymentsheet_select_payment_method">Selecciona el método de pago</string> <!-- Label indicating the total amount that the user is authorizing (e.g. "Total: $25.00") --> <string name="stripe_paymentsheet_total_amount">Total: %s</string> </resources>
{ "content_hash": "c4fd1f1d92718876befdbbc82428cf5e", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 212, "avg_line_length": 96.21052631578948, "alnum_prop": 0.7489059080962801, "repo_name": "stripe/stripe-android", "id": "37394dbc8aa33f6bf02779773ae16290a1770f45", "size": "3664", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "paymentsheet/res/values-b+es+419/strings.xml", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "67407" }, { "name": "Kotlin", "bytes": "7720826" }, { "name": "Python", "bytes": "13146" }, { "name": "Ruby", "bytes": "5171" }, { "name": "Shell", "bytes": "18256" } ], "symlink_target": "" }
<!DOCTYPE html> <html ng-app='WillowWay'> <head> <meta charset='utf-8'> <script src='/vendor/angular/angular.min.js'></script> <script src='/vendor/angular/angular-route.min.js'></script> <script src='/vendor/clipboard/clipboard.min.js'></script> <script src='/vendor/hsimp/hsimp.min.js'></script> <script src='/assets/scripts/client.min.js'></script> <link rel="stylesheet" href="/assets/styles/stylesheet.css"> <link rel="stylesheet" href="vendor/bootstrap/bootstrap.min.css"> <link rel="stylesheet" href="/assets/styles/hsimp.css"> <title>WillowWayPoint</title> <base href='/'> </head> <body class='body'> <nav class="navbar navbar-inverse navbar-static-top"> <div class="container"> <div class='navbar-header'> </div> </div> </nav> <div class='container'> <div class='jumbotron' style='background: #9FBCBF; border: solid 1px grey;' ng-controller='PasswordController as password'> <h1 class='text-center'>Generate Password</h1> <div class='passwordBox text-center'> {{ password.genPassword }} </div> <div class='passwordButton text-center'> <button ng-click='password.getPassword()'>Get Password</button> <button class='passwordCopy' data-clipboard-action="copy" data-clipboard-target=".passwordBox">Copy Password</button> </div> </div> <script> var clipboard = new Clipboard('.passwordCopy'); clipboard.on('success', function(e) { console.log(e); }); clipboard.on('error', function(e) { console.log(e); }); </script> </div> <div class='container'> <nav class='navbar navbar-default' style='background: #9FBCBF; border: solid 1px grey;'> <div> <ul class='nav navbar-nav'> <li> <a href='/home'>Home</a> </li> <li> <a href='/security'>Security Tips</a> </li> <li> <a href='/strength'>Password Strength</a> </li> <li> <a href='/saved'>Saved Passwords</a> </li> </ul> </div> <div class='container-fluid'> <div class='navbar-header navbar-right' ng-controller="RightNavController as rightNav"> <ul class='nav navbar-nav'> <li> <a href='/register'>Register</a> </li> <li> <a href='/login' ng-show"rightNav.!isLoggedIn">Login</a> </li> <li> <a href='/login/logout' ng-click="rightNav.send()" ng-show"rightNav.isLoggedIn">Logout</a> </li> </ul> </div> </div> </nav> </div> <div class='container'> <div class='well' style='background: #9FBCBF; border: solid 1px grey;'> <div class='container' ng-view> </div> <br> </div> </div> <footer class='footer navbar-inverse'> <div class='container'> <ul class='nav navbar-nav'> <li> <a href='/'>Home</a> </li> <li> <a href='/about'>About</a> </li> <li> <a href='https://twitter.com/td_ingram'>Contact</a> </li> </div> </footer> </body> </html>
{ "content_hash": "5431bc75fd7ae9719e87bca7e33bb756", "timestamp": "", "source": "github", "line_count": 105, "max_line_length": 127, "avg_line_length": 29.99047619047619, "alnum_prop": 0.5646236900603366, "repo_name": "TravisIngram/WillowWayPoint", "id": "0e8869cabeb602630debfcfe16fc53e03a060767", "size": "3149", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "server/public/views/index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "566" }, { "name": "HTML", "bytes": "5632" }, { "name": "JavaScript", "bytes": "10829" } ], "symlink_target": "" }
<?php namespace Heyday\Beam\DeploymentProvider; /** * Generated by PHPUnit_SkeletonGenerator 1.2.0 on 2013-05-15 at 11:01:03. */ class DeploymentTest extends \PHPUnit_Framework_TestCase { /** * @var Deployment */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { // $this->object = new Deployment; } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @covers Heyday\Beam\DeploymentProvider\Deployment::setBeam * @todo Implement testSetBeam(). */ public function testSetBeam() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } }
{ "content_hash": "3f5b8c2f49448474a3f2ed35e93b5686", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 74, "avg_line_length": 24, "alnum_prop": 0.6190476190476191, "repo_name": "stevie-mayhew/beam", "id": "43dcdb8483a49bce5a1f0aeffd5883c7d7ff92c2", "size": "1008", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Heyday/Beam/DeploymentProvider/DeploymentTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "253769" } ], "symlink_target": "" }
namespace kj { // ======================================================================================= TopLevelProcessContext::TopLevelProcessContext(StringPtr programName) : programName(programName), cleanShutdown(getenv("KJ_CLEAN_SHUTDOWN") != nullptr) {} StringPtr TopLevelProcessContext::getProgramName() { return programName; } void TopLevelProcessContext::exit() { int exitCode = hadErrors ? 1 : 0; if (cleanShutdown) { #if KJ_NO_EXCEPTIONS // This is the best we can do. warning("warning: KJ_CLEAN_SHUTDOWN may not work correctly when compiled " "with -fno-exceptions."); ::exit(exitCode); #else throw CleanShutdownException { exitCode }; #endif } _Exit(exitCode); } static void writeLineToFd(int fd, StringPtr message) { // Write the given message to the given file descriptor with a trailing newline iff the message // is non-empty and doesn't already have a trailing newline. We use writev() to do this in a // single system call without any copying. if (message.size() == 0) { return; } // Unfortunately the writev interface requires non-const pointers even though it won't modify // the data. struct iovec vec[2]; vec[0].iov_base = const_cast<char*>(message.begin()); vec[0].iov_len = message.size(); vec[1].iov_base = const_cast<char*>("\n"); vec[1].iov_len = 1; struct iovec* pos = vec; // Only use the second item in the vec if the message doesn't already end with \n. uint count = message.endsWith("\n") ? 1 : 2; for (;;) { ssize_t n = writev(fd, pos, count); if (n < 0) { if (errno == EINTR) { continue; } else { // This function is meant for writing to stdout and stderr. If writes fail on those FDs // there's not a whole lot we can reasonably do, so just ignore it. return; } } // Update chunks to discard what was successfully written. for (;;) { if (count == 0) { // Done writing. return; } else if (pos->iov_len <= implicitCast<size_t>(n)) { // Wrote this entire chunk. n -= pos->iov_len; ++pos; --count; } else { // Wrote only part of this chunk. Adjust the pointer and then retry. pos->iov_base = reinterpret_cast<byte*>(pos->iov_base) + n; pos->iov_len -= n; break; } } } } void TopLevelProcessContext::warning(StringPtr message) { writeLineToFd(STDERR_FILENO, message); } void TopLevelProcessContext::error(StringPtr message) { hadErrors = true; writeLineToFd(STDERR_FILENO, message); } void TopLevelProcessContext::exitError(StringPtr message) { error(message); exit(); } void TopLevelProcessContext::exitInfo(StringPtr message) { writeLineToFd(STDOUT_FILENO, message); exit(); } void TopLevelProcessContext::increaseLoggingVerbosity() { // At the moment, there is only one log level that isn't enabled by default. _::Debug::setLogLevel(_::Debug::Severity::INFO); } // ======================================================================================= int runMainAndExit(ProcessContext& context, MainFunc&& func, int argc, char* argv[]) { #if !KJ_NO_EXCEPTIONS try { #endif KJ_ASSERT(argc > 0); KJ_STACK_ARRAY(StringPtr, params, argc - 1, 8, 32); for (int i = 1; i < argc; i++) { params[i - 1] = argv[i]; } KJ_IF_MAYBE(exception, runCatchingExceptions([&]() { func(argv[0], params); })) { context.error(str("*** Uncaught exception ***\n", *exception)); } context.exit(); #if !KJ_NO_EXCEPTIONS } catch (const TopLevelProcessContext::CleanShutdownException& e) { return e.exitCode; } #endif KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT } // ======================================================================================= struct MainBuilder::Impl { inline Impl(ProcessContext& context, StringPtr version, StringPtr briefDescription, StringPtr extendedDescription) : context(context), version(version), briefDescription(briefDescription), extendedDescription(extendedDescription) {} ProcessContext& context; StringPtr version; StringPtr briefDescription; StringPtr extendedDescription; Arena arena; struct CharArrayCompare { inline bool operator()(const ArrayPtr<const char>& a, const ArrayPtr<const char>& b) const { int cmp = memcmp(a.begin(), b.begin(), min(a.size(), b.size())); if (cmp == 0) { return a.size() < b.size(); } else { return cmp < 0; } } }; struct Option { ArrayPtr<OptionName> names; bool hasArg; union { Function<Validity()>* func; Function<Validity(StringPtr)>* funcWithArg; }; StringPtr argTitle; StringPtr helpText; }; class OptionDisplayOrder; std::map<char, Option*> shortOptions; std::map<ArrayPtr<const char>, Option*, CharArrayCompare> longOptions; struct SubCommand { Function<MainFunc()> func; StringPtr helpText; }; std::map<StringPtr, SubCommand> subCommands; struct Arg { StringPtr title; Function<Validity(StringPtr)> callback; uint minCount; uint maxCount; }; Vector<Arg> args; Maybe<Function<Validity()>> finalCallback; Option& addOption(std::initializer_list<OptionName> names, bool hasArg, StringPtr helpText) { KJ_REQUIRE(names.size() > 0, "option must have at least one name"); Option& option = arena.allocate<Option>(); option.names = arena.allocateArray<OptionName>(names.size()); uint i = 0; for (auto& name: names) { option.names[i++] = name; if (name.isLong) { KJ_REQUIRE( longOptions.insert(std::make_pair(StringPtr(name.longName).asArray(), &option)).second, "duplicate option", name.longName); } else { KJ_REQUIRE( shortOptions.insert(std::make_pair(name.shortName, &option)).second, "duplicate option", name.shortName); } } option.hasArg = hasArg; option.helpText = helpText; return option; } Validity printVersion() { context.exitInfo(version); return true; } Validity increaseVerbosity() { context.increaseLoggingVerbosity(); return true; } }; MainBuilder::MainBuilder(ProcessContext& context, StringPtr version, StringPtr briefDescription, StringPtr extendedDescription) : impl(heap<Impl>(context, version, briefDescription, extendedDescription)) { addOption({"verbose"}, KJ_BIND_METHOD(*impl, increaseVerbosity), "Log informational messages to stderr; useful for debugging."); addOption({"version"}, KJ_BIND_METHOD(*impl, printVersion), "Print version information and exit."); } MainBuilder::~MainBuilder() noexcept(false) {} MainBuilder& MainBuilder::addOption(std::initializer_list<OptionName> names, Function<Validity()> callback, StringPtr helpText) { impl->addOption(names, false, helpText).func = &impl->arena.copy(kj::mv(callback)); return *this; } MainBuilder& MainBuilder::addOptionWithArg(std::initializer_list<OptionName> names, Function<Validity(StringPtr)> callback, StringPtr argumentTitle, StringPtr helpText) { auto& opt = impl->addOption(names, true, helpText); opt.funcWithArg = &impl->arena.copy(kj::mv(callback)); opt.argTitle = argumentTitle; return *this; } MainBuilder& MainBuilder::addSubCommand(StringPtr name, Function<MainFunc()> getSubParser, StringPtr helpText) { KJ_REQUIRE(impl->args.size() == 0, "cannot have sub-commands when expecting arguments"); KJ_REQUIRE(impl->finalCallback == nullptr, "cannot have a final callback when accepting sub-commands"); KJ_REQUIRE( impl->subCommands.insert(std::make_pair( name, Impl::SubCommand { kj::mv(getSubParser), helpText })).second, "duplicate sub-command", name); return *this; } MainBuilder& MainBuilder::expectArg(StringPtr title, Function<Validity(StringPtr)> callback) { KJ_REQUIRE(impl->subCommands.empty(), "cannot have sub-commands when expecting arguments"); impl->args.add(Impl::Arg { title, kj::mv(callback), 1, 1 }); return *this; } MainBuilder& MainBuilder::expectOptionalArg( StringPtr title, Function<Validity(StringPtr)> callback) { KJ_REQUIRE(impl->subCommands.empty(), "cannot have sub-commands when expecting arguments"); impl->args.add(Impl::Arg { title, kj::mv(callback), 0, 1 }); return *this; } MainBuilder& MainBuilder::expectZeroOrMoreArgs( StringPtr title, Function<Validity(StringPtr)> callback) { KJ_REQUIRE(impl->subCommands.empty(), "cannot have sub-commands when expecting arguments"); impl->args.add(Impl::Arg { title, kj::mv(callback), 0, UINT_MAX }); return *this; } MainBuilder& MainBuilder::expectOneOrMoreArgs( StringPtr title, Function<Validity(StringPtr)> callback) { KJ_REQUIRE(impl->subCommands.empty(), "cannot have sub-commands when expecting arguments"); impl->args.add(Impl::Arg { title, kj::mv(callback), 1, UINT_MAX }); return *this; } MainBuilder& MainBuilder::callAfterParsing(Function<Validity()> callback) { KJ_REQUIRE(impl->finalCallback == nullptr, "callAfterParsing() can only be called once"); KJ_REQUIRE(impl->subCommands.empty(), "cannot have a final callback when accepting sub-commands"); impl->finalCallback = kj::mv(callback); return *this; } class MainBuilder::MainImpl { public: MainImpl(Own<Impl>&& impl): impl(kj::mv(impl)) {} void operator()(StringPtr programName, ArrayPtr<const StringPtr> params); private: Own<Impl> impl; void usageError(StringPtr programName, StringPtr message) KJ_NORETURN; void printHelp(StringPtr programName) KJ_NORETURN; void wrapText(Vector<char>& output, StringPtr indent, StringPtr text); }; MainFunc MainBuilder::build() { return MainImpl(kj::mv(impl)); } void MainBuilder::MainImpl::operator()(StringPtr programName, ArrayPtr<const StringPtr> params) { Vector<StringPtr> arguments; for (size_t i = 0; i < params.size(); i++) { StringPtr param = params[i]; if (param == "--") { // "--" ends option parsing. arguments.addAll(params.begin() + i + 1, params.end()); break; } else if (param.startsWith("--")) { // Long option. ArrayPtr<const char> name; Maybe<StringPtr> maybeArg; KJ_IF_MAYBE(pos, param.findFirst('=')) { name = param.slice(2, *pos); maybeArg = param.slice(*pos + 1); } else { name = param.slice(2); } auto iter = impl->longOptions.find(name); if (iter == impl->longOptions.end()) { if (param == "--help") { printHelp(programName); } else { usageError(programName, str("--", name, ": unrecognized option")); } } else { const Impl::Option& option = *iter->second; if (option.hasArg) { // Argument expected. KJ_IF_MAYBE(arg, maybeArg) { // "--foo=blah": "blah" is the argument. KJ_IF_MAYBE(error, (*option.funcWithArg)(*arg).releaseError()) { usageError(programName, str(param, ": ", *error)); } } else if (i + 1 < params.size() && !params[i + 1].startsWith("-")) { // "--foo blah": "blah" is the argument. ++i; KJ_IF_MAYBE(error, (*option.funcWithArg)(params[i]).releaseError()) { usageError(programName, str(param, "=", params[i], ": ", *error)); } } else { usageError(programName, str("--", name, ": missing argument")); } } else { // No argument expected. if (maybeArg == nullptr) { KJ_IF_MAYBE(error, (*option.func)().releaseError()) { usageError(programName, str(param, ": ", *error)); } } else { usageError(programName, str("--", name, ": option does not accept an argument")); } } } } else if (param.startsWith("-")) { // Short option(s). for (uint j = 1; j < param.size(); j++) { char c = param[j]; auto iter = impl->shortOptions.find(c); if (iter == impl->shortOptions.end()) { usageError(programName, str("-", c, ": unrecognized option")); } else { const Impl::Option& option = *iter->second; if (option.hasArg) { // Argument expected. if (j + 1 < param.size()) { // Rest of flag is argument. StringPtr arg = param.slice(j + 1); KJ_IF_MAYBE(error, (*option.funcWithArg)(arg).releaseError()) { usageError(programName, str("-", c, " ", arg, ": ", *error)); } break; } else if (i + 1 < params.size() && !params[i + 1].startsWith("-")) { // Next parameter is argument. ++i; KJ_IF_MAYBE(error, (*option.funcWithArg)(params[i]).releaseError()) { usageError(programName, str("-", c, " ", params[i], ": ", *error)); } break; } else { usageError(programName, str("-", c, ": missing argument")); } } else { // No argument expected. KJ_IF_MAYBE(error, (*option.func)().releaseError()) { usageError(programName, str("-", c, ": ", *error)); } } } } } else if (!impl->subCommands.empty()) { // A sub-command name. auto iter = impl->subCommands.find(param); if (iter != impl->subCommands.end()) { MainFunc subMain = iter->second.func(); subMain(str(programName, ' ', param), params.slice(i + 1, params.size())); return; } else if (param == "help") { if (i + 1 < params.size()) { iter = impl->subCommands.find(params[i + 1]); if (iter != impl->subCommands.end()) { // Run the sub-command with "--help" as the argument. MainFunc subMain = iter->second.func(); StringPtr dummyArg = "--help"; subMain(str(programName, ' ', params[i + 1]), arrayPtr(&dummyArg, 1)); return; } else if (params[i + 1] == "help") { impl->context.exitInfo("Help, I'm trapped in a help text factory!"); } else { usageError(programName, str(params[i + 1], ": unknown command")); } } else { printHelp(programName); } } else { // Arguments are not accepted, so this is an error. usageError(programName, str(param, ": unknown command")); } } else { // Just a regular argument. arguments.add(param); } } // ------------------------------------ // Handle arguments. // ------------------------------------ if (!impl->subCommands.empty()) { usageError(programName, "missing command"); } // Count the number of required arguments, so that we know how to distribute the optional args. uint requiredArgCount = 0; for (auto& argSpec: impl->args) { requiredArgCount += argSpec.minCount; } // Now go through each argument spec and consume arguments with it. StringPtr* argPos = arguments.begin(); for (auto& argSpec: impl->args) { uint i = 0; for (; i < argSpec.minCount; i++) { if (argPos == arguments.end()) { usageError(programName, str("missing argument ", argSpec.title)); } else { KJ_IF_MAYBE(error, argSpec.callback(*argPos).releaseError()) { usageError(programName, str(*argPos, ": ", *error)); } ++argPos; --requiredArgCount; } } // If we have more arguments than we need, and this argument spec will accept extras, give // them to it. for (; i < argSpec.maxCount && arguments.end() - argPos > requiredArgCount; ++i) { KJ_IF_MAYBE(error, argSpec.callback(*argPos).releaseError()) { usageError(programName, str(*argPos, ": ", *error)); } ++argPos; } } // Did we consume all the arguments? while (argPos < arguments.end()) { usageError(programName, str(*argPos++, ": too many arguments")); } // Run the final callback, if any. KJ_IF_MAYBE(f, impl->finalCallback) { KJ_IF_MAYBE(error, (*f)().releaseError()) { usageError(programName, *error); } } } void MainBuilder::MainImpl::usageError(StringPtr programName, StringPtr message) { impl->context.exitError(kj::str( programName, ": ", message, "\nTry '", programName, " --help' for more information.")); KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT } class MainBuilder::Impl::OptionDisplayOrder { public: bool operator()(const Option* a, const Option* b) { if (a == b) return false; char aShort = '\0'; char bShort = '\0'; for (auto& name: a->names) { if (name.isLong) { if (aShort == '\0') { aShort = name.longName[0]; } } else { aShort = name.shortName; break; } } for (auto& name: b->names) { if (name.isLong) { if (bShort == '\0') { bShort = name.longName[0]; } } else { bShort = name.shortName; break; } } if (aShort < bShort) return true; if (aShort > bShort) return false; StringPtr aLong; StringPtr bLong; for (auto& name: a->names) { if (name.isLong) { aLong = name.longName; break; } } for (auto& name: b->names) { if (name.isLong) { bLong = name.longName; break; } } return aLong < bLong; } }; void MainBuilder::MainImpl::printHelp(StringPtr programName) { Vector<char> text(1024); std::set<const Impl::Option*, Impl::OptionDisplayOrder> sortedOptions; for (auto& entry: impl->shortOptions) { sortedOptions.insert(entry.second); } for (auto& entry: impl->longOptions) { sortedOptions.insert(entry.second); } text.addAll(str("Usage: ", programName, sortedOptions.empty() ? "" : " [<option>...]")); if (impl->subCommands.empty()) { for (auto& arg: impl->args) { text.add(' '); if (arg.minCount == 0) { text.addAll(str("[", arg.title, arg.maxCount > 1 ? "...]" : "]")); } else { text.addAll(str(arg.title, arg.maxCount > 1 ? "..." : "")); } } } else { text.addAll(StringPtr(" <command> [<arg>...]")); } text.addAll(StringPtr("\n\n")); wrapText(text, "", impl->briefDescription); if (!impl->subCommands.empty()) { text.addAll(StringPtr("\nCommands:\n")); size_t maxLen = 0; for (auto& command: impl->subCommands) { maxLen = kj::max(maxLen, command.first.size()); } for (auto& command: impl->subCommands) { text.addAll(StringPtr(" ")); text.addAll(command.first); for (size_t i = command.first.size(); i < maxLen; i++) { text.add(' '); } text.addAll(StringPtr(" ")); text.addAll(command.second.helpText); text.add('\n'); } text.addAll(str( "\nSee '", programName, " help <command>' for more information on a specific command.\n")); } if (!sortedOptions.empty()) { text.addAll(StringPtr("\nOptions:\n")); for (auto opt: sortedOptions) { text.addAll(StringPtr(" ")); bool isFirst = true; for (auto& name: opt->names) { if (isFirst) { isFirst = false; } else { text.addAll(StringPtr(", ")); } if (name.isLong) { text.addAll(str("--", name.longName)); if (opt->hasArg) { text.addAll(str("=", opt->argTitle)); } } else { text.addAll(str("-", name.shortName)); if (opt->hasArg) { text.addAll(opt->argTitle); } } } text.add('\n'); wrapText(text, " ", opt->helpText); } text.addAll(StringPtr(" --help\n Display this help text and exit.\n")); } if (impl->extendedDescription.size() > 0) { text.add('\n'); wrapText(text, "", impl->extendedDescription); } text.add('\0'); impl->context.exitInfo(String(text.releaseAsArray())); KJ_CLANG_KNOWS_THIS_IS_UNREACHABLE_BUT_GCC_DOESNT } void MainBuilder::MainImpl::wrapText(Vector<char>& output, StringPtr indent, StringPtr text) { uint width = 80 - indent.size(); while (text.size() > 0) { output.addAll(indent); KJ_IF_MAYBE(lineEnd, text.findFirst('\n')) { if (*lineEnd <= width) { output.addAll(text.slice(0, *lineEnd + 1)); text = text.slice(*lineEnd + 1); continue; } } if (text.size() <= width) { output.addAll(text); output.add('\n'); break; } uint wrapPos = width; for (;; wrapPos--) { if (wrapPos == 0) { // Hmm, no good place to break words. Just break in the middle. wrapPos = width; break; } else if (text[wrapPos] == ' ' && text[wrapPos - 1] != ' ') { // This position is a space and is preceded by a non-space. Wrap here. break; } } output.addAll(text.slice(0, wrapPos)); output.add('\n'); // Skip spaces after the text that was printed. while (text[wrapPos] == ' ') { ++wrapPos; } if (text[wrapPos] == '\n') { // Huh, apparently there were a whole bunch of spaces at the end of the line followed by a // newline. Skip the newline as well so we don't print a blank line. ++wrapPos; } text = text.slice(wrapPos); } } } // namespace kj
{ "content_hash": "e308d4f0e76b0f5dc9d2f55801e4f9cf", "timestamp": "", "source": "github", "line_count": 690, "max_line_length": 100, "avg_line_length": 31.48840579710145, "alnum_prop": 0.5806139826022921, "repo_name": "191919/capnproto", "id": "20aa02a0112ba3ee800288a0cf8c6072299f6b2e", "size": "23297", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "c++/src/kj/main.c++", "mode": "33188", "license": "bsd-2-clause", "language": [], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DNK.PriceListImport.AlaskaLoader { public class Room { private string name; public string Name { get { return name; } } private Dictionary<int, decimal> prices; public Dictionary<int, decimal> Prices { get { return prices; } } public Room(string name) { if (!string.IsNullOrEmpty(name)) { this.name = name; prices = new Dictionary<int, decimal>(); } } public void AddPrice(int key, string value) { if (prices != null) { if (!prices.ContainsKey(key)) { decimal price; if (decimal.TryParse(value, out price)) { prices.Add(key, price); } } } } } }
{ "content_hash": "8adfb74a96475826191984503ea6a3b7", "timestamp": "", "source": "github", "line_count": 38, "max_line_length": 73, "avg_line_length": 26.86842105263158, "alnum_prop": 0.4789422135161606, "repo_name": "sdimons/Danko2015", "id": "fef2a065ffdccd6bd7aa065a67c0ff22efe1438a", "size": "1023", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "DNK.PriceListImport.AlaskaLoader/Room.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "92615" }, { "name": "C#", "bytes": "1374188" }, { "name": "CSS", "bytes": "779" }, { "name": "HTML", "bytes": "42921" }, { "name": "JavaScript", "bytes": "26446" }, { "name": "PLpgSQL", "bytes": "1757" }, { "name": "SQLPL", "bytes": "1604" } ], "symlink_target": "" }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; class ChartsController extends Controller { public function charts(){ return View('charts.chart'); } }
{ "content_hash": "3bc0968d100cd6d9fbb50b79d33a4594", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 41, "avg_line_length": 15.214285714285714, "alnum_prop": 0.7089201877934272, "repo_name": "oasis1992/reto-emprendedor-hackaton-laravel", "id": "a5c3f670bd5da119a5d28af585866fda8708638f", "size": "213", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/Http/Controllers/ChartsController.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "553" }, { "name": "HTML", "bytes": "39791" }, { "name": "JavaScript", "bytes": "439482" }, { "name": "PHP", "bytes": "101826" } ], "symlink_target": "" }
<?php class Google_Service_DeploymentManager_ManifestsListResponse extends Google_Collection { protected $collection_key = 'manifests'; protected $manifestsType = 'Google_Service_DeploymentManager_Manifest'; protected $manifestsDataType = 'array'; public $nextPageToken; /** * @param Google_Service_DeploymentManager_Manifest[] */ public function setManifests($manifests) { $this->manifests = $manifests; } /** * @return Google_Service_DeploymentManager_Manifest[] */ public function getManifests() { return $this->manifests; } public function setNextPageToken($nextPageToken) { $this->nextPageToken = $nextPageToken; } public function getNextPageToken() { return $this->nextPageToken; } }
{ "content_hash": "bf77ba62410d4b73f4ea48653f4d975e", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 86, "avg_line_length": 22.939393939393938, "alnum_prop": 0.7107001321003963, "repo_name": "bshaffer/google-api-php-client-services", "id": "39744063b3d57a86e4c84e0910d5c8d8bcefccd9", "size": "1347", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Google/Service/DeploymentManager/ManifestsListResponse.php", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "PHP", "bytes": "9540154" } ], "symlink_target": "" }
using System; using System.Linq; using SharpTools.Collections; namespace SharpTools.Diagnostics.Logging { public class InMemoryLogger : ILogger { // Max 10mb used for storing the in memory logs private const int MAX_MEMORY_USAGE = 10*1024*1024; // An array of all the log levels for easy use private static readonly LogLevel[] LEVELS = Enum.GetValues(typeof (LogLevel)) as LogLevel[]; private readonly RingBuffer<string> _log; private LogLevel _level; public InMemoryLogger(LogLevel logLevel = LogLevel.All) { _level = logLevel; _log = new RingBuffer<string>(MAX_MEMORY_USAGE); } public IQueryable<string> Logs { get { return _log.AsQueryable(); } } public bool IsEnabled(LogLevel level) { return ((int) level) >= ((int) _level); } public void SetLogLevel(LogLevel level) { _level = level; } public void EnableLogLevel(LogLevel level) { if (_level.HasFlag(LogLevel.Disabled)) { _level = level; } else if (!_level.HasFlag(level)) { _level = _level | level; } } public void DisableLogLevel(LogLevel level) { if (_level.HasFlag(LogLevel.Disabled)) { _level = LogLevel.All; } else { _level = LEVELS .Where(l => _level.HasFlag(l) && !level.HasFlag(l)) .Aggregate((a, b) => a | b); } } public void Log(LogLevel level, object message) { var timestamp = DateTime.UtcNow.ToString("s"); var levelName = Enum.GetName(typeof (LogLevel), level); _log.Append(string.Format("{0} {1} {2}", timestamp, levelName, message)); } public void Log(LogLevel level, object message, Exception exception) { var timestamp = DateTime.UtcNow.ToString("s"); var levelName = Enum.GetName(typeof (LogLevel), level); var exTypeName = exception.GetType().Name; var exMessage = exception.Message; _log.Append(string.Format("{0} {1} {2} - {3}:{4}", timestamp, levelName, message, exTypeName, exMessage)); } public void Log(LogLevel level, string format, params object[] args) { var timestamp = DateTime.UtcNow.ToString("s"); var levelName = Enum.GetName(typeof (LogLevel), level); _log.Append(string.Format("{0} {1} {2}", timestamp, levelName, string.Format(format, args))); } public void Log(LogLevel level, IFormatProvider provider, string format, params object[] args) { var timestamp = DateTime.UtcNow.ToString("s"); var levelName = Enum.GetName(typeof (LogLevel), level); var formatted = string.Format(provider, format, args); _log.Append(string.Format("{0} {1} {2}", timestamp, levelName, formatted)); } } }
{ "content_hash": "5e543cd3744d8d7e760c5b99e8e3b2d0", "timestamp": "", "source": "github", "line_count": 95, "max_line_length": 119, "avg_line_length": 33.54736842105263, "alnum_prop": 0.5428302478820207, "repo_name": "bitwalker/SharpTools", "id": "34ebb46be1f5230a500b93ff146f08549373a801", "size": "3189", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "SharpTools/Diagnostics/Logging/InMemoryLogger.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "160859" }, { "name": "PowerShell", "bytes": "37268" }, { "name": "Shell", "bytes": "112" } ], "symlink_target": "" }
<section class="player-bar" ng-controller="PlayerBarCtrl as playerBar"> <div class="container"> <div class="control-group main-controls"> <a class="previous" ng-click="playerBar.songPlayer.previous()"> <span class="ion-skip-backward"></span> </a> <a class="play-pause"> <span class="ion-play" ng-show="!playerBar.songPlayer.currentSong.playing" ng-click="playerBar.songPlayer.play()"> </span> <span class="ion-pause" ng-show="playerBar.songPlayer.currentSong.playing" ng-click="playerBar.songPlayer.pause()"> </span> </a> <a class="next"> <span class="ion-skip-forward"></span> </a> </div> <div class="control-group currently-playing"> <h2 class="song-name"></h2> <h2 class="artist-song-mobile"></h2> <h3 class="artist-name"></h3> <div class="seek-control"> <seek-bar></seek-bar> <!-- <div class="seek-bar"> <div class="fill"></div> <div class="thumb"></div> </div>--> <div class="current-time"></div> <div class="total-time"></div> </div> </div> <div class="control-group volume"> <span class="icon ion-volume-high"></span> <div class="seek-bar"> <div class="fill"></div> <div class="thumb"></div> </div> </div> </div> </section>
{ "content_hash": "1559566f1de63c3f3fec0ba929c5d8fd", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 75, "avg_line_length": 39, "alnum_prop": 0.4609421586165772, "repo_name": "teckjon/bloc-jams-angular", "id": "e9dfbb819ccd6a9d6e979d742f741d02653ff7b2", "size": "1677", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "app/templates/player_bar.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "10177" }, { "name": "HTML", "bytes": "8014" }, { "name": "JavaScript", "bytes": "13282" } ], "symlink_target": "" }
import { generateUtilityClass, generateUtilityClasses } from '@mui/base'; export interface SwitchBaseClasses { root: string; checked: string; disabled: string; input: string; edgeStart: string; edgeEnd: string; } export type SwitchBaseClassKey = keyof SwitchBaseClasses; export function getSwitchBaseUtilityClass(slot: string): string { return generateUtilityClass('PrivateSwitchBase', slot); } const switchBaseClasses: SwitchBaseClasses = generateUtilityClasses('PrivateSwitchBase', [ 'root', 'checked', 'disabled', 'input', 'edgeStart', 'edgeEnd', ]); export default switchBaseClasses;
{ "content_hash": "6df7e405d09ccada13ee0fb541960100", "timestamp": "", "source": "github", "line_count": 27, "max_line_length": 90, "avg_line_length": 22.925925925925927, "alnum_prop": 0.7544426494345718, "repo_name": "rscnt/material-ui", "id": "5b667461486dfaef8701f4c79d9f3af43c4fc7ac", "size": "619", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "packages/mui-material/src/internal/switchBaseClasses.ts", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "2126" }, { "name": "JavaScript", "bytes": "3967457" }, { "name": "TypeScript", "bytes": "2468380" } ], "symlink_target": "" }
<?php namespace JasonRoman\NbaApi\Request\Stats\Stats\Homepage; use JasonRoman\NbaApi\Constraints as ApiAssert; use JasonRoman\NbaApi\Params\LeagueIdParam; use JasonRoman\NbaApi\Params\SeasonParam; use JasonRoman\NbaApi\Params\Stats\GameScopeParam; use JasonRoman\NbaApi\Params\Stats\PlayerOrTeamParam; use JasonRoman\NbaApi\Params\Stats\PlayerScopeParam; use JasonRoman\NbaApi\Params\Stats\SeasonTypeParam; use JasonRoman\NbaApi\Params\Stats\StatCategoryParam; use JasonRoman\NbaApi\Request\Stats\Stats\AbstractStatsStatsRequest; use Symfony\Component\Validator\Constraints as Assert; class HomepageLeadersRequest extends AbstractStatsStatsRequest { const ENDPOINT = '/stats/homepageleaders'; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiRegex(LeagueIdParam::FORMAT) * * @var string */ public $leagueId; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiRegex(SeasonParam::FORMAT) * * @var string */ public $season; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiChoice(SeasonTypeParam::OPTIONS) * * @var string */ public $seasonType; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiChoice(StatCategoryParam::OPTIONS) * * @var string */ public $statCategory; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiChoice(PlayerOrTeamParam::OPTIONS) * * @var string */ public $playerOrTeam; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiChoice(GameScopeParam::OPTIONS) * * @var string */ public $gameScope; /** * @Assert\NotBlank() * @Assert\Type("string") * @ApiAssert\ApiChoice(PlayerScopeParam::OPTIONS) * * @var string */ public $playerScope; }
{ "content_hash": "22f0391fb974fa456d514ac44da00558", "timestamp": "", "source": "github", "line_count": 82, "max_line_length": 68, "avg_line_length": 23.573170731707318, "alnum_prop": 0.6487325400931195, "repo_name": "jasonroman/nba-api", "id": "3ce87f213c6fba674e66cb9d8d829e49781bdfb0", "size": "1933", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/Request/Stats/Stats/Homepage/HomepageLeadersRequest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "731136" } ], "symlink_target": "" }
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('banish', '0002_auto_20170826_1311'), ] operations = [ migrations.AlterModelOptions( name='banishment', options={'permissions': (('can_ban_user', 'Can Ban User'),), 'verbose_name': 'Banishment Blacklist', 'verbose_name_plural': 'Banishments Blacklist'}, ), migrations.AlterModelOptions( name='whitelist', options={'permissions': (('can_whitelist_user', 'Can Whitelist User'),), 'verbose_name': 'Banishment Whitelist', 'verbose_name_plural': 'Banishments Whitelist'}, ), ]
{ "content_hash": "cf740e7ae5fc6fbab06090bfbeece5f0", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 173, "avg_line_length": 33.857142857142854, "alnum_prop": 0.6230661040787623, "repo_name": "intelligenia/django-banish-plus", "id": "0bba58573f5641da011566006548d26fe5e35ce4", "size": "782", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "banish/migrations/0003_auto_20171019_1600.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "19543" } ], "symlink_target": "" }
using System.Collections.Generic; namespace Kentico.Kontent.Delivery.Abstractions { /// <summary> /// Represents a response from Kentico Kontent Delivery API that contains a content item. /// </summary> /// <typeparam name="T">The type of a content item in the response.</typeparam> public interface IDeliveryItemResponse<out T> : IResponse { /// <summary> /// Gets the content item. /// </summary> T Item { get; } } }
{ "content_hash": "604ad46bcb2edcac0a993d278fa9452e", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 93, "avg_line_length": 30, "alnum_prop": 0.6333333333333333, "repo_name": "Kentico/Deliver-.NET-SDK", "id": "b3b3042a052cb3061f607e203f0980134b9a439e", "size": "482", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Kentico.Kontent.Delivery.Abstractions/ContentItems/IDeliveryItemResponse.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "47130" } ], "symlink_target": "" }
from tempest.api.compute import base from tempest import test class ServerMetadataV3Test(base.BaseV3ComputeTest): @classmethod def setUpClass(cls): super(ServerMetadataV3Test, cls).setUpClass() cls.client = cls.servers_client cls.quotas = cls.quotas_client resp, server = cls.create_test_server(meta={}, wait_until='ACTIVE') cls.server_id = server['id'] def setUp(self): super(ServerMetadataV3Test, self).setUp() meta = {'key1': 'value1', 'key2': 'value2'} resp, _ = self.client.set_server_metadata(self.server_id, meta) self.assertEqual(resp.status, 200) @test.attr(type='gate') def test_list_server_metadata(self): # All metadata key/value pairs for a server should be returned resp, resp_metadata = self.client.list_server_metadata(self.server_id) # Verify the expected metadata items are in the list self.assertEqual(200, resp.status) expected = {'key1': 'value1', 'key2': 'value2'} self.assertEqual(expected, resp_metadata) @test.attr(type='gate') def test_set_server_metadata(self): # The server's metadata should be replaced with the provided values # Create a new set of metadata for the server req_metadata = {'meta2': 'data2', 'meta3': 'data3'} resp, metadata = self.client.set_server_metadata(self.server_id, req_metadata) self.assertEqual(200, resp.status) # Verify the expected values are correct, and that the # previous values have been removed resp, resp_metadata = self.client.list_server_metadata(self.server_id) self.assertEqual(resp_metadata, req_metadata) @test.attr(type='gate') def test_update_server_metadata(self): # The server's metadata values should be updated to the # provided values meta = {'key1': 'alt1', 'key3': 'value3'} resp, metadata = self.client.update_server_metadata(self.server_id, meta) self.assertEqual(201, resp.status) # Verify the values have been updated to the proper values resp, resp_metadata = self.client.list_server_metadata(self.server_id) expected = {'key1': 'alt1', 'key2': 'value2', 'key3': 'value3'} self.assertEqual(expected, resp_metadata) @test.attr(type='gate') def test_update_metadata_empty_body(self): # The original metadata should not be lost if empty metadata body is # passed meta = {} _, metadata = self.client.update_server_metadata(self.server_id, meta) resp, resp_metadata = self.client.list_server_metadata(self.server_id) expected = {'key1': 'value1', 'key2': 'value2'} self.assertEqual(expected, resp_metadata) @test.attr(type='gate') def test_get_server_metadata_item(self): # The value for a specific metadata key should be returned resp, meta = self.client.get_server_metadata_item(self.server_id, 'key2') self.assertEqual('value2', meta['key2']) @test.attr(type='gate') def test_set_server_metadata_item(self): # The item's value should be updated to the provided value # Update the metadata value meta = {'nova': 'alt'} resp, body = self.client.set_server_metadata_item(self.server_id, 'nova', meta) self.assertEqual(200, resp.status) # Verify the meta item's value has been updated resp, resp_metadata = self.client.list_server_metadata(self.server_id) expected = {'key1': 'value1', 'key2': 'value2', 'nova': 'alt'} self.assertEqual(expected, resp_metadata) @test.attr(type='gate') def test_delete_server_metadata_item(self): # The metadata value/key pair should be deleted from the server resp, meta = self.client.delete_server_metadata_item(self.server_id, 'key1') self.assertEqual(204, resp.status) # Verify the metadata item has been removed resp, resp_metadata = self.client.list_server_metadata(self.server_id) expected = {'key2': 'value2'} self.assertEqual(expected, resp_metadata)
{ "content_hash": "2098fffcf3e1a6e0c245e4d11576b4f6", "timestamp": "", "source": "github", "line_count": 100, "max_line_length": 78, "avg_line_length": 44.22, "alnum_prop": 0.6087743102668476, "repo_name": "cloudbase/lis-tempest", "id": "c5443ee4adb68bcd086514e552bd7adec6ec6e36", "size": "5058", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "tempest/api/compute/v3/servers/test_server_metadata.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Python", "bytes": "3377111" }, { "name": "Shell", "bytes": "8663" } ], "symlink_target": "" }
package com.suwonsmartapp.studyexam.chat.server; import java.io.DataOutput; public class ClientInfo { private String nickName; private String ip; private DataOutput output; public ClientInfo(String nickName, String ip, DataOutput output) { this.nickName = nickName; this.output = output; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public DataOutput getOutput() { return output; } public void setOutput(DataOutput output) { this.output = output; } }
{ "content_hash": "8628cef02453068b17b8eafe2098cc12", "timestamp": "", "source": "github", "line_count": 33, "max_line_length": 67, "avg_line_length": 19.696969696969695, "alnum_prop": 0.7230769230769231, "repo_name": "suwonsmartapp/study-examples", "id": "db34b7306966dbfd22d2e65ff3841773c42ca86d", "size": "650", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/src/main/java/com/suwonsmartapp/studyexam/chat/server/ClientInfo.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "54202" } ], "symlink_target": "" }
package org.example.fogbeam.blackboard; import java.util.ArrayList; import java.util.List; import java.util.Observable; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class Blackboard extends Observable { private BlockingQueue<Conversation> blackboardQueue = new LinkedBlockingQueue<Conversation>(); private List<Conversation> extantConversations = new ArrayList<Conversation>(); public List<Conversation> getExtantConversations() { return extantConversations; } public void offer( final Conversation conversation ) { blackboardQueue.offer(conversation); this.setChanged(); this.extantConversations.add(conversation); this.notifyObservers(conversation); } private Conversation take() throws InterruptedException { Conversation conversation = blackboardQueue.take(); return conversation; } /* public void run() throws InterruptedException { while( true ) { try { Conversation conversation = take(); // we may be able to delete this, since the agent will register itself // as an observer of the Conversation once it sees it this.extantConversations.add(conversation); this.notifyObservers(conversation); // slow things down while we're working out the mechanics of how all this // works Thread.sleep( 500 ); } catch (InterruptedException e) { e.printStackTrace(); } } } */ }
{ "content_hash": "622d0713e7b2736b30f3decd899e3707", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 96, "avg_line_length": 22.46153846153846, "alnum_prop": 0.7280821917808219, "repo_name": "mindcrime/AISandbox", "id": "23e0e970ad3c3fb5d70876ccf1c21ac0b2855fc3", "size": "1460", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "xmpp-aiml-osgi-blackboard-bot/src/main/java/org/example/fogbeam/blackboard/Blackboard.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "75293" }, { "name": "Java", "bytes": "298784" }, { "name": "SQLPL", "bytes": "1085" }, { "name": "Shell", "bytes": "608" }, { "name": "TeX", "bytes": "20602" } ], "symlink_target": "" }
package com.opengamma.analytics.financial.model.option.definition; import com.opengamma.analytics.financial.interestrate.YieldCurveBundle; import com.opengamma.analytics.financial.model.volatility.curve.BlackForexTermStructureParameters; import com.opengamma.util.money.Currency; import com.opengamma.util.tuple.Pair; import com.opengamma.util.tuple.Pairs; /** * Class describing a yield curve bundle with Black term structure volatility for Forex options. * @deprecated Parent class is deprecated */ @Deprecated public class YieldCurveWithBlackForexTermStructureBundle extends ForexOptionDataBundle<BlackForexTermStructureParameters> { public static YieldCurveWithBlackForexTermStructureBundle from(final YieldCurveBundle ycBundle, final BlackForexTermStructureParameters termStructure, final Pair<Currency, Currency> currencyPair) { return new YieldCurveWithBlackForexTermStructureBundle(ycBundle, termStructure, currencyPair); } /** * Constructor from the smile parameters and the curves. * @param ycBundle The curves bundle. * @param termStructure The term structure parameters. * @param currencyPair The currency pair for which the smile is valid. */ public YieldCurveWithBlackForexTermStructureBundle(final YieldCurveBundle ycBundle, final BlackForexTermStructureParameters termStructure, final Pair<Currency, Currency> currencyPair) { super(ycBundle, termStructure, currencyPair); } @Override public YieldCurveWithBlackForexTermStructureBundle copy() { final YieldCurveBundle curves = getCurvesCopy(); final BlackForexTermStructureParameters termStructure = new BlackForexTermStructureParameters(getVolatilityModel().getVolatilityCurve()); final Pair<Currency, Currency> currencyPair = Pairs.of(getCurrencyPair().getFirst(), getCurrencyPair().getSecond()); return new YieldCurveWithBlackForexTermStructureBundle(curves, termStructure, currencyPair); } @Override public YieldCurveWithBlackForexTermStructureBundle with(final YieldCurveBundle ycBundle) { return new YieldCurveWithBlackForexTermStructureBundle(ycBundle, getVolatilityModel(), getCurrencyPair()); } @Override public YieldCurveWithBlackForexTermStructureBundle with(final BlackForexTermStructureParameters volatilityModel) { return new YieldCurveWithBlackForexTermStructureBundle(this, volatilityModel, getCurrencyPair()); } }
{ "content_hash": "d9fd00d6a62cd65e2b2b39823ee5d696", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 199, "avg_line_length": 48.63265306122449, "alnum_prop": 0.824171212757029, "repo_name": "jerome79/OG-Platform", "id": "54695ac20e06df727f60aa218f914839c45f7b95", "size": "2520", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "projects/OG-Analytics/src/main/java/com/opengamma/analytics/financial/model/option/definition/YieldCurveWithBlackForexTermStructureBundle.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "4064" }, { "name": "CSS", "bytes": "212432" }, { "name": "GAP", "bytes": "1490" }, { "name": "Groovy", "bytes": "11518" }, { "name": "HTML", "bytes": "284313" }, { "name": "Java", "bytes": "80970799" }, { "name": "JavaScript", "bytes": "1528695" }, { "name": "PLSQL", "bytes": "105" }, { "name": "PLpgSQL", "bytes": "13175" }, { "name": "Protocol Buffer", "bytes": "53119" }, { "name": "SQLPL", "bytes": "1004" }, { "name": "Shell", "bytes": "10958" } ], "symlink_target": "" }
#ifndef OMPLEXT_BOOST_NUMERIC_ODEINT_INTEGRATE_NULL_OBSERVER_HPP_INCLUDED #define OMPLEXT_BOOST_NUMERIC_ODEINT_INTEGRATE_NULL_OBSERVER_HPP_INCLUDED namespace boost { namespace numeric { namespace omplext_odeint { struct null_observer { template< class State , class Time > void operator()( const State& /* x */ , Time /* t */ ) const { } }; } // namespace omplext_odeint } // namespace numeric } // namespace boost #endif // BOOST_NUMERIC_ODEINT_INTEGRATE_NULL_OBSERVER_HPP_INCLUDED
{ "content_hash": "6de72ac8fcea1112d469322f4ef64f81", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 73, "avg_line_length": 21.125, "alnum_prop": 0.7159763313609467, "repo_name": "mpomarlan/ompl_slprm", "id": "d525107c1d39d4dbb502d95b4599e71825fa71ee", "size": "861", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/external/omplext_odeint/boost/numeric/odeint/integrate/null_observer.hpp", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "135078" }, { "name": "C++", "bytes": "2776858" }, { "name": "JavaScript", "bytes": "69501" }, { "name": "Objective-C", "bytes": "22385" }, { "name": "PHP", "bytes": "11620" }, { "name": "Python", "bytes": "152447" }, { "name": "Shell", "bytes": "4562" } ], "symlink_target": "" }
function MulitcastResult() { this.success = undefined; this.failure = undefined; this.canonicalIds = undefined; this.multicastId = undefined; this.results = []; this.retryMulticastIds = []; } MulitcastResult.prototype.addResult = function (result) { this.results.push(result); }; MulitcastResult.prototype.getTotal = function () { return this.success + this.failure; }; module.exports = MulitcastResult;
{ "content_hash": "d2730670ec1fed6ec170d7d8ba6ba638", "timestamp": "", "source": "github", "line_count": 20, "max_line_length": 57, "avg_line_length": 22.05, "alnum_prop": 0.6984126984126984, "repo_name": "ericsaboia/gcm-push", "id": "9d5515fbf5c9f08dee0d59d60eed6943c46d9a36", "size": "529", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/multicastresult.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "5762" } ], "symlink_target": "" }
require "spec_helper" describe Chef::Provider::Git do before(:each) do allow(STDOUT).to receive(:tty?).and_return(true) @original_log_level = Chef::Log.level Chef::Log.level = :info @current_resource = Chef::Resource::Git.new("web2.0 app") @current_resource.revision("d35af14d41ae22b19da05d7d03a0bafc321b244c") @resource = Chef::Resource::Git.new("web2.0 app") @resource.repository "git://github.com/opscode/chef.git" @resource.destination "/my/deploy/dir" @resource.revision "d35af14d41ae22b19da05d7d03a0bafc321b244c" @node = Chef::Node.new @events = Chef::EventDispatch::Dispatcher.new @run_context = Chef::RunContext.new(@node, {}, @events) @provider = Chef::Provider::Git.new(@resource, @run_context) @provider.current_resource = @current_resource end after(:each) do Chef::Log.level = @original_log_level end context "determining the revision of the currently deployed checkout" do before do @stdout = double("standard out") @stderr = double("standard error") @exitstatus = double("exitstatus") end it "sets the current revision to nil if the deploy dir does not exist" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) expect(@provider.find_current_revision).to be_nil end it "determines the current revision when there is one" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) @stdout = "9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\n" expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", { cwd: "/my/deploy/dir", returns: [0, 128], log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.find_current_revision).to eql("9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13") end it "gives the current revision as nil when there is no current revision" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) @stderr = "fatal: Not a git repository (or any of the parent directories): .git" @stdout = "" expect(@provider).to receive(:shell_out!).with("git rev-parse HEAD", cwd: "/my/deploy/dir", returns: [0, 128], log_tag: "git[web2.0 app]" ).and_return(double("ShellOut result", stdout: "", stderr: @stderr)) expect(@provider.find_current_revision).to be_nil end end it "creates a current_resource with the currently deployed revision when a clone exists in the destination dir" do allow(@provider).to receive(:find_current_revision).and_return("681c9802d1c62a45b490786c18f0b8216b309440") @provider.load_current_resource expect(@provider.current_resource.name).to eql(@resource.name) expect(@provider.current_resource.revision).to eql("681c9802d1c62a45b490786c18f0b8216b309440") end it "keeps the node and resource passed to it on initialize" do expect(@provider.node).to equal(@node) expect(@provider.new_resource).to equal(@resource) end context "cast git version into gem version object" do it "returns correct version with standard git" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version 2.14.1")) expect(@provider.git_gem_version).to eq Gem::Version.new("2.14.1") end it "returns correct version with Apple git" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version 2.11.0 (Apple Git-81)")) expect(@provider.git_gem_version).to eq Gem::Version.new("2.11.0") end it "maintains deprecated method name" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version 1.2.3")) expect(@provider.git_minor_version).to eq Gem::Version.new("1.2.3") end it "does not know how to handle other version" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version home-grown-git-99")) expect(@provider.git_gem_version).to be_nil end it "determines single branch option when it fails to parse git version" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version home-grown-git-99")) expect(@provider.git_has_single_branch_option?).to be false end it "determines single branch option as true when it parses git version and version is large" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version 1.8.0")) expect(@provider.git_has_single_branch_option?).to be true end it "determines single branch option as false when it parses git version and version is small" do expect(@provider).to receive(:shell_out!) .with("git --version", log_tag: "git[web2.0 app]") .and_return(double("ShellOut result", stdout: "git version 1.7.4")) expect(@provider.git_has_single_branch_option?).to be false end it "is compatible with git in travis" do expect(@provider.git_gem_version).to be > Gem::Version.new("1.0") end end context "resolving revisions to a SHA" do before do @git_ls_remote = "git ls-remote \"git://github.com/opscode/chef.git\" " end it "returns resource.revision as is if revision is already a full SHA" do expect(@provider.target_revision).to eql("d35af14d41ae22b19da05d7d03a0bafc321b244c") end it "converts resource.revision from a tag to a SHA" do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from an annotated tag to the tagged SHA (not SHA of tag)" do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0^{}\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("663c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from a tag to a SHA using an exact match" do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/releases/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from a tag to a SHA, matching tags first, then heads" do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("663c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from a tag to a SHA, matching heads if no tags match" do @resource.revision "v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.1\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from a tag to a SHA, matching tags first, then heads, then revision" do @resource.revision "refs/pulls/v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "805c22a5e41f5ae3193460cca044ed1435029f53\trefs/pulls/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/pulls/v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("805c22a5e41f5ae3193460cca044ed1435029f53") end it "converts resource.revision from a tag to a SHA, using full path if provided" do @resource.revision "refs/heads/v1.0" @stdout = ("d03c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" + "663c22a5e41f5ae3193460cca044ed1435029f53\trefs/tags/v1.0\n" + "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/v1.0\n") expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"refs/heads/v1.0*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("503c22a5e41f5ae3193460cca044ed1435029f53") end it "raises an invalid remote reference error if you try to deploy from ``origin'' and assertions are run" do @resource.revision "origin/" @provider.action = :checkout @provider.define_resource_requirements allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::InvalidRemoteGitReference) end it "raises an unresolvable git reference error if the revision can't be resolved to any revision and assertions are run" do @resource.revision "FAIL, that's the revision I want" @provider.action = :checkout expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", stdout: "\n")) @provider.define_resource_requirements expect { @provider.process_resource_requirements }.to raise_error(Chef::Exceptions::UnresolvableGitReference) end it "does not raise an error if the revision can't be resolved when assertions are not run" do @resource.revision "FAIL, that's the revision I want" expect(@provider).to receive(:shell_out!).and_return(double("ShellOut result", stdout: "\n")) expect(@provider.target_revision).to eq(nil) end it "does not raise an error when the revision is valid and assertions are run." do @resource.revision "0.8-alpha" @stdout = "503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha\n" expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"0.8-alpha*\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) @provider.action = :checkout allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) @provider.define_resource_requirements expect { @provider.process_resource_requirements }.not_to raise_error end it "gives the latest HEAD revision SHA if nothing is specified" do @stdout = <<~SHAS 28af684d8460ba4793eda3e7ac238c864a5d029a\tHEAD 503c22a5e41f5ae3193460cca044ed1435029f53\trefs/heads/0.8-alpha 28af684d8460ba4793eda3e7ac238c864a5d029a\trefs/heads/master c44fe79bb5e36941ce799cee6b9de3a2ef89afee\trefs/tags/0.5.2 14534f0e0bf133dc9ff6dbe74f8a0c863ff3ac6d\trefs/tags/0.5.4 d36fddb4291341a1ff2ecc3c560494e398881354\trefs/tags/0.5.6 9e5ce9031cbee81015de680d010b603bce2dd15f\trefs/tags/0.6.0 9b4d8dc38dd471246e7cfb1c3c1ad14b0f2bee13\trefs/tags/0.6.2 014a69af1cdce619de82afaf6cdb4e6ac658fede\trefs/tags/0.7.0 fa8097ff666af3ce64761d8e1f1c2aa292a11378\trefs/tags/0.7.2 44f9be0b33ba5c10027ddb030a5b2f0faa3eeb8d\trefs/tags/0.7.4 d7b9957f67236fa54e660cc3ab45ffecd6e0ba38\trefs/tags/0.7.8 b7d19519a1c15f1c1a324e2683bd728b6198ce5a\trefs/tags/0.7.8^{} ebc1b392fe7e8f0fbabc305c299b4d365d2b4d9b\trefs/tags/chef-server-package SHAS @resource.revision "" expect(@provider).to receive(:shell_out!).with(@git_ls_remote + "\"HEAD\"", { log_tag: "git[web2.0 app]" }).and_return(double("ShellOut result", stdout: @stdout)) expect(@provider.target_revision).to eql("28af684d8460ba4793eda3e7ac238c864a5d029a") end end it "responds to :revision_slug as an alias for target_revision" do expect(@provider).to respond_to(:revision_slug) end context "with an ssh wrapper" do let(:deploy_user) { "deployNinja" } let(:wrapper) { "do_it_this_way.sh" } let(:expected_cmd) { 'git clone "git://github.com/opscode/chef.git" "/my/deploy/dir"' } let(:default_options) do { user: deploy_user, environment: { "GIT_SSH" => wrapper, "HOME" => "/home/deployNinja" }, log_tag: "git[web2.0 app]", } end before do @resource.user deploy_user @resource.ssh_wrapper wrapper allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja")) end context "without a timeout set" do it "clones a repo with default git options" do expect(@provider).to receive(:shell_out!).with(expected_cmd, default_options) @provider.clone end end context "with a timeout set" do let (:seconds) { 10 } before { @resource.timeout(seconds) } it "clones a repo with amended git options" do expect(@provider).to receive(:shell_out!).with(expected_cmd, default_options.merge(timeout: seconds)) @provider.clone end end context "with a specific home" do let (:override_home) do { "HOME" => "/home/masterNinja" } end let(:overrided_options) do { user: deploy_user, environment: { "GIT_SSH" => wrapper, "HOME" => "/home/masterNinja" }, log_tag: "git[web2.0 app]", } end before do @resource.environment(override_home) end before { @resource.environment(override_home) } it "clones a repo with amended git options with specific home" do expect(@provider).to receive(:shell_out!).with(expected_cmd, overrided_options) @provider.clone end end end context "with a user id" do let(:deploy_user) { 123 } let(:expected_cmd) { 'git clone "git://github.com/opscode/chef.git" "/my/deploy/dir"' } let(:default_options) do { user: 123, environment: { "HOME" => "/home/deployNinja" }, log_tag: "git[web2.0 app]", } end before do @resource.user deploy_user allow(Etc).to receive(:getpwuid).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja")) end context "with a specific home" do let (:override_home) do { "HOME" => "/home/masterNinja" } end let(:overrided_options) do { user: 123, environment: { "HOME" => "/home/masterNinja" }, log_tag: "git[web2.0 app]", } end before do @resource.environment(override_home) end before { @resource.environment(override_home) } it "clones a repo with amended git options with specific home" do expect(@provider).to receive(:shell_out!).with(expected_cmd, hash_including(overrided_options)) @provider.clone end end end it "runs a clone command with escaped destination" do @resource.user "deployNinja" allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/deployNinja")) @resource.destination "/Application Support/with/space" @resource.ssh_wrapper "do_it_this_way.sh" expected_cmd = "git clone \"git://github.com/opscode/chef.git\" \"/Application Support/with/space\"" expect(@provider).to receive(:shell_out!).with(expected_cmd, user: "deployNinja", log_tag: "git[web2.0 app]", environment: { "HOME" => "/home/deployNinja", "GIT_SSH" => "do_it_this_way.sh" }) @provider.clone end it "compiles a clone command using --depth for shallow cloning" do @resource.depth 5 expected_cmd = "git clone --depth 5 \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\"" version_response = double("shell_out") allow(version_response).to receive(:stdout) { "git version 1.7.9" } expect(@provider).to receive(:shell_out!).with("git --version", log_tag: "git[web2.0 app]").and_return(version_response) expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]") @provider.clone end it "compiles a clone command using --no-single-branch for shallow cloning when git >= 1.7.10" do @resource.depth 5 expected_cmd = "git clone --depth 5 --no-single-branch \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\"" version_response = double("shell_out") allow(version_response).to receive(:stdout) { "git version 1.7.10" } expect(@provider).to receive(:shell_out!).with("git --version", log_tag: "git[web2.0 app]").and_return(version_response) expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]") @provider.clone end it "compiles a clone command with a remote other than ``origin''" do @resource.remote "opscode" expected_cmd = "git clone -o opscode \"git://github.com/opscode/chef.git\" \"/my/deploy/dir\"" expect(@provider).to receive(:shell_out!).with(expected_cmd, log_tag: "git[web2.0 app]") @provider.clone end it "runs a checkout command with default options" do expect(@provider).to receive(:shell_out!).with("git branch -f deploy d35af14d41ae22b19da05d7d03a0bafc321b244c", cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]").ordered expect(@provider).to receive(:shell_out!).with("git checkout deploy", cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]").ordered @provider.checkout end it "runs an enable_submodule command" do @resource.enable_submodules true expected_cmd = "git submodule sync" expect(@provider).to receive(:shell_out!).with(expected_cmd, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") expected_cmd = "git submodule update --init --recursive" expect(@provider).to receive(:shell_out!).with(expected_cmd, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.enable_submodules end it "does nothing for enable_submodules if resource.enable_submodules #=> false" do expect(@provider).not_to receive(:shell_out!) @provider.enable_submodules end it "runs a sync command with default options" do expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) expected_cmd1 = "git fetch --prune origin" expect(@provider).to receive(:shell_out!).with(expected_cmd1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") expected_cmd2 = "git fetch origin --tags" expect(@provider).to receive(:shell_out!).with(expected_cmd2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") expected_cmd3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" expect(@provider).to receive(:shell_out!).with(expected_cmd3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.fetch_updates end it "runs a sync command with the user and group specified in the resource" do @resource.user("whois") allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/whois")) @resource.group("thisis") expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) expected_cmd1 = "git fetch --prune origin" expect(@provider).to receive(:shell_out!).with(expected_cmd1, cwd: "/my/deploy/dir", user: "whois", group: "thisis", log_tag: "git[web2.0 app]", environment: { "HOME" => "/home/whois" }) expected_cmd2 = "git fetch origin --tags" expect(@provider).to receive(:shell_out!).with(expected_cmd2, cwd: "/my/deploy/dir", user: "whois", group: "thisis", log_tag: "git[web2.0 app]", environment: { "HOME" => "/home/whois" }) expected_cmd3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" expect(@provider).to receive(:shell_out!).with(expected_cmd3, cwd: "/my/deploy/dir", user: "whois", group: "thisis", log_tag: "git[web2.0 app]", environment: { "HOME" => "/home/whois" }) @provider.fetch_updates end it "configures remote tracking branches when remote is ``origin''" do @resource.remote "origin" expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) fetch_command1 = "git fetch --prune origin" expect(@provider).to receive(:shell_out!).with(fetch_command1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") fetch_command2 = "git fetch origin --tags" expect(@provider).to receive(:shell_out!).with(fetch_command2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") fetch_command3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" expect(@provider).to receive(:shell_out!).with(fetch_command3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.fetch_updates end it "configures remote tracking branches when remote is not ``origin''" do @resource.remote "opscode" expect(@provider).to receive(:setup_remote_tracking_branches).with(@resource.remote, @resource.repository) fetch_command1 = "git fetch --prune opscode" expect(@provider).to receive(:shell_out!).with(fetch_command1, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") fetch_command2 = "git fetch opscode --tags" expect(@provider).to receive(:shell_out!).with(fetch_command2, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") fetch_command3 = "git reset --hard d35af14d41ae22b19da05d7d03a0bafc321b244c" expect(@provider).to receive(:shell_out!).with(fetch_command3, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.fetch_updates end context "configuring remote tracking branches" do it "checks if a remote with this name already exists" do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 1 } expected_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(expected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", returns: [0, 1, 2]).and_return(command_response) add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(add_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end it "runs the config with the user and group specified in the resource" do @resource.user("whois") @resource.group("thisis") allow(Etc).to receive(:getpwnam).and_return(double("Struct::Passwd", name: @resource.user, dir: "/home/whois")) command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 1 } expected_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(expected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", user: "whois", group: "thisis", environment: { "HOME" => "/home/whois" }, returns: [0, 1, 2]).and_return(command_response) add_remote_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(add_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", user: "whois", group: "thisis", environment: { "HOME" => "/home/whois" }) @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end describe "when a remote with a given name hasn't been configured yet" do it "adds a new remote " do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 1 } check_remote_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(check_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", returns: [0, 1, 2]).and_return(command_response) expected_command = "git remote add #{@resource.remote} #{@resource.repository}" expect(@provider).to receive(:shell_out!).with(expected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end end describe "when a remote with a given name has already been configured" do it "updates remote url when the url is different" do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 0 } allow(command_response).to receive(:stdout) { "some_other_url" } check_remote_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(check_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", returns: [0, 1, 2]).and_return(command_response) expected_command = "git config --replace-all remote.#{@resource.remote}.url \"#{@resource.repository}\"" expect(@provider).to receive(:shell_out!).with(expected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end it "doesn't update remote url when the url is the same" do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 0 } allow(command_response).to receive(:stdout) { @resource.repository } check_remote_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(check_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", returns: [0, 1, 2]).and_return(command_response) unexpected_command = "git config --replace-all remote.#{@resource.remote}.url \"#{@resource.repository}\"" expect(@provider).not_to receive(:shell_out!).with(unexpected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end it "resets remote url when it has multiple values" do command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 2 } check_remote_command = "git config --get remote.#{@resource.remote}.url" expect(@provider).to receive(:shell_out!).with(check_remote_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]", returns: [0, 1, 2]).and_return(command_response) expected_command = "git config --replace-all remote.#{@resource.remote}.url \"#{@resource.repository}\"" expect(@provider).to receive(:shell_out!).with(expected_command, cwd: "/my/deploy/dir", log_tag: "git[web2.0 app]") @provider.setup_remote_tracking_branches(@resource.remote, @resource.repository) end end end it "raises an error if the git clone command would fail because the enclosing directory doesn't exist" do allow(@provider).to receive(:shell_out!) expect { @provider.run_action(:sync) }.to raise_error(Chef::Exceptions::MissingParentDirectory) end it "does a checkout by cloning the repo and then enabling submodules" do # will be invoked in load_current_resource allow(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", ".."]) expect(@provider).to receive(:clone) expect(@provider).to receive(:checkout) expect(@provider).to receive(:enable_submodules) @provider.run_action(:checkout) # Even though an actual run will cause an update to occur, the fact that we've stubbed out # the actions above will prevent updates from registering # @resource.should be_updated end it "does not call checkout if enable_checkout is false" do # will be invoked in load_current_resource allow(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", ".."]) @resource.enable_checkout false expect(@provider).to receive(:clone) expect(@provider).not_to receive(:checkout) expect(@provider).to receive(:enable_submodules) @provider.run_action(:checkout) end # REGRESSION TEST: on some OSes, the entries from an empty directory will be listed as # ['..', '.'] but this shouldn't change the behavior it "does a checkout by cloning the repo and then enabling submodules when the directory entries are listed as %w{.. .}" do allow(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(false) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return(["..", "."]) expect(@provider).to receive(:clone) expect(@provider).to receive(:checkout) expect(@provider).to receive(:enable_submodules) expect(@provider).to receive(:add_remotes) @provider.run_action(:checkout) # @resource.should be_updated end it "should not checkout if the destination exists or is a non empty directory" do # will be invoked in load_current_resource allow(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(false) allow(::File).to receive(:exist?).with("/my/deploy/dir").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(::Dir).to receive(:entries).with("/my/deploy/dir").and_return([".", "..", "foo", "bar"]) expect(@provider).not_to receive(:clone) expect(@provider).not_to receive(:checkout) expect(@provider).not_to receive(:enable_submodules) expect(@provider).not_to receive(:add_remotes) @provider.run_action(:checkout) expect(@resource).not_to be_updated end it "syncs the code by updating the source when the repo has already been checked out" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) expect(@provider).to receive(:find_current_revision).exactly(1).and_return("d35af14d41ae22b19da05d7d03a0bafc321b244c") expect(@provider).not_to receive(:fetch_updates) expect(@provider).to receive(:add_remotes) @provider.run_action(:sync) expect(@resource).not_to be_updated end it "marks the resource as updated when the repo is updated and gets a new version" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) # invoked twice - first time from load_current_resource expect(@provider).to receive(:find_current_revision).exactly(1).and_return("d35af14d41ae22b19da05d7d03a0bafc321b244c") allow(@provider).to receive(:target_revision).and_return("28af684d8460ba4793eda3e7ac238c864a5d029a") expect(@provider).to receive(:fetch_updates) expect(@provider).to receive(:enable_submodules) expect(@provider).to receive(:add_remotes) @provider.run_action(:sync) # @resource.should be_updated end it "does not fetch any updates if the remote revision matches the current revision" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(@provider).to receive(:find_current_revision).and_return("d35af14d41ae22b19da05d7d03a0bafc321b244c") allow(@provider).to receive(:target_revision).and_return("d35af14d41ae22b19da05d7d03a0bafc321b244c") expect(@provider).not_to receive(:fetch_updates) expect(@provider).to receive(:add_remotes) @provider.run_action(:sync) expect(@resource).not_to be_updated end it "clones the repo instead of fetching it if the deploy directory doesn't exist" do allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").exactly(2).and_return(false) expect(@provider).to receive(:action_checkout) expect(@provider).not_to receive(:shell_out!) @provider.run_action(:sync) # @resource.should be_updated end it "clones the repo instead of fetching updates if the deploy directory is empty" do expect(::File).to receive(:exist?).with("/my/deploy/dir/.git").exactly(2).and_return(false) allow(::File).to receive(:directory?).with("/my/deploy").and_return(true) allow(::File).to receive(:directory?).with("/my/deploy/dir").and_return(true) allow(@provider).to receive(:sync_command).and_return("huzzah!") expect(@provider).to receive(:action_checkout) expect(@provider).not_to receive(:shell_out!).with("huzzah!", cwd: "/my/deploy/dir") @provider.run_action(:sync) # @resource.should be_updated end it "does an export by cloning the repo then removing the .git directory" do expect(@provider).to receive(:action_checkout) expect(FileUtils).to receive(:rm_rf).with(@resource.destination + "/.git") @provider.run_action(:export) expect(@resource).to be_updated end describe "calling add_remotes" do it "adds a new remote for each entry in additional remotes hash" do @resource.additional_remotes({ opscode: "opscode_repo_url", another_repo: "some_other_repo_url" }) allow(STDOUT).to receive(:tty?).and_return(false) command_response = double("shell_out") allow(command_response).to receive(:exitstatus) { 0 } @resource.additional_remotes.each_pair do |remote_name, remote_url| expect(@provider).to receive(:setup_remote_tracking_branches).with(remote_name, remote_url) end @provider.add_remotes end end describe "calling multiple_remotes?" do before(:each) do @command_response = double("shell_out") end describe "when check remote command returns with status 2" do it "returns true" do allow(@command_response).to receive(:exitstatus) { 2 } expect(@provider.multiple_remotes?(@command_response)).to be_truthy end end describe "when check remote command returns with status 0" do it "returns false" do allow(@command_response).to receive(:exitstatus) { 0 } expect(@provider.multiple_remotes?(@command_response)).to be_falsey end end describe "when check remote command returns with status 0" do it "returns false" do allow(@command_response).to receive(:exitstatus) { 1 } expect(@provider.multiple_remotes?(@command_response)).to be_falsey end end end describe "calling remote_matches?" do before(:each) do @command_response = double("shell_out") end describe "when output of the check remote command matches the repository url" do it "returns true" do allow(@command_response).to receive(:exitstatus) { 0 } allow(@command_response).to receive(:stdout) { @resource.repository } expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_truthy end end describe "when output of the check remote command doesn't match the repository url" do it "returns false" do allow(@command_response).to receive(:exitstatus) { 0 } allow(@command_response).to receive(:stdout) { @resource.repository + "test" } expect(@provider.remote_matches?(@resource.repository, @command_response)).to be_falsey end end end end
{ "content_hash": "d9382821c884159e3772ca8d595bf809", "timestamp": "", "source": "github", "line_count": 764, "max_line_length": 212, "avg_line_length": 52.84424083769633, "alnum_prop": 0.631164392044188, "repo_name": "tomdoherty/chef", "id": "4a6266b58aabfc5368b251f1f269eb69506ef2e4", "size": "41064", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "spec/unit/provider/git_spec.rb", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2717" }, { "name": "Dockerfile", "bytes": "345" }, { "name": "HTML", "bytes": "37416" }, { "name": "Makefile", "bytes": "1326" }, { "name": "Perl", "bytes": "64" }, { "name": "PowerShell", "bytes": "17296" }, { "name": "Python", "bytes": "54260" }, { "name": "Roff", "bytes": "781" }, { "name": "Ruby", "bytes": "9422991" }, { "name": "Shell", "bytes": "24693" } ], "symlink_target": "" }
import { test, moduleFor } from 'ember-qunit'; moduleFor('route:player', 'PlayerRoute', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); test('it exists', function() { var route = this.subject(); ok(route); });
{ "content_hash": "f33dc8d89624887fa55f72d308141c1f", "timestamp": "", "source": "github", "line_count": 11, "max_line_length": 61, "avg_line_length": 24.272727272727273, "alnum_prop": 0.651685393258427, "repo_name": "aequitas/munerator", "id": "079ae97e4c9786caa7cef14df7997ee2d4dd1c32", "size": "267", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "arena/tests/unit/routes/player-test.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "539" }, { "name": "HTML", "bytes": "2052" }, { "name": "Handlebars", "bytes": "11697" }, { "name": "JavaScript", "bytes": "27664" }, { "name": "Makefile", "bytes": "2090" }, { "name": "Python", "bytes": "71095" }, { "name": "Shell", "bytes": "454" } ], "symlink_target": "" }
package io.trivium.dep.com.google.common.util.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.FutureTask; import javax.annotation.Nullable; /** * A {@link FutureTask} that also implements the {@link ListenableFuture} * interface. Unlike {@code FutureTask}, {@code ListenableFutureTask} does not * provide an overrideable {@link FutureTask#done() done()} method. For similar * functionality, call {@link #addListener}. * * <p> * * @author Sven Mawson * @since 1.0 */ public class ListenableFutureTask<V> extends FutureTask<V> implements ListenableFuture<V> { // TODO(cpovirk): explore ways of making ListenableFutureTask final. There are // some valid reasons such as BoundedQueueExecutorService to allow extends but it // would be nice to make it final to avoid unintended usage. // The execution list to hold our listeners. private final ExecutionList executionList = new ExecutionList(); /** * Creates a {@code ListenableFutureTask} that will upon running, execute the * given {@code Callable}. * * @param callable the callable task * @since 10.0 */ public static <V> ListenableFutureTask<V> create(Callable<V> callable) { return new ListenableFutureTask<V>(callable); } /** * Creates a {@code ListenableFutureTask} that will upon running, execute the * given {@code Runnable}, and arrange that {@code get} will return the * given result on successful completion. * * @param runnable the runnable task * @param result the result to return on successful completion. If you don't * need a particular result, consider using constructions of the form: * {@code ListenableFuture<?> f = ListenableFutureTask.create(runnable, * null)} * @since 10.0 */ public static <V> ListenableFutureTask<V> create( Runnable runnable, @Nullable V result) { return new ListenableFutureTask<V>(runnable, result); } ListenableFutureTask(Callable<V> callable) { super(callable); } ListenableFutureTask(Runnable runnable, @Nullable V result) { super(runnable, result); } @Override public void addListener(Runnable listener, Executor exec) { executionList.add(listener, exec); } /** * Internal implementation detail used to invoke the listeners. */ @Override protected void done() { executionList.execute(); } }
{ "content_hash": "d41594483fcc48c8ff80850a935beb44", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 83, "avg_line_length": 30.72151898734177, "alnum_prop": 0.7124021425628347, "repo_name": "trivium-io/trivium-core", "id": "18d13c2bad04b223b763d802bb811ce131625eab", "size": "3027", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/io/trivium/dep/com/google/common/util/concurrent/ListenableFutureTask.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "9683" }, { "name": "HTML", "bytes": "78864" }, { "name": "Java", "bytes": "8440296" }, { "name": "JavaScript", "bytes": "1481641" }, { "name": "Shell", "bytes": "398" } ], "symlink_target": "" }
package edu.usu.sdl.openstorefront.service.io.parser; import au.com.bytecode.opencsv.CSVReader; import edu.usu.sdl.openstorefront.common.exception.OpenStorefrontRuntimeException; import edu.usu.sdl.openstorefront.core.entity.AttributeCode; import edu.usu.sdl.openstorefront.core.entity.AttributeType; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * @author dshurtleff */ public abstract class BaseAttributeParser { protected Map<AttributeType, List<AttributeCode>> attributeMap = new HashMap<>(); public Map<AttributeType, List<AttributeCode>> parse(InputStream in) { try (CSVReader reader = new CSVReader(new InputStreamReader(in));) { internalParse(reader); } catch (Exception e) { throw new OpenStorefrontRuntimeException(e); } return attributeMap; } /** * * @return */ public abstract String getHEADER(); protected abstract void internalParse(CSVReader reader) throws IOException; }
{ "content_hash": "209bbdd1b953a96cde3a6b9dabcd4c09", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 82, "avg_line_length": 24.904761904761905, "alnum_prop": 0.7724665391969407, "repo_name": "Razaltan/openstorefront", "id": "4074aebbdda634b09f9fce7816739df34e240549", "size": "1700", "binary": false, "copies": "4", "ref": "refs/heads/v1.6", "path": "server/openstorefront/openstorefront-core/service/src/main/java/edu/usu/sdl/openstorefront/service/io/parser/BaseAttributeParser.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "24139" }, { "name": "CSS", "bytes": "1050294" }, { "name": "HTML", "bytes": "975330" }, { "name": "Java", "bytes": "3239344" }, { "name": "JavaScript", "bytes": "2138479" }, { "name": "PHP", "bytes": "2199" }, { "name": "Ruby", "bytes": "44" } ], "symlink_target": "" }
/** \file * * * \brief Master header file for all routines in SLsimLib. Should be the only header file that needs to be included. * * assert() statements can be removed here. * * slsimlib.h * * Created on: Oct 25, 2011 * Author: bmetcalf */ #ifndef _SLSIMLIB_DECLARE_ #define _SLSIMLIB_DECLARE_ #include "utilities_slsim.h" #include "lens_halos.h" #include <KistDriver.h> #include <divide_images.h> #include <tree_maintenance.h> #include <grid_maintenance.h> #include <source_models.h> #include <peak_refinement.h> #include <map_images.h> #include <fitlens.h> #include <image_processing.h> #include <nsie.h> /**** halos ****/ #include "analytic_lens.h" #include "uniform_lens.h" #include "MOKAlens.h" #include "particle_halo.h" /**** sources ****/ #include "sourceAnaGalaxy.h" #include "overzier_source.h" #include "sersic_source.h" #include "causticdata.h" #endif
{ "content_hash": "8121ebb7b873ae9aa8f83a5cdd13306a", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 117, "avg_line_length": 18.285714285714285, "alnum_prop": 0.6897321428571429, "repo_name": "glenco/SLsimLib", "id": "1c2346fc9e973b4c9efe752b4017191df469b12e", "size": "896", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "include/slsimlib.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "20663" }, { "name": "C++", "bytes": "2215860" }, { "name": "CMake", "bytes": "4142" }, { "name": "TeX", "bytes": "3249" } ], "symlink_target": "" }
<?php namespace Concrete\Controller\Panel\Page; use Concrete\Controller\Backend\UserInterface\Page as BackendUIPageController; use Concrete\Core\Page\Collection\Version\Version; use Concrete\Core\Page\Type\Type; use Permissions; use PageTemplate; use PageTheme; use Request; use PageEditResponse; use Loader; use Response; use View; use User; use Concrete\Core\Workflow\Request\ApprovePageRequest; use Config; class Design extends BackendUIPageController { protected $viewPath = '/panels/page/design'; public function canAccess() { return $this->permissions->canEditPageTemplate() || $this->permissions->canEditPageTheme(); } public function view() { $c = $this->page; $cp = $this->permissions; $pagetype = $c->getPageTypeObject(); if (is_object($pagetype)) { $_templates = $pagetype->getPageTypePageTemplateObjects(); } else { $_templates = PageTemplate::getList(); } $pTemplateID = $c->getPageTemplateID(); $templates = array(); if ($pTemplateID) { $selectedTemplate = PageTemplate::getByID($pTemplateID); $templates[] = $selectedTemplate; } foreach ($_templates as $tmp) { if (!in_array($tmp, $templates)) { $templates[] = $tmp; } } $tArrayTmp = array_merge(PageTheme::getGlobalList(), PageTheme::getLocalList()); $_themes = array(); foreach ($tArrayTmp as $pt) { if ($cp->canEditPageTheme($pt)) { $_themes[] = $pt; } } $pThemeID = $c->getCollectionThemeID(); if ($pThemeID) { $selectedTheme = PageTheme::getByID($pThemeID); } else { $selectedTheme = PageTheme::getSiteTheme(); } $themes = array($selectedTheme); foreach ($_themes as $t) { if (!in_array($t, $themes)) { $themes[] = $t; } } $templatesSelect = array(); $themesSelect = array(); foreach ($_themes as $pt) { $themesSelect[$pt->getThemeID()] = $pt->getThemeDisplayName(); } foreach ($_templates as $pt) { $templatesSelect[$pt->getPageTemplateID()] = $pt->getPageTemplateDisplayName(); } $typesSelect = array('0' => t('** None')); $tree = $c->getSiteTreeObject(); if (is_object($tree)) { $type = $tree->getSiteType(); $typeList = Type::getList(false, $type); foreach ($typeList as $_pagetype) { $typesSelect[$_pagetype->getPageTypeID()] = $_pagetype->getPageTypeDisplayName(); } } $this->set('templatesSelect', $templatesSelect); $this->set('themesSelect', $themesSelect); $this->set('themes', $themes); $this->set('templates', $templates); $this->set('typesSelect', $typesSelect); $this->set('selectedTheme', $selectedTheme); $this->set('selectedType', $pagetype); $this->set('selectedTemplate', $selectedTemplate); } public function preview() { $this->setViewObject(new View('/panels/details/page/preview')); } public function preview_contents() { $req = Request::getInstance(); $req->setCurrentPage($this->page); $controller = $this->page->getPageController(); $view = $controller->getViewObject(); if ($_REQUEST['pTemplateID']) { $pt = PageTemplate::getByID(Loader::helper('security')->sanitizeInt($_REQUEST['pTemplateID'])); if (is_object($pt)) { $view->setCustomPageTemplate($pt); } } if ($_REQUEST['pThemeID']) { $pt = PageTheme::getByID(Loader::helper('security')->sanitizeInt($_REQUEST['pThemeID'])); if (is_object($pt)) { $view->setCustomPageTheme($pt); } } $req->setCustomRequestUser(-1); $response = new Response(); $content = $view->render(); $response->setContent($content); return $response; } public function submit() { if ($this->validateAction()) { $cp = $this->permissions; $c = $this->page; $nvc = $c->getVersionToModify(); if ($this->permissions->canEditPageTheme()) { $pl = false; if ($_POST['pThemeID']) { $pl = PageTheme::getByID($_POST['pThemeID']); } $data = array(); if (is_object($pl)) { $nvc->setTheme($pl); } } if (!$c->isGeneratedCollection()) { if ($_POST['pTemplateID'] && $cp->canEditPageTemplate()) { // now we have to check to see if you're allowed to update this page to this page type. // We do this by checking to see whether the PARENT page allows you to add this page type here. // if this is the home page then we assume you are good $template = PageTemplate::getByID($_POST['pTemplateID']); $proceed = true; $pagetype = $c->getPageTypeObject(); if (is_object($pagetype)) { $templates = $pagetype->getPageTypePageTemplateObjects(); if (!in_array($template, $templates)) { $proceed = false; } } if ($proceed) { $data['pTemplateID'] = $_POST['pTemplateID']; $nvc->update($data); } } if ($cp->canEditPageType()) { $ptID = $c->getPageTypeID(); if ($ptID != $_POST['ptID']) { // the page type has changed. if ($_POST['ptID']) { $type = Type::getByID($_POST['ptID']); if (is_object($type)) { $nvc->setPageType($type); } } else { $nvc->setPageType(null); } } } } $r = new PageEditResponse(); $r->setPage($c); if ($this->request->request->get('sitemap')) { $r->setMessage(t('Page updated successfully.')); if ($this->permissions->canApprovePageVersions() && Config::get('concrete.misc.sitemap_approve_immediately')) { $pkr = new ApprovePageRequest(); $u = new User(); $pkr->setRequestedPage($this->page); $v = Version::get($this->page, "RECENT"); $pkr->setRequestedVersionID($v->getVersionID()); $pkr->setRequesterUserID($u->getUserID()); $response = $pkr->trigger(); $u->unloadCollectionEdit(); } } else { $r->setRedirectURL(\URL::to($c)); } $r->outputJSON(); } } }
{ "content_hash": "316ee7ec709fb5c6c3b1d40b2cbda0df", "timestamp": "", "source": "github", "line_count": 210, "max_line_length": 127, "avg_line_length": 34.89047619047619, "alnum_prop": 0.4866930530913061, "repo_name": "a3020/concrete5", "id": "2ae9f68490b2eb0a93342d23e5d66442cf530c07", "size": "7327", "binary": false, "copies": "2", "ref": "refs/heads/develop", "path": "concrete/controllers/panel/page/design.php", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "37" }, { "name": "CSS", "bytes": "495051" }, { "name": "Hack", "bytes": "45" }, { "name": "JavaScript", "bytes": "963634" }, { "name": "PHP", "bytes": "10700471" }, { "name": "Vue", "bytes": "2153" } ], "symlink_target": "" }
FOUNDATION_EXPORT double HiddenVersionNumber; FOUNDATION_EXPORT const unsigned char HiddenVersionString[];
{ "content_hash": "4af0ca2d993618ac15b13ce4a253b4b7", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 60, "avg_line_length": 36, "alnum_prop": 0.8611111111111112, "repo_name": "buribae/Hidden", "id": "40201b4954cf3843c95add58460816121288fec1", "size": "304", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Example/Pods/Target Support Files/Hidden/Hidden-umbrella.h", "mode": "33188", "license": "mit", "language": [ { "name": "Swift", "bytes": "974" } ], "symlink_target": "" }
try: from unittest.mock import patch except ImportError: # for python 2.7 from mock import patch
{ "content_hash": "d2875b35864111412f8557ad47970ee2", "timestamp": "", "source": "github", "line_count": 5, "max_line_length": 35, "avg_line_length": 21.8, "alnum_prop": 0.7064220183486238, "repo_name": "william-richard/moto", "id": "4af2156f76b18d6d5a42cdd2f177cc7879e22741", "size": "109", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/compat.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Dockerfile", "bytes": "443" }, { "name": "HTML", "bytes": "5848" }, { "name": "Java", "bytes": "1688" }, { "name": "JavaScript", "bytes": "756" }, { "name": "Makefile", "bytes": "1213" }, { "name": "Python", "bytes": "6637538" }, { "name": "Ruby", "bytes": "188" }, { "name": "Scala", "bytes": "782" }, { "name": "Shell", "bytes": "797" } ], "symlink_target": "" }
<Record> <Term>Optimine</Term> <SemanticType>Pharmacologic Substance</SemanticType> <SemanticType>Organic Chemical</SemanticType> <PrimarySemanticType>Pharmacologic Substance</PrimarySemanticType> <Synonym>Azatadine</Synonym> <Synonym>Azatadine maleate</Synonym> <Source>FDA Registry</Source> </Record>
{ "content_hash": "d2b1b8327fc8eedae70d07455aff549a", "timestamp": "", "source": "github", "line_count": 9, "max_line_length": 66, "avg_line_length": 34.666666666666664, "alnum_prop": 0.7980769230769231, "repo_name": "detnavillus/modular-informatic-designs", "id": "b5984020e54c815ec189c61059c15ff553c845ef", "size": "312", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "pipeline/src/test/resources/thesaurus/fdarecords/optimine.xml", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "2069134" } ], "symlink_target": "" }
/* * Copyright 2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: WriterChain.java,v 1.1.4.1 2005/09/08 10:58:44 suresh_emailid Exp $ */ package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; /** * It is unfortunate that java.io.Writer is a class rather than an interface. * The serializer has a number of classes that extend java.io.Writer * and which send their ouput to a yet another wrapped Writer or OutputStream. * * The purpose of this interface is to force such classes to over-ride all of * the important methods defined on the java.io.Writer class, namely these: * <code> * write(int val) * write(char[] chars) * write(char[] chars, int start, int count) * write(String chars) * write(String chars, int start, int count) * flush() * close() * </code> * In this manner nothing will accidentally go directly to * the base class rather than to the wrapped Writer or OutputStream. * * The purpose of this class is to have a uniform way of chaining the output of one writer to * the next writer in the chain. In addition there are methods to obtain the Writer or * OutputStream that this object sends its output to. * * This interface is only for internal use withing the serializer. * @xsl.usage internal */ interface WriterChain { /** This method forces us to over-ride the method defined in java.io.Writer */ public void write(int val) throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void write(char[] chars) throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void write(char[] chars, int start, int count) throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void write(String chars) throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void write(String chars, int start, int count) throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void flush() throws IOException; /** This method forces us to over-ride the method defined in java.io.Writer */ public void close() throws IOException; /** * If this method returns null, getOutputStream() must return non-null. * Get the writer that this writer sends its output to. * * It is possible that the Writer returned by this method does not * implement the WriterChain interface. */ public java.io.Writer getWriter(); /** * If this method returns null, getWriter() must return non-null. * Get the OutputStream that this writer sends its output to. */ public java.io.OutputStream getOutputStream(); }
{ "content_hash": "dd34905de54718ee9a5079213cbcc671", "timestamp": "", "source": "github", "line_count": 81, "max_line_length": 93, "avg_line_length": 41.48148148148148, "alnum_prop": 0.7181547619047619, "repo_name": "itgeeker/jdk", "id": "25a12d027e9f0f4ecdca899384b9a36e7eef0f4e", "size": "3515", "binary": false, "copies": "1", "ref": "refs/heads/dev", "path": "src/com/sun/org/apache/xml/internal/serializer/WriterChain.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "189890" }, { "name": "C++", "bytes": "6565" }, { "name": "Java", "bytes": "85554389" } ], "symlink_target": "" }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>ResultOfAWordToSymbolApplication - ScalaTest 2.1.1 - org.scalatest.words.ResultOfAWordToSymbolApplication</title> <meta name="description" content="ResultOfAWordToSymbolApplication - ScalaTest 2.1.1 - org.scalatest.words.ResultOfAWordToSymbolApplication" /> <meta name="keywords" content="ResultOfAWordToSymbolApplication ScalaTest 2.1.1 org.scalatest.words.ResultOfAWordToSymbolApplication" /> <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> <link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" /> <link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" /> <script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script> <script type="text/javascript" src="../../../lib/jquery-ui.js"></script> <script type="text/javascript" src="../../../lib/template.js"></script> <script type="text/javascript" src="../../../lib/tools.tooltip.js"></script> <script type="text/javascript"> if(top === self) { var url = '../../../index.html'; var hash = 'org.scalatest.words.ResultOfAWordToSymbolApplication'; var anchor = window.location.hash; var anchor_opt = ''; if (anchor.length >= 1) anchor_opt = '@' + anchor.substring(1); window.location.href = url + '#' + hash + anchor_opt; } </script> <!-- gtag [javascript] --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-71294502-1"></script> <script defer> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-71294502-1'); </script> </head> <body class="type"> <!-- Top of doc.scalatest.org [javascript] --> <script type="text/javascript"> var rnd = window.rnd || Math.floor(Math.random()*10e6); var pid204546 = window.pid204546 || rnd; var plc204546 = window.plc204546 || 0; var abkw = window.abkw || ''; var absrc = 'http://ab167933.adbutler-ikon.com/adserve/;ID=167933;size=468x60;setID=204546;type=js;sw='+screen.width+';sh='+screen.height+';spr='+window.devicePixelRatio+';kw='+abkw+';pid='+pid204546+';place='+(plc204546++)+';rnd='+rnd+';click=CLICK_MACRO_PLACEHOLDER'; document.write('<scr'+'ipt src="'+absrc+'" type="text/javascript"></scr'+'ipt>'); </script> <div id="definition"> <img src="../../../lib/class_big.png" /> <p id="owner"><a href="../../package.html" class="extype" name="org">org</a>.<a href="../package.html" class="extype" name="org.scalatest">scalatest</a>.<a href="package.html" class="extype" name="org.scalatest.words">words</a></p> <h1>ResultOfAWordToSymbolApplication</h1> </div> <h4 id="signature" class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">class</span> </span> <span class="symbol"> <span class="name">ResultOfAWordToSymbolApplication</span><span class="result"> extends <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div id="comment" class="fullcommenttop"><div class="comment cmt"><p>This class is part of the ScalaTest matchers DSL. Please see the documentation for <a href="../Matchers.html"><code>Matchers</code></a> for an overview of the matchers DSL. </p></div><dl class="attributes block"> <dt>Source</dt><dd><a href="https://github.com/scalatest/scalatest/tree/release-2.1.1-for-scala-2.10/src/main/scala/org/scalatest/words/ResultOfAWordToSymbolApplication.scala" target="_blank">ResultOfAWordToSymbolApplication.scala</a></dd></dl><div class="toggleContainer block"> <span class="toggle">Linear Supertypes</span> <div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div> </div></div> <div id="mbrsel"> <div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div> <div id="order"> <span class="filtertype">Ordering</span> <ol> <li class="alpha in"><span>Alphabetic</span></li> <li class="inherit out"><span>By inheritance</span></li> </ol> </div> <div id="ancestors"> <span class="filtertype">Inherited<br /> </span> <ol id="linearization"> <li class="in" name="org.scalatest.words.ResultOfAWordToSymbolApplication"><span>ResultOfAWordToSymbolApplication</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li> </ol> </div><div id="ancestors"> <span class="filtertype"></span> <ol> <li class="hideall out"><span>Hide All</span></li> <li class="showall in"><span>Show all</span></li> </ol> <a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a> </div> <div id="visbl"> <span class="filtertype">Visibility</span> <ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol> </div> </div> <div id="template"> <div id="allMembers"> <div id="constructors" class="members"> <h3>Instance Constructors</h3> <ol><li name="org.scalatest.words.ResultOfAWordToSymbolApplication#&lt;init&gt;" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="&lt;init&gt;(symbol:Symbol):org.scalatest.words.ResultOfAWordToSymbolApplication"></a> <a id="&lt;init&gt;:ResultOfAWordToSymbolApplication"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">new</span> </span> <span class="symbol"> <span class="name">ResultOfAWordToSymbolApplication</span><span class="params">(<span name="symbol">symbol: <span class="extype" name="scala.Symbol">Symbol</span></span>)</span> </span> </h4> </li></ol> </div> <div id="values" class="values members"> <h3>Value Members</h3> <ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:AnyRef):Boolean"></a> <a id="!=(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="!=(x$1:Any):Boolean"></a> <a id="!=(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="##():Int"></a> <a id="##():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:AnyRef):Boolean"></a> <a id="==(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.Any#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="==(x$1:Any):Boolean"></a> <a id="==(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="asInstanceOf[T0]:T0"></a> <a id="asInstanceOf[T0]:T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="clone():Object"></a> <a id="clone():AnyRef"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">java.lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="eq(x$1:AnyRef):Boolean"></a> <a id="eq(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="equals(x$1:Any):Boolean"></a> <a id="equals(Any):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="finalize():Unit"></a> <a id="finalize():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<span class="extype" name="java.lang">java.lang</span>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="getClass():Class[_]"></a> <a id="getClass():Class[_]"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="hashCode():Int"></a> <a id="hashCode():Int"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div> </li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="isInstanceOf[T0]:Boolean"></a> <a id="isInstanceOf[T0]:Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div> </li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="ne(x$1:AnyRef):Boolean"></a> <a id="ne(AnyRef):Boolean"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notify():Unit"></a> <a id="notify():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="notifyAll():Unit"></a> <a id="notifyAll():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="org.scalatest.words.ResultOfAWordToSymbolApplication#symbol" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped"> <a id="symbol:Symbol"></a> <a id="symbol:Symbol"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">val</span> </span> <span class="symbol"> <span class="name">symbol</span><span class="result">: <span class="extype" name="scala.Symbol">Symbol</span></span> </span> </h4> </li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="synchronized[T0](x$1:=&gt;T0):T0"></a> <a id="synchronized[T0](⇒T0):T0"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div> </li><li name="org.scalatest.words.ResultOfAWordToSymbolApplication#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="toString():String"></a> <a id="toString():String"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier"></span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Predef.String">String</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd><a href="" class="extype" name="org.scalatest.words.ResultOfAWordToSymbolApplication">ResultOfAWordToSymbolApplication</a> → AnyRef → Any</dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait():Unit"></a> <a id="wait():Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long,x$2:Int):Unit"></a> <a id="wait(Long,Int):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped"> <a id="wait(x$1:Long):Unit"></a> <a id="wait(Long):Unit"></a> <h4 class="signature"> <span class="modifier_kind"> <span class="modifier">final </span> <span class="kind">def</span> </span> <span class="symbol"> <span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span> </span> </h4> <div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd> <span class="name">@throws</span><span class="args">()</span> </dd></dl></div> </li></ol> </div> </div> <div id="inheritedMembers"> <div class="parent" name="scala.AnyRef"> <h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3> </div><div class="parent" name="scala.Any"> <h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3> </div> </div> <div id="groupedMembers"> <div class="group" name="Ungrouped"> <h3>Ungrouped</h3> </div> </div> </div> <div id="tooltip"></div> <div id="footer"> </div> </body> </html>
{ "content_hash": "f7ac9f98d925301b4abaf5c706e118b1", "timestamp": "", "source": "github", "line_count": 479, "max_line_length": 335, "avg_line_length": 50.592901878914404, "alnum_prop": 0.5919369480894611, "repo_name": "scalatest/scalatest-website", "id": "5b85dcc78ee8ae9a2bc9e3ca384cb9ec9e3f4086", "size": "24250", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "public/scaladoc/2.1.1/org/scalatest/words/ResultOfAWordToSymbolApplication.html", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "8401192" }, { "name": "HTML", "bytes": "4508833233" }, { "name": "JavaScript", "bytes": "12256885" }, { "name": "Procfile", "bytes": "62" }, { "name": "Scala", "bytes": "136544" } ], "symlink_target": "" }
FROM nginx ARG SERVER_NAME ARG WEBAPP_PORT ARG API_PORT ARG API_HOST ENV SERVER_NAME=$SERVER_NAME ENV API_HOST=$API_HOST ENV API_PORT=$API_PORT ENV WEBAPP_PORT=$WEBAPP_PORT ENV NGINX_CERT_DIR=/etc/nginx/cert RUN apt-get update; apt-get install -y \ openssl RUN echo "api Host: $API_HOST" RUN echo "api Port: $API_PORT" RUN echo "Webapp Port: $WEBAPP_PORT" ADD nginx.conf.template /etc/nginx/nginx.conf.template USER root RUN envsubst '$WEBAPP_PORT $API_HOST $API_PORT $SERVER_NAME' < /etc/nginx/nginx.conf.template > /etc/nginx/nginx.conf run cat /etc/nginx/nginx.conf WORKDIR $NGINX_CERT_DIR ADD cert/ $NGINX_CERT_DIR/ RUN echo "$SERVER_NAME"
{ "content_hash": "7e75a13805a45c74966db5d72521cc68", "timestamp": "", "source": "github", "line_count": 23, "max_line_length": 117, "avg_line_length": 28.217391304347824, "alnum_prop": 0.7473035439137135, "repo_name": "castlemilk/nutry-web", "id": "d94fd467adcc6a0f4944f4de8461aafd128bb9cd", "size": "649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "proxy/Dockerfile", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "1526" }, { "name": "CSS", "bytes": "388" }, { "name": "HTML", "bytes": "10287" }, { "name": "JavaScript", "bytes": "212492" } ], "symlink_target": "" }
#define BOOST_TEST_MODULE KernelGenerator #include <boost/test/unit_test.hpp> #include <boost/phoenix/phoenix.hpp> #include <vexcl/vector.hpp> #include <vexcl/generator.hpp> #include <vexcl/tagged_terminal.hpp> #include "context_setup.hpp" template <class state_type> state_type sys_func(const state_type &x) { return sin(x); } template <class state_type, class SysFunction> void runge_kutta_2(SysFunction sys, state_type &x, double dt) { state_type k1 = dt * sys(x); state_type k2 = dt * sys(x + 0.5 * k1); x += k2; } BOOST_AUTO_TEST_CASE(kernel_generator) { typedef vex::symbolic<double> sym_state; const size_t n = 1024; const double dt = 0.01; std::ostringstream body; vex::generator::set_recorder(body); sym_state sym_x(sym_state::VectorParameter); // Record expression sequence. runge_kutta_2(sys_func<sym_state>, sym_x, dt); // Build kernel. auto kernel = vex::generator::build_kernel( ctx, "rk2_stepper", body.str(), sym_x); std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) kernel(X); check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } BOOST_AUTO_TEST_CASE(kernel_generator_with_user_function) { typedef vex::symbolic<double> sym_state; const size_t n = 1024; std::ostringstream body; vex::generator::set_recorder(body); sym_state sym_x(sym_state::VectorParameter, sym_state::Const); sym_state sym_y(sym_state::VectorParameter); VEX_FUNCTION(double, sin2, (double, x), double s = sin(x); return s * s; ); sym_y = sin2(sym_x); auto kernel = vex::generator::build_kernel( ctx, "test_sin2", body.str(), sym_x, sym_y); vex::vector<double> X(ctx, random_vector<double>(n)); vex::vector<double> Y(ctx, n); for(int i = 0; i < 100; i++) kernel(X, Y); check_sample(X, Y, [&](size_t, double x, double y) { BOOST_CHECK_CLOSE(y, sin(x) * sin(x), 1e-8); }); } BOOST_AUTO_TEST_CASE(function_generator) { typedef vex::symbolic<double> sym_state; const size_t n = 1024; const double dt = 0.01; std::ostringstream body; vex::generator::set_recorder(body); sym_state sym_x(sym_state::VectorParameter); // Record expression sequence. runge_kutta_2(sys_func<sym_state>, sym_x, dt); // Build function. // Body string has to be static: static std::string function_body = vex::generator::make_function( body.str(), sym_x, sym_x); VEX_FUNCTION_S(double, rk2, (double, prm1), function_body); std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) { X = rk2(X); } check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } struct rk2_stepper { double dt; rk2_stepper(double dt) : dt(dt) {} template <class State> State operator()(const State &x) const { State new_x = x; runge_kutta_2(sys_func<State>, new_x, dt); return new_x; } }; BOOST_AUTO_TEST_CASE(function_adapter) { const size_t n = 1024; const double dt = 0.01; rk2_stepper step(dt); auto rk2 = vex::generator::make_function<double(double)>(step); std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) { X = rk2(X); } check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) s = step(s); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } BOOST_AUTO_TEST_CASE(function_adapter_and_phoenix_lambda) { using namespace boost::phoenix::arg_names; const size_t n = 1024; auto squared_radius = vex::generator::make_function<double(double, double)>( arg1 * arg1 + arg2 * arg2); vex::vector<double> X(ctx, random_vector<double>(n)); vex::vector<double> Y(ctx, random_vector<double>(n)); vex::vector<double> Z = squared_radius(X, Y); check_sample(X, Y, Z, [&](size_t, double x, double y, double z) { BOOST_CHECK_CLOSE(z, x * x + y * y, 1e-8); }); } /* An alternative variant, which does not use the generator facility. Intermediate subexpression are captured with help of 'auto' keyword, and are combined into larger expression. Note how vex::tag<>() facilitates reuse of kernel parameters. */ BOOST_AUTO_TEST_CASE(lazy_evaluation) { const size_t n = 1024; const double dt = 0.01; auto rk2 = [](vex::vector<double> &x, double dt) { auto X = vex::tag<1>(x); auto DT = vex::tag<2>(dt); auto k1 = DT * sin(X); auto x1 = X + 0.5 * k1; auto k2 = DT * sin(x1); x = X + k2; }; std::vector<double> x = random_vector<double>(n); vex::vector<double> X(ctx, x); for(int i = 0; i < 100; i++) { rk2(X, dt); } check_sample(X, [&](size_t idx, double a) { double s = x[idx]; for(int i = 0; i < 100; i++) runge_kutta_2(sys_func<double>, s, dt); BOOST_CHECK_CLOSE(a, s, 1e-8); }); } BOOST_AUTO_TEST_CASE(element_index) { const size_t n = 1024; std::vector<vex::command_queue> queue(1, ctx.queue(0)); typedef vex::symbolic<int> sym_vector; std::ostringstream body; vex::generator::set_recorder(body); sym_vector sym_x(sym_vector::VectorParameter); sym_x = vex::generator::index(); auto kernel = vex::generator::build_kernel(queue, "element_index", body.str(), sym_x); vex::vector<int> x(queue, n); kernel(x); check_sample(x, [&](size_t idx, int i) { BOOST_CHECK_EQUAL(i, idx); }); } BOOST_AUTO_TEST_SUITE_END()
{ "content_hash": "72fbc4267e8d49e0bba72af6445a64bb", "timestamp": "", "source": "github", "line_count": 242, "max_line_length": 90, "avg_line_length": 25.388429752066116, "alnum_prop": 0.5758463541666666, "repo_name": "ddemidov/vexcl", "id": "127ae8318c1ab22cb0db0e1a8bc98103ad252093", "size": "6144", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/generator.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C++", "bytes": "1845850" }, { "name": "CMake", "bytes": "29557" }, { "name": "Shell", "bytes": "1088" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{ "content_hash": "c5a80ccde7da5137b4be4fdecbe7bb81", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 39, "avg_line_length": 10.23076923076923, "alnum_prop": 0.6917293233082706, "repo_name": "mdoering/backbone", "id": "0c488c6a64d1725e146efb05433e00bfc531da17", "size": "191", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Gentianales/Rubiaceae/Lasianthus/Lasianthus helferi/ Syn. Nonatelia helferi/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, NSStringFromClass([YCHAppDelegate class])); } }
{ "content_hash": "8989ba178cb161561eb8a8ee4f22fb3a", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 93, "avg_line_length": 26.833333333333332, "alnum_prop": 0.6645962732919255, "repo_name": "Neirys/YCHActionSheet", "id": "508a304a881d2db2cdbb912d7ca4bcb125947461", "size": "365", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "Examples/YCHActionSheetExamples/main.m", "mode": "33188", "license": "mit", "language": [ { "name": "Objective-C", "bytes": "36139" }, { "name": "Ruby", "bytes": "583" } ], "symlink_target": "" }
/* Colorbox Core Style: The following CSS is consistent between example themes and should not be altered. */ #colorbox, #cboxOverlay, #cboxWrapper { position: absolute; top: 0; left: 0; z-index: 9999; overflow: hidden; } #cboxOverlay { position: fixed; width: 100%; height: 100%; } #cboxMiddleLeft, #cboxBottomLeft { clear: left; } #cboxContent { position: relative; } #cboxLoadedContent { overflow: auto; -webkit-overflow-scrolling: touch; } #cboxTitle { margin: 0; } #cboxLoadingOverlay, #cboxLoadingGraphic { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } #cboxPrevious, #cboxNext, #cboxClose, #cboxSlideshow { cursor: pointer; } .cboxPhoto { float: left; margin: auto; border: 0; display: block; max-width: none; -ms-interpolation-mode: bicubic; } .cboxIframe { width: 100%; height: 100%; display: block; border: 0; } #colorbox, #cboxContent, #cboxLoadedContent { box-sizing: content-box; -moz-box-sizing: content-box; -webkit-box-sizing: content-box; } /* User Style: Change the following styles to modify the appearance of Colorbox. They are ordered & tabbed in a way that represents the nesting of the generated HTML. */ #cboxOverlay { background: url(images/overlay.png) repeat 0 0; } #colorbox { outline: 0; } #cboxTopLeft { width: 21px; height: 21px; background: url(images/controls.png) no-repeat -101px 0; } #cboxTopRight { width: 21px; height: 21px; background: url(images/controls.png) no-repeat -130px 0; } #cboxBottomLeft { width: 21px; height: 21px; background: url(images/controls.png) no-repeat -101px -29px; } #cboxBottomRight { width: 21px; height: 21px; background: url(images/controls.png) no-repeat -130px -29px; } #cboxMiddleLeft { width: 21px; background: url(images/controls.png) left top repeat-y; } #cboxMiddleRight { width: 21px; background: url(images/controls.png) right top repeat-y; } #cboxTopCenter { height: 21px; background: url(images/border.png) 0 0 repeat-x; } #cboxBottomCenter { height: 21px; background: url(images/border.png) 0 -29px repeat-x; } #cboxContent { background: #fff; overflow: hidden; } .cboxIframe { background: #fff; } #cboxError { padding: 50px; border: 1px solid #ccc; } #cboxLoadedContent { margin-bottom: 28px; } #cboxTitle { position: absolute; bottom: 4px; left: 0; text-align: center; width: 100%; color: #949494; } #cboxCurrent { position: absolute; bottom: 4px; left: 58px; color: #949494; } #cboxLoadingOverlay { background: url(images/loading_background.png) no-repeat center center; } #cboxLoadingGraphic { background: url(images/loading.gif) no-repeat center center; } /* these elements are buttons, and may need to have additional styles reset to avoid unwanted base styles */ #cboxPrevious, #cboxNext, #cboxSlideshow, #cboxClose { border: 0; padding: 0; margin: 0; overflow: visible; width: auto; background: none; } /* avoid outlines on :active (mouseclick), but preserve outlines on :focus (tabbed navigating) */ #cboxPrevious:active, #cboxNext:active, #cboxSlideshow:active, #cboxClose:active { outline: 0; } #cboxSlideshow { position: absolute; bottom: 4px; right: 30px; color: #0092ef; } #cboxPrevious { position: absolute; bottom: 0; left: 0; background: url(images/controls.png) no-repeat -75px 0; width: 25px; height: 25px; text-indent: -9999px; } #cboxPrevious:hover { background-position: -75px -25px; } #cboxNext { position: absolute; bottom: 0; left: 27px; background: url(images/controls.png) no-repeat -50px 0; width: 25px; height: 25px; text-indent: -9999px; } #cboxNext:hover { background-position: -50px -25px; } #cboxClose { position: absolute; bottom: 0; right: 0; background: url(images/controls.png) no-repeat -25px 0; width: 25px; height: 25px; text-indent: -9999px; } #cboxClose:hover { background-position: -25px -25px; } /* The following fixes a problem where IE7 and IE8 replace a PNG's alpha transparency with a black fill when an alpha filter (opacity change) is set on the element or ancestor element. This style is not applied to or needed in IE9. See: http://jacklmoore.com/notes/ie-transparency-problems/ */ .cboxIE #cboxTopLeft, .cboxIE #cboxTopCenter, .cboxIE #cboxTopRight, .cboxIE #cboxBottomLeft, .cboxIE #cboxBottomCenter, .cboxIE #cboxBottomRight, .cboxIE #cboxMiddleLeft, .cboxIE #cboxMiddleRight { filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF, endColorstr=#00FFFFFF); }
{ "content_hash": "b199ee38be5687acdb6094df5a58294a", "timestamp": "", "source": "github", "line_count": 247, "max_line_length": 130, "avg_line_length": 20.554655870445345, "alnum_prop": 0.6334449478038211, "repo_name": "fixbugs/tips", "id": "765582d49b247072cd0411c1887aadf613d0fc07", "size": "5077", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "static/ace-admin/assets/css/colorbox.css", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "116785" }, { "name": "HTML", "bytes": "9230892" }, { "name": "JavaScript", "bytes": "76647" }, { "name": "PHP", "bytes": "2207104" }, { "name": "Shell", "bytes": "597" } ], "symlink_target": "" }
(function () { 'use strict'; angular .module('magicitems') .factory('MagicitemsService', MagicitemsService); MagicitemsService.$inject = ['$resource']; function MagicitemsService($resource) { return $resource('api/magicitems/:magicitemId', { magicitemId: '@_id' }, { update: { method: 'PUT' } }); } }());
{ "content_hash": "37ef961d425de37e59452793b41e8fc7", "timestamp": "", "source": "github", "line_count": 19, "max_line_length": 53, "avg_line_length": 19.157894736842106, "alnum_prop": 0.5796703296703297, "repo_name": "atadsp/d20cp", "id": "2e96f49e327a25e43791f73c74c0a51471177ef8", "size": "432", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/magicitems/client/services/magicitems.client.service.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1974" }, { "name": "HTML", "bytes": "119420" }, { "name": "JavaScript", "bytes": "954644" }, { "name": "Shell", "bytes": "685" } ], "symlink_target": "" }
import os, sys import numpy from itertools import permutations import tokenize import normalize import labelselect import statsify import wordselection import dictizer import split_dataset from Token import Token from parse_args import parse_args from train import maxent_classifier from train import maxent_classifier_with_validation from train import naive_bayes_classifier def main(args): print "Opening dataset..." tokens = tokenize.open_tweets_file("../data/b.tsv", 0, args.items) print "Selecting labels..." tokens = labelselect.__call__(tokens, args.labels) # Select only the labels print "Normalizing dataset..." #tokens = normalize.__call__(tokens) # Normalize the tokens if args.normalize and args.normalize_words: normalize.normalize_words(tokens) if args.normalize and args.normalize_punct: normalize.normalize_punct(tokens) if args.normalize and args.normalize_emoticons: normalize.normalize_emoticons(tokens) if args.normalize and args.normalize_users: normalize.normalize_users(tokens) if args.normalize and args.normalize_hashtags: normalize.normalize_hashtags(tokens) if args.normalize and args.normalize_nums: normalize.normalize_nums(tokens) if args.normalize and args.normalize_urls: normalize.normalize_urls(tokens) print "Transforming dataset..." feature_list = dictizer.__call__(tokens) docfreq = wordselection.calculate_docfreq(feature_list) if args.stopword_removal: print "Removing stopwords from the dataset..." feature_list = wordselection.remove_stopwords(feature_list) if args.uncommon_selection: print "Removing uncommon words from the dataset..." feature_list = wordselection.remove_uncommon(feature_list, docfreq, args.df_cutoff) wordselection.print_reatined_features(docfreq, args.df_cutoff) # Write the features out to a file with open("filtered_docs.txt", "w") as w: for row in feature_list: w.write(str(row[0]) + "\n") print "Generating feature set statistics..." statsify.__call__(feature_list, args.labels) print "Splitting the dataset..." partitions = split_dataset.partition(feature_list, args.num_folds) #print len(partitions), "Partitions" #for p in partitions: #print #for t in p: #print t #return accumulation_dict = {} if args.classifier_type == "max_ent": validation = True else: validation = False for i, fold in enumerate(generate_folds(partitions, validation)): print "Fold number: {} looks like: {}".format(i, "".join(fold)) #print fold print "Training fold", i train_set = select_set("t", fold, partitions) validation_set = select_set("v", fold, partitions) test_set = select_set("T", fold, partitions) if args.validation_metric != "none": classifier = maxent_classifier_with_validation(train_set, validation_set, args.validation_metric, 3) elif args.numIterations: classifier = maxent_classifier(train_set, iterations=args.numIterations) else: classifier = naive_bayes_classifier(train_set) print "Testing fold {}...".format(i), results_dict = classifier.test(test_set, args.labels, trace=False) #Add results to the accumulation dict for key in results_dict.keys(): try: accumulation_dict[key].append(results_dict[key]) except KeyError: accumulation_dict[key] = [results_dict[key]] print "done.\n" #classifier.show_informative_features(30) #classifier.inspect_errors(test_set) print "\n\nAccumulating Results" for key in sorted(accumulation_dict.keys(), reverse=True): print key, ":\t", accumulation_dict[key] print "{}-avg:\t".format(key), numpy.mean(accumulation_dict[key]) print "{}-std:\t".format(key), numpy.std(accumulation_dict[key]) def select_set(set_type, fold, partitions): output_set = [] for i,x in enumerate(fold): if x == set_type: output_set += partitions[i] return output_set def generate_folds(partitions, validation): num_folds = len(partitions) if validation: if num_folds == 5: sets = "tttvT" elif num_folds == 10: sets = "ttttttvvTT" else: if num_folds == 5: sets = "tttTT" elif num_folds == 10: sets = "ttttttTTTT" available = {} #range(len(partitions)) for order in permutations(sets, num_folds): try: available["".join(order)] except KeyError: available["".join(order)] = True yield order if __name__ == "__main__": args = parse_args() main(args)
{ "content_hash": "16e587a765574832d44a21d874065e7c", "timestamp": "", "source": "github", "line_count": 149, "max_line_length": 91, "avg_line_length": 32.79194630872483, "alnum_prop": 0.6426524764633648, "repo_name": "hockeybuggy/twitter-sentiment", "id": "9465a54221f32f6a81441f031376b37e2048647d", "size": "5046", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/crossval.py", "mode": "33261", "license": "mit", "language": [ { "name": "C", "bytes": "3367" }, { "name": "Python", "bytes": "34902" }, { "name": "R", "bytes": "2192" }, { "name": "TeX", "bytes": "41214" } ], "symlink_target": "" }
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in Herb. Fr. Champ. (Paris), Histoire des Champignons 1(1): 449 (1793) #### Original name Agaricus conocephalus Bull., 1793 ### Remarks null
{ "content_hash": "e714a1b2e77ff5c1d7815e5a5c877ce7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 67, "avg_line_length": 17.307692307692307, "alnum_prop": 0.7066666666666667, "repo_name": "mdoering/backbone", "id": "3d133efc741b78636da801143695c857aae7fcee", "size": "282", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Fungi/Basidiomycota/Agaricomycetes/Agaricales/Bolbitiaceae/Galerella/Galerella conocephala/ Syn. Agaricus conocephalus/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
package org.usergrid.query.validator; import org.apache.commons.lang.StringUtils; import org.codehaus.jackson.JsonNode; import org.springframework.http.HttpMethod; import org.springframework.stereotype.Component; import org.usergrid.java.client.response.ApiResponse; import org.usergrid.persistence.Entity; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.usergrid.java.client.Client; import org.usergrid.persistence.Schema; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static org.usergrid.java.client.utils.ObjectUtils.isEmpty; /** * @author Sung-ju Jin(realbeast) */ @Component public class ApiServerRunner implements QueryRunner { private Logger logger = Logger.getLogger(SqliteRunner.class.getName()); private Client client; private String org; private String app; private String baseUri; private String email; private String password; private String collection; private List<Entity> entities; @Override public boolean setup() { client = new Client(getOrg(), getApp()).withApiUrl(getBaseUri()); String accessToken = authorize(email, password); if(!StringUtils.isEmpty(accessToken)) client.setAccessToken(accessToken); return insertDatas(); } public String authorize(String email, String password) { String accessToken = null; Map<String, Object> formData = new HashMap<String, Object>(); formData.put("grant_type", "password"); formData.put("username", email); formData.put("password", password); ApiResponse response = client.apiRequest(HttpMethod.POST, null, formData, "management", "token"); if (!isEmpty(response.getAccessToken())) { accessToken = response.getAccessToken(); logger.info("Access token: " + accessToken); } else { logger.info("Response: " + response); } return accessToken; } public boolean insertDatas() { List<org.usergrid.java.client.entities.Entity> clientEntities = getEntitiesForClient(getEntities()); for(org.usergrid.java.client.entities.Entity entity : clientEntities) { ApiResponse response = client.createEntity(entity); if( response == null || !StringUtils.isEmpty(response.getError()) ) { logger.log(Level.SEVERE, response.getErrorDescription()); //throw new RuntimeException(response.getErrorDescription()); } else { logger.log(Level.INFO, response.toString()); } } return true; } private List<org.usergrid.java.client.entities.Entity> getEntitiesForClient(List<Entity> entities) { List<org.usergrid.java.client.entities.Entity> clientEntities = new ArrayList<org.usergrid.java.client.entities.Entity>(); for(Entity entity : entities) { org.usergrid.java.client.entities.Entity clientEntity = new org.usergrid.java.client.entities.Entity(); clientEntity.setType(entity.getType()); Map<String, Object> properties = Schema.getDefaultSchema().getEntityProperties(entity); for(String key : properties.keySet()) { Object value = entity.getProperty(key); if( value instanceof String ) clientEntity.setProperty(key,(String)value ); else if( value instanceof Long ) clientEntity.setProperty(key,(Long)value ); else if( value instanceof Integer ) clientEntity.setProperty(key,(Integer)value ); else if( value instanceof Float ) clientEntity.setProperty(key,(Float)value ); else if( value instanceof Boolean ) clientEntity.setProperty(key,(Boolean)value ); } clientEntities.add(clientEntity); } return clientEntities; } @Override public List<Entity> execute(String query) { return execute(query, 10); } @Override public List<Entity> execute(String query, int limit) { Map<String, Object> params = new HashMap<String, Object>(); params.put("ql", query); params.put("limit", limit); ApiResponse response = client.apiRequest(HttpMethod.GET, params, null, getOrg(), getApp(), getCollection()); List<Entity> entities = new ArrayList<Entity>(); if( response.getEntities() == null ) return entities; for(org.usergrid.java.client.entities.Entity clientEntitity : response.getEntities()) { Entity entity = new QueryEntity(); entity.setUuid(clientEntitity.getUuid()); entity.setType(clientEntitity.getType()); Map<String, JsonNode> values = clientEntitity.getProperties(); for( String key : values.keySet() ) { JsonNode node = values.get(key); if( node.isBoolean() ) { entity.setProperty(key, node.asBoolean()); } else if( node.isInt() ) { entity.setProperty(key, node.asInt()); } else if( node.isLong() ) { entity.setProperty(key, node.asLong()); } else if( node.isDouble() ) { entity.setProperty(key, node.asDouble()); } else { entity.setProperty(key, node.asText()); } } entities.add(entity); } return entities; } public String getOrg() { return org; } public void setOrg(String org) { this.org = org; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getBaseUri() { return baseUri; } public void setBaseUri(String baseUri) { this.baseUri = baseUri; } public String getCollection() { return collection; } public void setCollection(String collection) { this.collection = collection; } public List<Entity> getEntities() { return entities; } public void setEntities(List<Entity> entities) { this.entities = entities; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
{ "content_hash": "8b8e3029c51a77d2dc3710a310aad1a6", "timestamp": "", "source": "github", "line_count": 198, "max_line_length": 130, "avg_line_length": 33.515151515151516, "alnum_prop": 0.6146775165762508, "repo_name": "pgorla/usergrid", "id": "b7c573950a2729823b42173636067e1f13f17df7", "size": "7379", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "query-validator/src/main/java/org/usergrid/query/validator/ApiServerRunner.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "5666" }, { "name": "Java", "bytes": "3940092" }, { "name": "Python", "bytes": "826" }, { "name": "Shell", "bytes": "427" } ], "symlink_target": "" }