text
stringlengths
2
1.04M
meta
dict
package com.example.appengine; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.FetchOptions; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.KeyFactory; import com.google.appengine.api.datastore.PreparedQuery; import com.google.appengine.api.datastore.Query; import java.util.ArrayList; import java.util.List; public class GuestbookTestUtilities { public static void cleanDatastore(DatastoreService ds, String book) { Query query = new Query("Greeting") .setAncestor(new KeyFactory.Builder("Guestbook", book) .getKey()).setKeysOnly(); PreparedQuery pq = ds.prepare(query); List<Entity> entities = pq.asList(FetchOptions.Builder.withDefaults()); ArrayList<Key> keys = new ArrayList<>(entities.size()); for (Entity e : entities) { keys.add(e.getKey()); } ds.delete(keys); } }
{ "content_hash": "2d8d905c40aad0a8986e66b759eeede4", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 75, "avg_line_length": 31.741935483870968, "alnum_prop": 0.7439024390243902, "repo_name": "tswast/java-docs-samples", "id": "99a40b5fe49686bc817bd3d33be58e42ee7da22b", "size": "1589", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "appengine/multitenancy/src/test/java/com/example/appengine/GuestbookTestUtilities.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "348" }, { "name": "HTML", "bytes": "14365" }, { "name": "Java", "bytes": "867172" }, { "name": "Python", "bytes": "1282" }, { "name": "Shell", "bytes": "8449" }, { "name": "XSLT", "bytes": "1055" } ], "symlink_target": "" }
/* TODO(dzhioev): support RTL. http://crbug.com/423354 */ :host { display: block; overflow: auto; } core-selector { display: block; } :host([connecting]) { pointer-events: none; } paper-icon-item { padding-bottom: 18px; padding-top: 18px; } /* Items separator. */ paper-icon-item:not(:last-of-type)::after { background-color: rgba(0, 0, 0, 0.1); bottom: 0; content: ''; display: block; height: 1px; left: calc(40px + 1em); position: absolute; right: 0; } iron-icon { height: 40px; margin-right: 1em; width: 40px; } .throbber { display: none; } .iron-selected { font-weight: bold; } :host([connecting]) .iron-selected .throbber { background: url(chrome://resources/images/throbber_small.svg) no-repeat; background-size: cover; display: inline-block; height: 25px; margin-right: 10px; width: 25px; }
{ "content_hash": "ece8ee451a5611e8a95e73767d022987", "timestamp": "", "source": "github", "line_count": 57, "max_line_length": 74, "avg_line_length": 15.087719298245615, "alnum_prop": 0.6465116279069767, "repo_name": "hujiajie/chromium-crosswalk", "id": "eb2c72573d626086917bfbab8b98459f204c6d3a", "size": "1028", "binary": false, "copies": "20", "ref": "refs/heads/master", "path": "chrome/browser/resources/chromeos/login/pairing_device_list.css", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
{-# LANGUAGE QuasiQuotes #-} module LLVM.General.Quote.Test.Metadata where import Test.Tasty import Test.Tasty.HUnit import Test.HUnit import LLVM.General.Quote.LLVM import LLVM.General.AST as A import qualified LLVM.General.AST.Linkage as L import qualified LLVM.General.AST.Visibility as V import qualified LLVM.General.AST.CallingConvention as CC import qualified LLVM.General.AST.Constant as C import LLVM.General.AST.Global as G tests = testGroup "Metadata" [ testCase "local" $ do let ast = Module "<string>" Nothing Nothing [ GlobalDefinition $ globalVariableDefaults { G.name = UnName 0, G.type' = IntegerType 32 }, GlobalDefinition $ functionDefaults { G.returnType = IntegerType 32, G.name = Name "foo", G.basicBlocks = [ BasicBlock (Name "entry") [ UnName 0 := Load { volatile = False, address = ConstantOperand (C.GlobalReference (UnName 0)), maybeAtomicity = Nothing, A.alignment = 0, metadata = [] } ] ( Do $ Ret (Just (ConstantOperand (C.Int 32 0))) [ ( "my-metadatum", MetadataNode [ Just $ LocalReference (UnName 0), Just $ MetadataStringOperand "super hyper", Nothing ] ) ] ) ] } ] let s = [llmod|; ModuleID = '<string>' @0 = external global i32 define i32 @foo() { entry: %0 = load i32* @0 ret i32 0, !my-metadatum !{i32 %0, metadata !"super hyper", null} }|] s @?= ast, testCase "global" $ do let ast = Module "<string>" Nothing Nothing [ GlobalDefinition $ functionDefaults { G.returnType = IntegerType 32, G.name = Name "foo", G.basicBlocks = [ BasicBlock (Name "entry") [ ] ( Do $ Ret (Just (ConstantOperand (C.Int 32 0))) [ ("my-metadatum", MetadataNodeReference (MetadataNodeID 0)) ] ) ] }, MetadataNodeDefinition (MetadataNodeID 0) [ Just $ ConstantOperand (C.Int 32 1) ] ] let s = [llmod|; ModuleID = '<string>' define i32 @foo() { entry: ret i32 0, !my-metadatum !0 } !0 = metadata !{i32 1}|] s @?= ast, testCase "named" $ do let ast = Module "<string>" Nothing Nothing [ NamedMetadataDefinition "my-module-metadata" [ MetadataNodeID 0 ], MetadataNodeDefinition (MetadataNodeID 0) [ Just $ ConstantOperand (C.Int 32 1) ] ] let s = [llmod|; ModuleID = '<string>' !my-module-metadata = !{!0} !0 = metadata !{i32 1}|] s @?= ast, testCase "null" $ do let ast = Module "<string>" Nothing Nothing [ NamedMetadataDefinition "my-module-metadata" [ MetadataNodeID 0 ], MetadataNodeDefinition (MetadataNodeID 0) [ Nothing ] ] let s = [llmod|; ModuleID = '<string>' !my-module-metadata = !{!0} !0 = metadata !{null}|] s @?= ast, testGroup "cyclic" [ testCase "metadata-only" $ do let ast = Module "<string>" Nothing Nothing [ NamedMetadataDefinition "my-module-metadata" [MetadataNodeID 0], MetadataNodeDefinition (MetadataNodeID 0) [ Just $ MetadataNodeOperand (MetadataNodeReference (MetadataNodeID 1)) ], MetadataNodeDefinition (MetadataNodeID 1) [ Just $ MetadataNodeOperand (MetadataNodeReference (MetadataNodeID 0)) ] ] let s = [llmod|; ModuleID = '<string>' !my-module-metadata = !{!0} !0 = metadata !{metadata !1} !1 = metadata !{metadata !0}|] s @?= ast, testCase "metadata-global" $ do let ast = Module "<string>" Nothing Nothing [ GlobalDefinition $ functionDefaults { G.returnType = VoidType, G.name = Name "foo", G.basicBlocks = [ BasicBlock (Name "entry") [ ] ( Do $ Ret Nothing [ ("my-metadatum", MetadataNodeReference (MetadataNodeID 0)) ] ) ] }, MetadataNodeDefinition (MetadataNodeID 0) [ Just $ ConstantOperand (C.GlobalReference (Name "foo")) ] ] let s = [llmod|; ModuleID = '<string>' define void @foo() { entry: ret void, !my-metadatum !0 } !0 = metadata !{void ()* @foo}|] s @?= ast ] ]
{ "content_hash": "505882a504b1bf7b7ad19d6973a975e9", "timestamp": "", "source": "github", "line_count": 155, "max_line_length": 100, "avg_line_length": 32.36129032258064, "alnum_prop": 0.4958133971291866, "repo_name": "tvh/llvm-general-quote", "id": "9d2ae488fe9342f0cbbef25708bd5a86ffd470d8", "size": "5016", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "test/LLVM/General/Quote/Test/Metadata.hs", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Haskell", "bytes": "149139" }, { "name": "Logos", "bytes": "13276" }, { "name": "Yacc", "bytes": "39736" } ], "symlink_target": "" }
GLFrustum viewFrustum; GLBatch starsBatch; GLuint starFieldShader; // The point sprite shader GLint locMVP; // The location of the ModelViewProjection matrix uniform GLint locTimeStamp; // The location of the time stamp GLint locTexture; // The location of the texture uniform GLuint starTexture; // The star texture texture object // Load a TGA as a 2D Texture. Completely initialize the state bool LoadTGATexture(const char *szFileName, GLenum minFilter, GLenum magFilter, GLenum wrapMode) { GLbyte *pBits; int nWidth, nHeight, nComponents; GLenum eFormat; // Read the texture bits pBits = gltReadTGABits(szFileName, &nWidth, &nHeight, &nComponents, &eFormat); if(pBits == NULL) return false; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapMode); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glTexImage2D(GL_TEXTURE_2D, 0, nComponents, nWidth, nHeight, 0, eFormat, GL_UNSIGNED_BYTE, pBits); free(pBits); if(minFilter == GL_LINEAR_MIPMAP_LINEAR || minFilter == GL_LINEAR_MIPMAP_NEAREST || minFilter == GL_NEAREST_MIPMAP_LINEAR || minFilter == GL_NEAREST_MIPMAP_NEAREST) glGenerateMipmap(GL_TEXTURE_2D); return true; } // This function does any needed initialization on the rendering // context. void SetupRC(void) { // Background glClearColor(0.0f, 0.0f, 0.0f, 1.0f ); glEnable(GL_POINT_SPRITE); GLfloat fColors[4][4] = {{ 1.0f, 1.0f, 1.0f, 1.0f}, // White { 0.67f, 0.68f, 0.82f, 1.0f}, // Blue Stars { 1.0f, 0.5f, 0.5f, 1.0f}, // Reddish { 1.0f, 0.82f, 0.65f, 1.0f}}; // Orange // Randomly place the stars in their initial positions, and pick a random color starsBatch.Begin(GL_POINTS, NUM_STARS); for(int i = 0; i < NUM_STARS; i++) { int iColor = 0; // All stars start as white // One in five will be blue if(rand() % 5 == 1) iColor = 1; // One in 50 red if(rand() % 50 == 1) iColor = 2; // One in 100 is amber if(rand() % 100 == 1) iColor = 3; starsBatch.Color4fv(fColors[iColor]); M3DVector3f vPosition; vPosition[0] = float(3000 - (rand() % 6000)) * 0.1f; vPosition[1] = float(3000 - (rand() % 6000)) * 0.1f; vPosition[2] = -float(rand() % 1000)-1.0f; // -1 to -1000.0f starsBatch.Vertex3fv(vPosition); } starsBatch.End(); starFieldShader = gltLoadShaderPairWithAttributes("SpaceFlight.vp", "SpaceFlight.fp", 2, GLT_ATTRIBUTE_VERTEX, "vVertex", GLT_ATTRIBUTE_COLOR, "vColor"); locMVP = glGetUniformLocation(starFieldShader, "mvpMatrix"); locTexture = glGetUniformLocation(starFieldShader, "starImage"); locTimeStamp = glGetUniformLocation(starFieldShader, "timeStamp"); glGenTextures(1, &starTexture); glBindTexture(GL_TEXTURE_2D, starTexture); LoadTGATexture("Star.tga", GL_LINEAR_MIPMAP_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE); } // Cleanup void ShutdownRC(void) { glDeleteTextures(1, &starTexture); } // Called to draw scene void RenderScene(void) { static CStopWatch timer; // Clear the window and the depth buffer glClear(GL_COLOR_BUFFER_BIT); // Turn on additive blending glEnable(GL_BLEND); glBlendFunc(GL_ONE, GL_ONE); // Let the vertex program determine the point size glEnable(GL_PROGRAM_POINT_SIZE); // Bind to our shader, set uniforms glUseProgram(starFieldShader); glUniformMatrix4fv(locMVP, 1, GL_FALSE, viewFrustum.GetProjectionMatrix()); glUniform1i(locTexture, 0); // fTime goes from 0.0 to 999.0 and recycles float fTime = timer.GetElapsedSeconds() * 10.0f; fTime = fmod(fTime, 999.0f); glUniform1f(locTimeStamp, fTime); // Draw the stars starsBatch.Draw(); glutSwapBuffers(); glutPostRedisplay(); } void ChangeSize(int w, int h) { // Prevent a divide by zero if(h == 0) h = 1; // Set Viewport to window dimensions glViewport(0, 0, w, h); viewFrustum.SetPerspective(35.0f, float(w)/float(h), 1.0f, 1000.0f); } /////////////////////////////////////////////////////////////////////////////// // Main entry point for GLUT based programs int main(int argc, char* argv[]) { gltSetWorkingDirectory(argv[0]); glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL); glutInitWindowSize(800, 600); glutCreateWindow("Spaced Out"); glutReshapeFunc(ChangeSize); glutDisplayFunc(RenderScene); GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return 1; } SetupRC(); glutMainLoop(); ShutdownRC(); return 0; }
{ "content_hash": "5e48eabeeef8ccf4385d260ec645e74c", "timestamp": "", "source": "github", "line_count": 180, "max_line_length": 125, "avg_line_length": 27.1, "alnum_prop": 0.6529315293152932, "repo_name": "wjingzhe/OpenGL_SB5_static", "id": "ac26d0f19d54bc89b6c207157c444fb3374f0126", "size": "5263", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sb5Codes/Chapter07/PointSprites/PointSprites.cpp", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "2795347" }, { "name": "C++", "bytes": "1566792" }, { "name": "GLSL", "bytes": "33284" }, { "name": "HTML", "bytes": "977460" }, { "name": "JavaScript", "bytes": "4066" }, { "name": "Makefile", "bytes": "36003" }, { "name": "Shell", "bytes": "246370" } ], "symlink_target": "" }
package com.jivesoftware.os.filer.queue.store; import com.jivesoftware.os.mlogger.core.MetricLogger; import com.jivesoftware.os.mlogger.core.MetricLoggerFactory; import java.util.LinkedList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.lang.mutable.MutableLong; public class TookPhasedFileQueue { private final static MetricLogger logger = MetricLoggerFactory.getLogger(); public enum State { CONSUMEABLE, EMPTY, BUSY, FAILED } private final TwoPhasedFileQueueImpl tookFrom; private State state; private final Object stateLock = new Object(); private final UniqueOrderableFileName queueId; private final FileQueue took; private final AtomicLong approximateCount; private final AtomicLong consumedCount; private final AtomicLong processedCount; private final List<PhasedQueueEntryImpl> failures = new LinkedList<>(); private final MutableLong pending; TookPhasedFileQueue(TwoPhasedFileQueueImpl tookFrom, State state, UniqueOrderableFileName queueId, FileQueue took, AtomicLong approximateCount, MutableLong pending) { this.tookFrom = tookFrom; this.state = state; this.queueId = queueId; this.took = took; this.approximateCount = approximateCount; this.consumedCount = new AtomicLong(); this.processedCount = new AtomicLong(); this.pending = pending; } public boolean isState(State state) { synchronized (stateLock) { return this.state == state; } } public PhasedQueueEntryImpl consume() { synchronized (stateLock) { if (failures.size() > 0) { logger.warn("retrying failure message from " + tookFrom + "!"); return failures.remove(0); } if (state == State.EMPTY) { return null; } FileQueueEntry next = null; try { next = took.readNext(FileQueue.ENQEUED, FileQueue.ENQEUED); // we can leave entry as is cause the remove is the main helper } catch (Exception x) { logger.error("failed to read from queue! look for corrupt files!", x); next = null; } if (next == null) { long processed = processedCount.get(); long consumed = consumedCount.get(); logger.debug(took + " isEmpty " + processed + " out of " + consumed); state = State.EMPTY; if (processed == consumed) { // we are all done with this page tookFrom.processed(TookPhasedFileQueue.this, false); } return null; } long got = approximateCount.decrementAndGet(); pending.setValue(got); consumedCount.incrementAndGet(); return new PhasedQueueEntryImpl(next) { @Override public void processed() { //don't mark individual records when we're processing at the granularity of a full file. if (!tookFrom.isTakeFullQueuesOnly()) { super.processed(); } long processed = processedCount.incrementAndGet(); long consumed = consumedCount.get(); synchronized (stateLock) { if (state == State.EMPTY) { if (processed == consumed) { // we are all done with this page tookFrom.processed(TookPhasedFileQueue.this, false); } } } } @Override public void failed(long modeIfFailed) { super.failed(modeIfFailed); synchronized (stateLock) { failures.add(this); } } }; } } FileQueue took() { return took; } @Override public String toString() { return state + " " + took; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final TookPhasedFileQueue other = (TookPhasedFileQueue) obj; return !(this.queueId != other.queueId && (this.queueId == null || !this.queueId.equals(other.queueId))); } @Override public int hashCode() { int hash = 7; hash = 59 * hash + (this.queueId != null ? this.queueId.hashCode() : 0); return hash; } }
{ "content_hash": "17ed5facfe9a65756fd6d950667f4764", "timestamp": "", "source": "github", "line_count": 135, "max_line_length": 147, "avg_line_length": 35.34814814814815, "alnum_prop": 0.5561609388097234, "repo_name": "jivesoftware/filer", "id": "bb33722a57324c344fada2a2fc9c201450919985", "size": "4772", "binary": false, "copies": "1", "ref": "refs/heads/develop", "path": "queue-store/src/main/java/com/jivesoftware/os/filer/queue/store/TookPhasedFileQueue.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Java", "bytes": "659808" }, { "name": "Shell", "bytes": "3025" } ], "symlink_target": "" }
package org.olat.presentation.framework.core.components.form.flexible.elements; /* TODO: ORID-1007 'File' */ import java.io.File; import java.io.InputStream; import java.util.Set; import org.olat.data.commons.vfs.VFSContainer; import org.olat.data.commons.vfs.VFSLeaf; import org.olat.presentation.framework.core.components.form.flexible.FormMultipartItem; /** * <h3>Description:</h3> * <p> * The FileElement represents a file within a flexi form. It offers a read only view of files and an upload view. * <p> * Initial Date: 08.12.2008 <br> * * @author Florian Gnaegi, frentix GmbH, http://www.frentix.com */ public interface FileElement extends FormMultipartItem { public static final int UPLOAD_ONE_MEGABYTE = 1024 * 1024; // 1 Meg public static final int UPLOAD_UNLIMITED = -1; /** * Set an initial value for the file element. Optional. Use this to preload your file element with a previously submitted file. * * @param initialFile */ public void setInitialFile(File initialFile); /** * Get the initial file value * * @return the file or NULL if not set */ public File getInitialFile(); /** * Set the KB that are allowed in the file upload. In case the user uploads too much, the error with the given key will be displayed.<br /> * Use UPLOAD_UNLIMITED to set no limit. * * @param maxFileSizeKB * max file size in KB * @param i18nErrKey * i18n key used in case user uploaded to big file * @param i18nArgs * optional arguments for thei18nErrKey */ public void setMaxUploadSizeKB(int maxFileSizeKB, String i18nErrKey, String[] i18nArgs); /** * Set a mime type limitation on which files are allowed in the upload process. Wildcards like image/* are also allowed. * * @param mimeTypes * @param i18nErrKey * i18n key used in case user uploaded wrong files * @param i18nArgs * optional arguments for thei18nErrKey */ public void limitToMimeType(Set<String> mimeTypes, String i18nErrKey, String[] i18nArgs); /** * Get the set of the mime types limitation * * @return Set containing mime types. Can be empty but is never NULL. */ public Set<String> getMimeTypeLimitations(); /** * Set this form element mandatory. * * @param mandatory * true: is mandatory; false: is optional * @param i18nErrKey * i18n key used in case user did not upload something */ public void setMandatory(boolean mandatory, String i18nErrKey); // // Methods that are used when a file has been uploaded /** * @return true: file has been uploaded; false: file has not been uploaded */ public boolean isUploadSuccess(); /** * Get the size of the uploaded file * * @return */ public long getUploadSize(); /** * @return The filename of the uploaded file */ public String getUploadFileName(); /** * @return The mime type of the uploaded file */ public String getUploadMimeType(); /** * Use the upload file only for temporary checks on the file. Use the moveUploadFileTo() to move the file to the final destination. The temp file will be deleted on * form disposal. * * @return A reference to the uploaded file */ public File getUploadFile(); /** * Get the input stream of the uploaded file to copy it to some other place * * @return */ public InputStream getUploadInputStream(); /** * Move the uploaded file from the temporary location to the given destination directory. * <p> * If in the destination a file with the given name does already exist, rename the file accordingly * <p> * Whenever possible use the second moveUploadFileTo method that takes a VFSContainer as an argument instead of the file. * * @param destinationDir * @return A reference to the moved file or NULL if file could not be moved */ public File moveUploadFileTo(File destinationDir); /** * Move the uploaded file from the temporary location to the given destination VFSContainer. * <p> * If in the destination a leaf with the given name does already exist, rename the leaf accordingly * <p> * The method optimizes for containers of type LocalFolderImpl in which case the file is moved. In other cases the content is copied via the file input stream. * * @param destinationContainer * @return A reference of the new leaf file or NULL if the file could not be created */ public VFSLeaf moveUploadFileTo(VFSContainer destinationContainer); }
{ "content_hash": "9f078c0f1987d0dda5d4225b1688033e", "timestamp": "", "source": "github", "line_count": 147, "max_line_length": 168, "avg_line_length": 32.61224489795919, "alnum_prop": 0.6608260325406758, "repo_name": "huihoo/olat", "id": "690cb0a46eb6535888967cdde8720aefe1effefa", "size": "5539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "OLAT-LMS/src/main/java/org/olat/presentation/framework/core/components/form/flexible/elements/FileElement.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "24445" }, { "name": "AspectJ", "bytes": "36132" }, { "name": "CSS", "bytes": "2135670" }, { "name": "HTML", "bytes": "2950677" }, { "name": "Java", "bytes": "50804277" }, { "name": "JavaScript", "bytes": "31237972" }, { "name": "PLSQL", "bytes": "64492" }, { "name": "Perl", "bytes": "10717" }, { "name": "Shell", "bytes": "79994" }, { "name": "XSLT", "bytes": "186520" } ], "symlink_target": "" }
const int kPlayerStartX = 10; const int kPlayerStartY = 10; // These are the images for our game characters in the game const char kPlayerImage[] = "Npcs\\Player.bmp"; const char kTrendorImage[] = "Npcs\\Trendor.bmp"; // This is the direction constants that we use for moving the character enum eDirections { kUp = 0, kDown, kLeft, kRight }; // This stores the constants for the types of items to equip enum eEquipment { kEqHead = 0, kEqChest, kEqWeapon, kEqFeet }; // This is our player class class CPlayer { public: // The constructor and deconstructor CPlayer(); ~CPlayer(); // This inits the player with an image and a position void Init(HBITMAP image, int x, int y); // This draws the player to the screen void Draw(); // This moves the player according to the desired direction (kUp, kDown, kLeft, kRight) bool Move(int direction); // This restores the players previous position void MovePlayerBack() { m_position = m_lastPosition; } // These functions set the player's data void SetName(char *szPlayerName) { strcpy(m_szName, szPlayerName); } void SetHealth(int playerHealth) { m_health = playerHealth; } void SetHealthMax(int maxHealth) { m_healthMax = maxHealth; } void SetStrength(int playerStrength) { m_strength = playerStrength; } void SetProtection(int protection) { m_protection = protection; } void SetExperience(int experience) { m_experience = experience; } void SetLevel(int level) { m_level = level; } void SetGold(int gold) { m_gold = gold; } // These function retrieve info about the player int GetStrength() { return m_strength; } int GetHealth() { return m_health; } int GetHealthMax() { return m_healthMax; } int GetProtection() { return m_protection; } int GetExperience() { return m_experience; } int GetLevel() { return m_level; } int GetGold() { return m_gold; } char *GetName() { return m_szName; } // These get and set the player's image HBITMAP GetImage() { return m_image; } void SetImage(HBITMAP newImage) { m_image = newImage; } // These get and set the players position POINT GetPosition() { return m_position; } void SetPosition(POINT newPosition) { m_position = newPosition; } // These get and set the players last position POINT GetLastPosition() { return m_lastPosition; } void SetLastPosition(POINT lastPosition) { m_lastPosition = lastPosition; } // This tells us if the player is still alive or not bool IsAlive() { return (m_health > 0); } // This adds an item to our inventory void AddItem(const CItem &newItem); // This drops an item from our inventory void DropItem(CItem *pItem); // This uses and equips (if necessary) an item to the player void UseItem(CItem *pItem); // This equips an item to the player according to it's type void SetEquipment(CItem *pItem, int type); // These are get functions for our inventory int GetInventorySize() { return (int)m_vItems.size(); } CItem *GetItem(int index) { return &m_vItems[index]; } CItem *GetItem(char *szName); CItem *GetEquipment(int type); int GetItemIndex(CItem *pItem); // This safely erases an item from the inventory void EraseItemFromInventory(CItem *pItem); // This returns a pointer to our inventory list vector<CItem> *GetInventory() { return &m_vItems; } //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// // These are get functions for our party management int GetPartySize() { return (int)m_vParty.size(); } CPlayer *GetPartyMember(int index) { return m_vParty[index]; } // This adds a player to our current part void AddPlayerToParty(CPlayer *pPlayer) { m_vParty.push_back(pPlayer); } // This draws all the party members and checks if they are still breathing void UpdateParty(); // This handles the following of party members when the player moves void MoveParty(); // This attacks a monster void Attack(CMonster *pMonster); //////////// *** NEW *** ////////// *** NEW *** ///////////// *** NEW *** //////////////////// private: HBITMAP m_image; // The player's image POINT m_position; // The player's position POINT m_lastPosition; // The player's last position char m_szName[kMaxNameLen]; // The player's name int m_health; // The player's current health int m_strength; // The player's strength int m_protection; // The player's protection int m_experience; // The player's experience points int m_level; // The player's level int m_gold; // The player's gold int m_healthMax; // The player's max health CItem *m_pHead; // The current equipment on the player's head CItem *m_pChest; // The current equipment on the player's chest CItem *m_pWeapon; // The current player's weapon CItem *m_pFeet; // The current equipment on the player's feet vector<CPlayer*> m_vParty; // The list of players in your party vector<CItem> m_vItems; // The inventory list for the player }; #endif //////////////////////////////////////////////////////////////////// // // *Quick Notes* // // In this version we added a bunch of functions to handle our party // and attacking code. // // // Ben Humphrey (DigiBen) // Game Programmer // [email protected] // Co-Web Host of www.GameTutorials.com
{ "content_hash": "85d34177c99b98de065c231562224e4a", "timestamp": "", "source": "github", "line_count": 169, "max_line_length": 94, "avg_line_length": 31.733727810650887, "alnum_prop": 0.6628752563863509, "repo_name": "Ockin/tutorials", "id": "84eef4d45c120fce9e8f755bddfe9fd76f03aa50", "size": "5513", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "Win32/2D RPG Part4/Player.h", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "9550805" }, { "name": "C#", "bytes": "67823" }, { "name": "C++", "bytes": "22002901" }, { "name": "CMake", "bytes": "8502" }, { "name": "FLUX", "bytes": "81236" }, { "name": "GLSL", "bytes": "7768" }, { "name": "HCL", "bytes": "5238" }, { "name": "HTML", "bytes": "469130" }, { "name": "Java", "bytes": "99901" }, { "name": "Objective-C", "bytes": "51905" } ], "symlink_target": "" }
MAKEFLAGS=-r # The source directory tree. srcdir := .. abs_srcdir := $(abspath $(srcdir)) # The name of the builddir. builddir_name ?= . # The V=1 flag on command line makes us verbosely print command lines. ifdef V quiet= else quiet=quiet_ endif # Specify BUILDTYPE=Release on the command line for a release build. BUILDTYPE ?= Release # Directory all our build output goes into. # Note that this must be two directories beneath src/ for unit tests to pass, # as they reach into the src/ directory for data with relative paths. builddir ?= $(builddir_name)/$(BUILDTYPE) abs_builddir := $(abspath $(builddir)) depsdir := $(builddir)/.deps # Object output directory. obj := $(builddir)/obj abs_obj := $(abspath $(obj)) # We build up a list of every single one of the targets so we can slurp in the # generated dependency rule Makefiles in one pass. all_deps := CC.target ?= $(CC) CFLAGS.target ?= $(CFLAGS) CXX.target ?= $(CXX) CXXFLAGS.target ?= $(CXXFLAGS) LINK.target ?= $(LINK) LDFLAGS.target ?= $(LDFLAGS) AR.target ?= $(AR) # C++ apps need to be linked with g++. # # Note: flock is used to seralize linking. Linking is a memory-intensive # process so running parallel links can often lead to thrashing. To disable # the serialization, override LINK via an envrionment variable as follows: # # export LINK=g++ # # This will allow make to invoke N linker processes as specified in -jN. LINK ?= ./gyp-mac-tool flock $(builddir)/linker.lock $(CXX.target) # TODO(evan): move all cross-compilation logic to gyp-time so we don't need # to replicate this environment fallback in make as well. CC.host ?= gcc CFLAGS.host ?= CXX.host ?= g++ CXXFLAGS.host ?= LINK.host ?= $(CXX.host) LDFLAGS.host ?= AR.host ?= ar # Define a dir function that can handle spaces. # http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions # "leading spaces cannot appear in the text of the first argument as written. # These characters can be put into the argument value by variable substitution." empty := space := $(empty) $(empty) # http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces replace_spaces = $(subst $(space),?,$1) unreplace_spaces = $(subst ?,$(space),$1) dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) # Flags to make gcc output dependency info. Note that you need to be # careful here to use the flags that ccache and distcc can understand. # We write to a dep file on the side first and then rename at the end # so we can't end up with a broken dep file. depfile = $(depsdir)/$(call replace_spaces,$@).d DEPFLAGS = -MMD -MF $(depfile).raw # We have to fixup the deps output in a few ways. # (1) the file output should mention the proper .o file. # ccache or distcc lose the path to the target, so we convert a rule of # the form: # foobar.o: DEP1 DEP2 # into # path/to/foobar.o: DEP1 DEP2 # (2) we want missing files not to cause us to fail to build. # We want to rewrite # foobar.o: DEP1 DEP2 \ # DEP3 # to # DEP1: # DEP2: # DEP3: # so if the files are missing, they're just considered phony rules. # We have to do some pretty insane escaping to get those backslashes # and dollar signs past make, the shell, and sed at the same time. # Doesn't work with spaces, but that's fine: .d files have spaces in # their names replaced with other characters. define fixup_dep # The depfile may not exist if the input file didn't have any #includes. touch $(depfile).raw # Fixup path as in (1). sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) # Add extra rules as in (2). # We remove slashes and replace spaces with new lines; # remove blank lines; # delete the first line and append a colon to the remaining lines. sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ grep -v '^$$' |\ sed -e 1d -e 's|$$|:|' \ >> $(depfile) rm $(depfile).raw endef # Command definitions: # - cmd_foo is the actual command to run; # - quiet_cmd_foo is the brief-output summary of the command. quiet_cmd_cc = CC($(TOOLSET)) $@ cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_cxx = CXX($(TOOLSET)) $@ cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_objc = CXX($(TOOLSET)) $@ cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_objcxx = CXX($(TOOLSET)) $@ cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # Commands for precompiled header files. quiet_cmd_pch_c = CXX($(TOOLSET)) $@ cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< quiet_cmd_pch_m = CXX($(TOOLSET)) $@ cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< # gyp-mac-tool is written next to the root Makefile by gyp. # Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd # already. quiet_cmd_mac_tool = MACTOOL $(4) $< cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) quiet_cmd_infoplist = INFOPLIST $@ cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" quiet_cmd_touch = TOUCH $@ cmd_touch = touch $@ quiet_cmd_copy = COPY $@ # send stderr to /dev/null to ignore messages when linking directories. cmd_copy = rm -rf "$@" && cp -af "$<" "$@" quiet_cmd_alink = LIBTOOL-STATIC $@ cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) quiet_cmd_link = LINK($(TOOLSET)) $@ cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink = SOLINK($(TOOLSET)) $@ cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) # Define an escape_quotes function to escape single quotes. # This allows us to handle quotes properly as long as we always use # use single quotes and escape_quotes. escape_quotes = $(subst ','\'',$(1)) # This comment is here just to include a ' to unconfuse syntax highlighting. # Define an escape_vars function to escape '$' variable syntax. # This allows us to read/write command lines with shell variables (e.g. # $LD_LIBRARY_PATH), without triggering make substitution. escape_vars = $(subst $$,$$$$,$(1)) # Helper that expands to a shell command to echo a string exactly as it is in # make. This uses printf instead of echo because printf's behaviour with respect # to escape sequences is more portable than echo's across different shells # (e.g., dash, bash). exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' # Helper to compare the command we're about to run against the command # we logged the last time we ran the command. Produces an empty # string (false) when the commands match. # Tricky point: Make has no string-equality test function. # The kernel uses the following, but it seems like it would have false # positives, where one string reordered its arguments. # arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ # $(filter-out $(cmd_$@), $(cmd_$(1)))) # We instead substitute each for the empty string into the other, and # say they're equal if both substitutions produce the empty string. # .d files contain ? instead of spaces, take that into account. command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) # Helper that is non-empty when a prerequisite changes. # Normally make does this implicitly, but we force rules to always run # so we can check their command lines. # $? -- new prerequisites # $| -- order-only dependencies prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) # Helper that executes all postbuilds until one fails. define do_postbuilds @E=0;\ for p in $(POSTBUILDS); do\ eval $$p;\ E=$$?;\ if [ $$E -ne 0 ]; then\ break;\ fi;\ done;\ if [ $$E -ne 0 ]; then\ rm -rf "$@";\ exit $$E;\ fi endef # do_cmd: run a command via the above cmd_foo names, if necessary. # Should always run for a given target to handle command-line changes. # Second argument, if non-zero, makes it do asm/C/C++ dependency munging. # Third argument, if non-zero, makes it do POSTBUILDS processing. # Note: We intentionally do NOT call dirx for depfile, since it contains ? for # spaces already and dirx strips the ? characters. define do_cmd $(if $(or $(command_changed),$(prereq_changed)), @$(call exact_echo, $($(quiet)cmd_$(1))) @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" $(if $(findstring flock,$(word 2,$(cmd_$1))), @$(cmd_$(1)) @echo " $(quiet_cmd_$(1)): Finished", @$(cmd_$(1)) ) @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) @$(if $(2),$(fixup_dep)) $(if $(and $(3), $(POSTBUILDS)), $(call do_postbuilds) ) ) endef # Declare the "all" target first so it is the default, # even though we don't have the deps yet. .PHONY: all all: # make looks for ways to re-generate included makefiles, but in our case, we # don't have a direct way. Explicitly telling make that it has nothing to do # for them makes it go faster. %.d: ; # Use FORCE_DO_CMD to force a target to run. Should be coupled with # do_cmd. .PHONY: FORCE_DO_CMD FORCE_DO_CMD: TOOLSET := target # Suffix rules, putting all outputs into $(obj). $(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) # Try building from generated source, too. $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD @$(call do_cmd,cxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD @$(call do_cmd,objc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD @$(call do_cmd,objcxx,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD @$(call do_cmd,cc,1) $(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD @$(call do_cmd,cc,1) ifeq ($(strip $(foreach prefix,$(NO_LOAD),\ $(findstring $(join ^,$(prefix)),\ $(join ^,kerberos.target.mk)))),) include kerberos.target.mk endif quiet_cmd_regen_makefile = ACTION Regenerating $@ cmd_regen_makefile = cd $(srcdir); /usr/local/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py -fmake --ignore-environment "--toplevel-dir=." -I/Users/EvanHughes/Desktop/tutorials/backbone/backbone-fundamentals/book-library/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/config.gypi -I/usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi -I/Users/EvanHughes/.node-gyp/0.10.33/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/Users/EvanHughes/.node-gyp/0.10.33" "-Dmodule_root_dir=/Users/EvanHughes/Desktop/tutorials/backbone/backbone-fundamentals/book-library/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos" binding.gyp Makefile: $(srcdir)/../../../../../../../../../../../../../usr/local/lib/node_modules/npm/node_modules/node-gyp/addon.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp $(srcdir)/../../../../../../../../../../../.node-gyp/0.10.33/common.gypi $(call do_cmd,regen_makefile) # "all" is a concatenation of the "all" targets from all the included # sub-makefiles. This is just here to clarify. all: # Add in dependency-tracking rules. $(all_deps) is the list of every single # target in our tree. Only consider the ones with .d (dependency) info: d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d)) ifneq ($(d_files),) include $(d_files) endif
{ "content_hash": "74e1f3d75301a77d6cfc0f1b4d757f80", "timestamp": "", "source": "github", "line_count": 344, "max_line_length": 770, "avg_line_length": 39.15988372093023, "alnum_prop": 0.6542944102145349, "repo_name": "evanhughes3/tutorials", "id": "a432c5565c6d02459a7331bd274da76ba6829acd", "size": "13801", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "backbone/backbone-fundamentals/book-library/node_modules/mongoose/node_modules/mongodb/node_modules/kerberos/build/Makefile", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "27698" }, { "name": "CoffeeScript", "bytes": "1126" }, { "name": "HTML", "bytes": "40348" }, { "name": "JavaScript", "bytes": "1807720" }, { "name": "PHP", "bytes": "1945" }, { "name": "Ruby", "bytes": "5317" } ], "symlink_target": "" }
#ifndef nsContentDLF_h__ #define nsContentDLF_h__ #include "nsIDocumentLoaderFactory.h" #include "nsIDocumentViewer.h" #include "nsIDocument.h" #include "nsMimeTypes.h" class nsIChannel; class nsIContentViewer; class nsIDocumentViewer; class nsIFile; class nsIInputStream; class nsILoadGroup; class nsIStreamListener; #define CONTENT_DLF_CONTRACTID "@mozilla.org/content/document-loader-factory;1" #define PLUGIN_DLF_CONTRACTID "@mozilla.org/content/plugin/document-loader-factory;1" class nsContentDLF : public nsIDocumentLoaderFactory { public: nsContentDLF(); virtual ~nsContentDLF(); NS_DECL_ISUPPORTS NS_DECL_NSIDOCUMENTLOADERFACTORY nsresult InitUAStyleSheet(); nsresult CreateDocument(const char* aCommand, nsIChannel* aChannel, nsILoadGroup* aLoadGroup, nsISupports* aContainer, const nsCID& aDocumentCID, nsIStreamListener** aDocListener, nsIContentViewer** aDocViewer); nsresult CreateXULDocument(const char* aCommand, nsIChannel* aChannel, nsILoadGroup* aLoadGroup, const char* aContentType, nsISupports* aContainer, nsISupports* aExtraInfo, nsIStreamListener** aDocListener, nsIContentViewer** aDocViewer); private: static nsresult EnsureUAStyleSheet(); static PRBool IsImageContentType(const char* aContentType); }; nsresult NS_NewContentDocumentLoaderFactory(nsIDocumentLoaderFactory** aResult); #ifdef MOZ_VIEW_SOURCE #define CONTENTDLF_VIEWSOURCE_CATEGORIES \ { "Gecko-Content-Viewers", VIEWSOURCE_CONTENT_TYPE, "@mozilla.org/content/document-loader-factory;1" }, #else #define CONTENTDLF_VIEWSOURCE_CATEGORIES #endif #ifdef MOZ_MATHML #define CONTENTDLF_MATHML_CATEGORIES \ { "Gecko-Content-Viewers", APPLICATION_MATHML_XML, "@mozilla.org/content/document-loader-factory;1" }, #else #define CONTENTDLF_MATHML_CATEGORIES #endif #ifdef MOZ_SVG #define CONTENTDLF_SVG_CATEGORIES \ { "Gecko-Content-Viewers", IMAGE_SVG_XML, "@mozilla.org/content/document-loader-factory;1" }, #else #define CONTENTDLF_SVG_CATEGORIES #endif #ifdef MOZ_WEBM #define CONTENTDLF_WEBM_CATEGORIES \ { "Gecko-Content-Viewers", VIDEO_WEBM, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", AUDIO_WEBM, "@mozilla.org/content/document-loader-factory;1" }, #else #define CONTENTDLF_WEBM_CATEGORIES #endif #define CONTENTDLF_CATEGORIES \ { "Gecko-Content-Viewers", TEXT_HTML, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_PLAIN, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_CSS, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_JAVASCRIPT, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_ECMASCRIPT, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_JAVASCRIPT, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_ECMASCRIPT, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_XJAVASCRIPT, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_XHTML_XML, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_XML, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_XML, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_RDF_XML, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_RDF, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", TEXT_XUL, "@mozilla.org/content/document-loader-factory;1" }, \ { "Gecko-Content-Viewers", APPLICATION_CACHED_XUL, "@mozilla.org/content/document-loader-factory;1" }, \ CONTENTDLF_VIEWSOURCE_CATEGORIES \ CONTENTDLF_MATHML_CATEGORIES \ CONTENTDLF_SVG_CATEGORIES \ CONTENTDLF_WEBM_CATEGORIES #endif
{ "content_hash": "8e8e76ef35d953448eebfb62f4011f28", "timestamp": "", "source": "github", "line_count": 109, "max_line_length": 109, "avg_line_length": 39.84403669724771, "alnum_prop": 0.6916877734285056, "repo_name": "akiellor/selenium", "id": "98c938aa7f460d35227d23bb24a4e50c368e80c9", "size": "6121", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "third_party/gecko-2/mac/include/nsContentDLF.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "22777" }, { "name": "C", "bytes": "13787069" }, { "name": "C#", "bytes": "1592944" }, { "name": "C++", "bytes": "39839762" }, { "name": "Java", "bytes": "5948691" }, { "name": "JavaScript", "bytes": "15038006" }, { "name": "Objective-C", "bytes": "331601" }, { "name": "Python", "bytes": "544265" }, { "name": "Ruby", "bytes": "557579" }, { "name": "Shell", "bytes": "21701" } ], "symlink_target": "" }
#pragma once #include "interface/AFIPlugin.hpp" #include "interface/AFIModule.hpp" #include "base/AFPluginManager.hpp" namespace ark { ARK_DECLARE_PLUGIN(Sample4Plugin) } // namespace ark
{ "content_hash": "580ce9bbc802cb5005f79509643764a5", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 35, "avg_line_length": 14.923076923076923, "alnum_prop": 0.7628865979381443, "repo_name": "ArkGame/ArkGameFrame", "id": "d6b9afcfc2a3acbfc132a4e3f4a473d48246957d", "size": "894", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/sample4/Sample4Plugin.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "138199" }, { "name": "Batchfile", "bytes": "10057" }, { "name": "C", "bytes": "824552" }, { "name": "C#", "bytes": "1113258" }, { "name": "C++", "bytes": "2994051" }, { "name": "CLIPS", "bytes": "5291" }, { "name": "CMake", "bytes": "18168" }, { "name": "DIGITAL Command Language", "bytes": "27303" }, { "name": "Java", "bytes": "45257" }, { "name": "Lua", "bytes": "11710" }, { "name": "M4", "bytes": "1572" }, { "name": "Makefile", "bytes": "27066" }, { "name": "Module Management System", "bytes": "1545" }, { "name": "Objective-C", "bytes": "21403" }, { "name": "Pascal", "bytes": "70297" }, { "name": "Perl", "bytes": "3895" }, { "name": "Python", "bytes": "2980" }, { "name": "Roff", "bytes": "7559" }, { "name": "SAS", "bytes": "1847" }, { "name": "Shell", "bytes": "4376" } ], "symlink_target": "" }
<?php namespace Polymath\Conversions\Volume\Test; use PHPUnit_Framework_TestCase; class Volume extends PHPUnit_Framework_TestCase { /** * @dataProvider getTestLiters2GallonsData **/ public function testLiters2Gallons($liters, $expected) { $volume = new \Polymath\Conversions\Volume\Volume(); $result = $volume->liters2gallons($liters); $this->assertEquals($result, $expected, 'Convert liters to gallons'); } public function getTestLiters2GallonsData() { return array( array(1, 0.264), array(3, 0.792), array(7, 1.848) ); } /** * @dataProvider getTestGallons2LitersData **/ public function testGallons2Liters($gallons, $expected) { $volume = new \Polymath\Conversions\Volume\Volume(); $result = $volume->gallons2liters($gallons); $this->assertEquals($result, $expected, 'Convert gallons to liters'); } public function getTestGallons2LitersData() { return array( array(1, 3.78541), array(3, 11.35623), array(7, 26.49787) ); } }
{ "content_hash": "c3c6ead582a8f52bc30584fb7553f5d5", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 78, "avg_line_length": 25.282608695652176, "alnum_prop": 0.5967325881341359, "repo_name": "sanderblue/polymath", "id": "ac65072e60b3ce1c83b2f2fd524fa2de4e83f2c1", "size": "1163", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "tests/Polymath/Test/Conversions/Volume/VolumeTest.php", "mode": "33188", "license": "mit", "language": [ { "name": "PHP", "bytes": "82056" } ], "symlink_target": "" }
function isBundleCheckRequired($injector) { try { const $staticConfig = $injector.resolve('$staticConfig') const version = $staticConfig && $staticConfig.version const majorVersion = (version || '').split('.')[0] // If the major version is not available, probably we are in some new version of CLI, where the staticConfig is not available // So it definitely should work with bundle; return !majorVersion || +majorVersion < 6 } catch (err) { return false } } module.exports.isBundleCheckRequired = isBundleCheckRequired
{ "content_hash": "b60546b29e611ff6569df49d4694d707", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 129, "avg_line_length": 39.642857142857146, "alnum_prop": 0.7117117117117117, "repo_name": "rigor789/nativescript-vue", "id": "b5b4a2d155c8c1ad12ad6b669823c313b4d68052", "size": "555", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "platform/nativescript/hooks/helpers.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "414749" } ], "symlink_target": "" }
using Anycmd.Xacml.Interfaces; // ReSharper disable once CheckNamespace namespace Anycmd.Xacml.Runtime.Functions { /// <summary> /// Function implementation, in order to check the function behavior use the value of the Id /// property to search the function in the specification document. /// </summary> public class TimeAtLeastOneMemberOf : BaseAtLeastOneMemberOf { #region IFunction Members /// <summary> /// The id of the function, used only for notification. /// </summary> public override string Id { get{ return Consts.Schema1.InternalFunctions.TimeAtLeastOneMemberOf; } } /// <summary> /// Defines the data type for which the function was defined for. /// </summary> public override IDataType DataType { get{ return DataTypeDescriptor.Time; } } #endregion } }
{ "content_hash": "02fd3125d5365e7870937ed7030a845c", "timestamp": "", "source": "github", "line_count": 32, "max_line_length": 93, "avg_line_length": 25.375, "alnum_prop": 0.7216748768472906, "repo_name": "anycmd/anycmd", "id": "e7c0504c1e922c1f1c20a571da4de7007fcf26e4", "size": "812", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/Anycmd.Xacml/Runtime/Functions/Time/TimeAtLeastOneMemberOf.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "42024" }, { "name": "Batchfile", "bytes": "207" }, { "name": "C#", "bytes": "6965720" }, { "name": "CSS", "bytes": "279467" }, { "name": "HTML", "bytes": "385769" }, { "name": "Java", "bytes": "10698" }, { "name": "JavaScript", "bytes": "1311453" }, { "name": "PHP", "bytes": "92207" } ], "symlink_target": "" }
// Copyright (c) 2021 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License using System; namespace Alachisoft.NCache.Common.Communication.Exceptions { public class ConnectionException :Exception { public ConnectionException():base() { } public ConnectionException(string message) : base(message) { } public ConnectionException(string message, Exception innerException) : base(message, innerException) { } } }
{ "content_hash": "fb0180376b4e3377c5e06989f991e300", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 112, "avg_line_length": 37.69230769230769, "alnum_prop": 0.7224489795918367, "repo_name": "Alachisoft/NCache", "id": "163998fceeaf93cb54a44f8aa2164119b88db203", "size": "982", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Src/NCCommon/Communication/Exceptions/ConnectionException.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "12283536" }, { "name": "CSS", "bytes": "707" }, { "name": "HTML", "bytes": "16825" }, { "name": "JavaScript", "bytes": "377" } ], "symlink_target": "" }
from datetime import timedelta from mock import patch import re from django.test import TestCase from django.test.utils import override_settings from django.utils.timezone import now import requests from .factories import ProxyGrantingTicketFactory from .factories import ProxyTicketFactory from .factories import ServiceTicketFactory from .factories import UserFactory from mama_cas.models import ProxyGrantingTicket from mama_cas.models import ServiceTicket from mama_cas.exceptions import InvalidProxyCallback from mama_cas.exceptions import InvalidRequest from mama_cas.exceptions import InvalidService from mama_cas.exceptions import InvalidTicket from mama_cas.exceptions import UnauthorizedServiceProxy class TicketManagerTests(TestCase): """ Test the ``TicketManager`` model manager. """ url = 'http://www.example.com/' def setUp(self): self.user = UserFactory() def test_create_ticket(self): """ A ticket ought to be created with a generated ticket string. """ st = ServiceTicket.objects.create_ticket(user=self.user) self.assertTrue(re.search(st.TICKET_RE, st.ticket)) def test_create_ticket_ticket(self): """ A ticket ought to be created with a provided ticket string, if present. """ ticket = 'ST-0000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' st = ServiceTicket.objects.create_ticket(ticket=ticket, user=self.user) self.assertEqual(st.ticket, ticket) def test_create_ticket_service(self): """ If a service is provided, it should be cleaned. """ service = 'http://www.example.com/test?test3=blue#green' st = ServiceTicket.objects.create_ticket(service=service, user=self.user) self.assertEqual(st.service, 'http://www.example.com/test') def test_create_ticket_no_expires(self): """ A ticket ought to be created with a calculated expiry value. """ st = ServiceTicket.objects.create_ticket(user=self.user) self.assertTrue(st.expires > now()) def test_create_ticket_expires(self): """ A ticket ought to be created with a provided expiry value, if present. """ expires = now() + timedelta(seconds=30) st = ServiceTicket.objects.create_ticket(expires=expires, user=self.user) self.assertEqual(st.expires, expires) def test_create_ticket_str(self): """ A ticket string should be created with the appropriate model prefix and format. """ str = ServiceTicket.objects.create_ticket_str() self.assertTrue(re.search('^ST-[0-9]{10,}-[a-zA-Z0-9]{32}$', str)) def test_create_ticket_str_prefix(self): """ A ticket string should be created with the provided prefix string and format. """ str = ProxyGrantingTicket.objects.create_ticket_str(prefix='PGTIOU') self.assertTrue(re.search('^PGTIOU-[0-9]{10,}-[a-zA-Z0-9]{32}$', str)) def test_validate_ticket(self): """ Validation ought to succeed when provided with a valid ticket string and data. The ticket ought to be consumed in the process. """ st = ServiceTicketFactory() ticket = ServiceTicket.objects.validate_ticket(st.ticket, self.url) self.assertEqual(ticket, st) self.assertTrue(ticket.is_consumed()) def test_validate_ticket_no_ticket(self): """ The validation process ought to fail when no ticket string is provided. """ with self.assertRaises(InvalidRequest): ServiceTicket.objects.validate_ticket(None, self.url) def test_validate_ticket_invalid_ticket(self): """ The validation process ought to fail when an invalid ticket string is provided. """ with self.assertRaises(InvalidTicket): ServiceTicket.objects.validate_ticket('12345', self.url) def test_validate_ticket_does_not_exist(self): """ The validation process ought to fail when a valid ticket string cannot be found in the database. """ ticket = 'ST-0000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' with self.assertRaises(InvalidTicket): ServiceTicket.objects.validate_ticket(ticket, self.url) def test_validate_ticket_consumed_ticket(self): """ The validation process ought to fail when a consumed ticket is provided. """ st = ServiceTicketFactory(consume=True) with self.assertRaises(InvalidTicket): ServiceTicket.objects.validate_ticket(st.ticket, self.url) def test_validate_ticket_expired_ticket(self): """ The validation process ought to fail when an expired ticket is provided. """ st = ServiceTicketFactory(expire=True) with self.assertRaises(InvalidTicket): ServiceTicket.objects.validate_ticket(st.ticket, self.url) def test_validate_ticket_no_service(self): """ The validation process ought to fail when no service identifier is provided. The ticket ought to be consumed in the process. """ st = ServiceTicketFactory() with self.assertRaises(InvalidRequest): ServiceTicket.objects.validate_ticket(st.ticket, None) st = ServiceTicket.objects.get(ticket=st.ticket) self.assertTrue(st.is_consumed()) def test_validate_ticket_invalid_service(self): """ The validation process ought to fail when an invalid service identifier is provided. """ service = 'http://www.example.org' st = ServiceTicketFactory() with self.assertRaises(InvalidService): ServiceTicket.objects.validate_ticket(st.ticket, service) def test_validate_ticket_service_mismatch(self): """ The validation process ought to fail when the provided service identifier does not match the ticket's service. """ service = 'http://sub.example.com/' st = ServiceTicketFactory() with self.assertRaises(InvalidService): ServiceTicket.objects.validate_ticket(st.ticket, service) def test_validate_ticket_renew(self): """ When ``renew`` is set, the validation process should succeed if the ticket was issued from the presentation of the user's primary credentials. """ st = ServiceTicketFactory(primary=True) ticket = ServiceTicket.objects.validate_ticket(st.ticket, self.url, renew=True) self.assertEqual(ticket, st) def test_validate_ticket_renew_secondary(self): """ When ``renew`` is set, the validation process should fail if the ticket was not issued from the presentation of the user's primary credentials. """ st = ServiceTicketFactory() with self.assertRaises(InvalidTicket): ServiceTicket.objects.validate_ticket(st.ticket, self.url, renew=True) def test_delete_invalid_tickets(self): """ Expired or consumed tickets should be deleted. Invalid tickets referenced by other tickets should not be deleted. """ ServiceTicketFactory() # Should not be deleted expired = ServiceTicketFactory(expire=True) consumed = ServiceTicketFactory(consume=True) referenced = ServiceTicketFactory(consume=True) # Should not be deleted ProxyGrantingTicketFactory(granted_by_st=referenced) ServiceTicket.objects.delete_invalid_tickets() self.assertEqual(ServiceTicket.objects.count(), 2) self.assertRaises(ServiceTicket.DoesNotExist, ServiceTicket.objects.get, ticket=expired.ticket) self.assertRaises(ServiceTicket.DoesNotExist, ServiceTicket.objects.get, ticket=consumed.ticket) def test_consume_tickets(self): """ All tickets belonging to the specified user should be consumed. """ st1 = ServiceTicketFactory() st2 = ServiceTicketFactory() ServiceTicket.objects.consume_tickets(self.user) self.assertTrue(ServiceTicket.objects.get(ticket=st1).is_consumed()) self.assertTrue(ServiceTicket.objects.get(ticket=st2).is_consumed()) class TicketTests(TestCase): """ Test the ``Ticket`` abstract model. """ def test_ticket_consumed(self): """ ``is_consumed()`` should return ``True`` for a consumed ticket. """ st = ServiceTicketFactory() st.consume() st = ServiceTicket.objects.get(ticket=st.ticket) self.assertTrue(st.is_consumed()) def test_ticket_not_consumed(self): """ ``is_consumed()`` should return ``False`` for a valid ticket. """ st = ServiceTicketFactory() self.assertFalse(st.is_consumed()) def test_ticket_expired(self): """ ``is_expired()`` should return ``True`` for an expired ticket. """ st = ServiceTicketFactory(expire=True) self.assertTrue(st.is_expired()) def test_ticket_not_expired(self): """ ``is_expired()`` should return ``False`` for a valid ticket. """ st = ServiceTicketFactory() self.assertFalse(st.is_expired()) @override_settings(MAMA_CAS_ENABLE_SINGLE_SIGN_OUT=True) class ServiceTicketManagerTests(TestCase): """ Test the ``ServiceTicketManager`` model manager. """ def setUp(self): self.user = UserFactory() def test_request_sign_out(self): """ Calling the ``request_sign_out()`` manager method should issue a POST request for each consumed ticket for the provided user. """ ServiceTicketFactory(consume=True) ServiceTicketFactory(consume=True) with patch('requests.Session.post') as mock: mock.return_value.status_code = 200 ServiceTicket.objects.request_sign_out(self.user) self.assertEqual(mock.call_count, 2) class ServiceTicketTests(TestCase): """ Test the ``ServiceTicket`` model. """ def test_create_service_ticket(self): """ A ``ServiceTicket`` ought to be created with an appropriate prefix. """ st = ServiceTicketFactory() self.assertTrue(st.ticket.startswith(st.TICKET_PREFIX)) def test_primary(self): """ ``is_primary()`` should return ``True`` if the ``ServiceTicket`` was created from the presentation of a user's credentials. """ st = ServiceTicketFactory(primary=True) self.assertTrue(st.is_primary()) def test_secondary(self): """ ``is_primary()`` should return ``False`` if the ``ServiceTicket`` was not created from the presentation of a user's credentials. """ st = ServiceTicketFactory() self.assertFalse(st.is_primary()) def test_request_sign_out(self): """ A successful sign-out request to a service should not cause any side-effects. """ st = ServiceTicketFactory() with patch('requests.Session.post') as mock: mock.return_value.status_code = 200 st.request_sign_out() def test_request_sign_out_exception(self): """ If a sign-out request to a service raises an exception, it should be handled. """ st = ServiceTicketFactory() with patch('requests.Session.post') as mock: mock.side_effect = requests.exceptions.RequestException st.request_sign_out() def test_request_sign_out_invalid_status(self): """ If a sign-out request to a service returns an invalid status code, the resulting exception should be handled. """ st = ServiceTicketFactory() with patch('requests.Session.post') as mock: mock.return_value.status_code = 500 st.request_sign_out() def test_request_sign_out_logout_allow_false(self): """ If SLO requests are disabled for a service, the logout request should not be sent. """ st = ServiceTicketFactory(service='http://example.com') with patch('requests.Session.post') as mock: mock.return_value.status_code = 500 st.request_sign_out() self.assertEqual(mock.call_count, 0) class ProxyTicketTests(TestCase): """ Test the ``ProxyTicket`` model. """ def test_create_proxy_ticket(self): """ A ``ProxyTicket`` ought to be created with an appropriate prefix. """ pt = ProxyTicketFactory() self.assertTrue(pt.ticket.startswith(pt.TICKET_PREFIX)) class ProxyGrantingTicketManager(TestCase): """ Test the ``ProxyGrantingTicketManager`` model manager. """ def setUp(self): self.user = UserFactory() self.pt = ProxyTicketFactory() self.pgtid = ProxyGrantingTicket.objects.create_ticket_str() self.pgtiou = ProxyGrantingTicket.objects.create_ticket_str(prefix=ProxyGrantingTicket.IOU_PREFIX) def test_create_ticket(self): """ A ``ProxyGrantingTicket`` ought to be created with the appropriate ticket strings. """ with patch('requests.get') as mock: mock.return_value.status_code = 200 pgt = ProxyGrantingTicket.objects.create_ticket('https://www.example.com', 'https://www.example.com/', user=self.user, granted_by_pt=self.pt) self.assertTrue(re.search(pgt.TICKET_RE, pgt.ticket)) self.assertTrue(pgt.iou.startswith(pgt.IOU_PREFIX)) def test_create_ticket_invalid_pgturl(self): """ If callback validation fails, ``None`` should be returned instead of a ``ProxyGrantingTicket``. """ with patch('requests.get') as mock: mock.side_effect = requests.exceptions.ConnectionError pgt = ProxyGrantingTicket.objects.create_ticket('https://www.example.com', 'https://www.example.com/', user=self.user, granted_by_pt=self.pt) self.assertEqual(mock.call_count, 1) self.assertIsNone(pgt) def test_validate_callback(self): """ If a valid PGTURL is provided, an exception should not be raised. """ with patch('requests.get') as mock: mock.return_value.status_code = 200 try: ProxyGrantingTicket.objects.validate_callback('https://www.example.com', 'https://www.example.com/', self.pgtid, self.pgtiou) except InvalidProxyCallback: self.fail("Exception raised validating proxy callback URL") self.assertEqual(mock.call_count, 2) def test_validate_callback_unauthorized_service(self): """ If an unauthorized service is provided, `UnauthorizedServiceProxy` should be raised. """ with self.assertRaises(UnauthorizedServiceProxy): ProxyGrantingTicket.objects.validate_callback('http://example.com/', 'https://www.example.com/', self.pgtid, self.pgtiou) def test_validate_callback_http_pgturl(self): """ If an HTTP PGTURL is provided, InvalidProxyCallback should be raised. """ with self.assertRaises(InvalidProxyCallback): ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'http://www.example.com/', self.pgtid, self.pgtiou) def test_validate_callback_invalid_pgturl(self): """If an invalid PGTURL is provided, InvalidProxyCallback should be raised.""" with self.assertRaises(InvalidProxyCallback): ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/', self.pgtid, self.pgtiou) def test_validate_callback_ssl_error(self): """ If the validation request encounters an SSL error, an InvalidProxyCallback should be raised. """ with patch('requests.get') as mock: mock.side_effect = requests.exceptions.SSLError with self.assertRaises(InvalidProxyCallback): ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/', self.pgtid, self.pgtiou) def test_validate_callback_connection_error(self): """ If the validation request encounters an exception, an InvalidProxyCallback should be raised. """ with patch('requests.get') as mock: mock.side_effect = requests.exceptions.ConnectionError with self.assertRaises(InvalidProxyCallback): ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/', self.pgtid, self.pgtiou) def test_validate_callback_invalid_status(self): """ If the validation request returns an invalid status code, an InvalidProxyCallback should be raised. """ with patch('requests.get') as mock: mock.return_value.raise_for_status.side_effect = requests.exceptions.HTTPError with self.assertRaises(InvalidProxyCallback): ProxyGrantingTicket.objects.validate_callback('http://www.example.com/', 'https://www.example.org/', self.pgtid, self.pgtiou) def test_validate_ticket(self): """ Validation ought to succeed when provided with a valid ticket string and data. The ticket should not be consumed in the process. """ pgt = ProxyGrantingTicketFactory() ticket = ProxyGrantingTicket.objects.validate_ticket(pgt.ticket, 'https://www.example.com') self.assertEqual(ticket, pgt) self.assertFalse(ticket.is_consumed()) def test_validate_ticket_no_ticket(self): """ The validation process ought to fail when no ticket string is provided. """ with self.assertRaises(InvalidRequest): ProxyGrantingTicket.objects.validate_ticket(None, 'https://www.example.com') def test_validate_ticket_no_service(self): """ The validation process ought to fail when no service identifier is provided. """ pgt = ProxyGrantingTicketFactory() with self.assertRaises(InvalidRequest): ProxyGrantingTicket.objects.validate_ticket(pgt.ticket, None) def test_validate_ticket_invalid_ticket(self): """ The validation process ought to fail when an invalid ticket string is provided. """ with self.assertRaises(InvalidTicket): ProxyGrantingTicket.objects.validate_ticket('12345', 'https://www.example.com') def test_validate_ticket_does_not_exist(self): """ The validation process ought to fail when a valid ticket string cannot be found in the database. """ ticket = 'PGT-0000000000-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' with self.assertRaises(InvalidTicket): ProxyGrantingTicket.objects.validate_ticket(ticket, 'https://www.example.com') def test_validate_ticket_consumed_ticket(self): """ The validation process ought to fail when a consumed ticket is provided. """ pgt = ProxyGrantingTicketFactory(consume=True) with self.assertRaises(InvalidTicket): ProxyGrantingTicket.objects.validate_ticket(pgt.ticket, 'https://www.example.com') def test_validate_ticket_expired_ticket(self): """ The validation process ought to fail when an expired ticket is provided. """ pgt = ProxyGrantingTicketFactory(expire=True) with self.assertRaises(InvalidTicket): ProxyGrantingTicket.objects.validate_ticket(pgt.ticket, 'https://www.example.com') def test_validate_ticket_invalid_service(self): """ The validation process ought to fail when an invalid service identifier is provided. """ pgt = ProxyGrantingTicketFactory() with self.assertRaises(InvalidService): ProxyGrantingTicket.objects.validate_ticket(pgt.ticket, 'http://www.example.org') class ProxyGrantingTicketTests(TestCase): """ Test the ``ProxyGrantingTicket`` model. """ def test_create_proxy_granting_ticket(self): """ A ``ProxyGrantingTicket`` ought to be created with an appropriate prefix. """ pgt = ProxyGrantingTicketFactory() self.assertTrue(pgt.ticket.startswith(pgt.TICKET_PREFIX))
{ "content_hash": "b7225acafbfbf108379c3ece73f5880d", "timestamp": "", "source": "github", "line_count": 552, "max_line_length": 116, "avg_line_length": 38.68840579710145, "alnum_prop": 0.6234313541861772, "repo_name": "orbitvu/django-mama-cas", "id": "3d7cb6d447adc83f5b3a853c244d869f14d85c79", "size": "21356", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "mama_cas/tests/test_models.py", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "HTML", "bytes": "3971" }, { "name": "Python", "bytes": "164680" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>cnf: src/semicnftagger.h Source File</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javaScript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body onload='searchBox.OnSelectItem(0);'> <!-- Generated by Doxygen 1.7.1 --> <script type="text/javascript"><!-- var searchBox = new SearchBox("searchBox", "search",false,'Search'); --></script> <div class="navigation" id="top"> <div class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> <li id="searchli"> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div class="tabs2"> <ul class="tablist"> <li><a href="files.html"><span>File&nbsp;List</span></a></li> </ul> </div> <div class="header"> <div class="headertitle"> <h1>src/semicnftagger.h</h1> </div> </div> <div class="contents"> <div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <a name="l00006"></a>00006 <span class="preprocessor"># ifndef SEMI_CNF_T_H</span> <a name="l00007"></a>00007 <span class="preprocessor"></span><span class="preprocessor"># define SEMI_CNF_T_H</span> <a name="l00008"></a>00008 <span class="preprocessor"></span> <a name="l00009"></a>00009 <span class="preprocessor"># include &lt;semicnflearn.h&gt;</span> <a name="l00010"></a>00010 <span class="preprocessor"># include &lt;myutil.h&gt;</span> <a name="l00011"></a>00011 <a name="l00012"></a>00012 <span class="keyword">namespace </span>SemiCnf <a name="l00013"></a>00013 { <a name="l00014"></a><a class="code" href="struct_semi_cnf_1_1vsegment.html">00014</a> <span class="keyword">typedef</span> <span class="keyword">struct </span><a class="code" href="struct_semi_cnf_1_1vsegment.html">vsegment</a> <a name="l00015"></a>00015 { <a name="l00016"></a>00016 <span class="keywordtype">int</span> sl; <span class="comment">// segment label</span> <a name="l00017"></a>00017 <span class="keywordtype">int</span> bl; <span class="comment">// begin of local label</span> <a name="l00018"></a>00018 <span class="keywordtype">int</span> il; <span class="comment">// inside of local label</span> <a name="l00019"></a>00019 <a class="code" href="struct_semi_cnf_1_1sfeature__t.html">sfeature_t</a> us; <span class="comment">// unigram segment id</span> <a name="l00020"></a>00020 <a class="code" href="struct_semi_cnf_1_1sfeature__t.html">sfeature_t</a> bs; <span class="comment">// bigram segment id</span> <a name="l00021"></a>00021 <span class="comment">//int ut; // unigram segment template id</span> <a name="l00022"></a>00022 <span class="comment">//int bt; // bigram segment template id</span> <a name="l00023"></a>00023 <span class="keywordtype">int</span> len; <span class="comment">// length</span> <a name="l00024"></a>00024 <span class="keywordtype">float</span> _lcost; <a name="l00025"></a>00025 <a class="code" href="struct_semi_cnf_1_1vsegment.html">vsegment</a> *join; <a name="l00026"></a>00026 } <a class="code" href="struct_semi_cnf_1_1vsegment.html">vsegment_t</a>; <a name="l00027"></a>00027 <a name="l00028"></a><a class="code" href="struct_semi_cnf_1_1vnode__t.html">00028</a> <span class="keyword">typedef</span> <span class="keyword">struct</span> <a name="l00029"></a>00029 { <a name="l00030"></a>00030 std::vector&lt;vsegment_t*&gt; prev; <a name="l00031"></a>00031 std::vector&lt;vsegment_t*&gt; next; <a name="l00032"></a>00032 <a class="code" href="struct_semi_cnf_1_1feature__t.html">feature_t</a> tokenf; <a name="l00033"></a>00033 } <a class="code" href="struct_semi_cnf_1_1vnode__t.html">vnode_t</a>; <a name="l00034"></a>00034 <a name="l00035"></a><a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">00035</a> <span class="keyword">class </span><a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a> <a name="l00036"></a>00036 { <a name="l00037"></a>00037 <span class="keyword">public</span>: <a name="l00042"></a>00042 <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>(<span class="keyword">const</span> <span class="keywordtype">char</span> *tmpl, <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> pool); <a name="l00043"></a>00043 <span class="keyword">virtual</span> ~<a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>(); <a name="l00047"></a>00047 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#afeb60d68fc7bc074b5ee3526c1315010">read</a>(<span class="keyword">const</span> <span class="keywordtype">char</span> *model); <a name="l00051"></a>00051 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a6a7c43be325827a69089d6867752ebc3">tagging</a>(<span class="keyword">const</span> <span class="keywordtype">char</span> *corpus); <a name="l00057"></a>00057 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a4f4c5749ad36b1f6c886b4d3cc96058c">viterbi</a>(<a class="code" href="class_sequence.html">Sequence</a> *s, <a class="code" href="class_alloc_memdiscard.html">AllocMemdiscard</a> *cache, std::vector&lt;int&gt;&amp; labelids); <a name="l00062"></a>00062 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#ad0d08f72706b7305241944102166660d">output</a>(<a class="code" href="class_sequence.html">Sequence</a> *s, std::vector&lt;int&gt;&amp; labels); <a name="l00066"></a>00066 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a9f78d23277107c0f891b4d7f5fd1e5e6">setcache</a>(<span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> cachesize); <a name="l00071"></a>00071 <span class="keywordtype">void</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a2d275c4c88a11a2f0066d767a6dcb6ca">setsqcol</a>(<span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> sqcolsize); <a name="l00073"></a><a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a656ab4d6a8a70bcbad56276f6d067cd0">00073</a> std::vector&lt;std::string&gt; <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html#a656ab4d6a8a70bcbad56276f6d067cd0" title="label index to surface">label2surf</a>; <a name="l00074"></a>00074 <span class="keyword">private</span>: <a name="l00075"></a>00075 <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>(); <a name="l00076"></a>00076 <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>(<span class="keyword">const</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>&amp;); <a name="l00077"></a>00077 <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>&amp; operator=(<span class="keyword">const</span> <a class="code" href="class_semi_cnf_1_1_semi_cnftagger.html">SemiCnftagger</a>&amp;); <a name="l00078"></a>00078 <a name="l00080"></a>00080 <span class="keywordtype">bool</span> valid; <a name="l00082"></a>00082 <span class="keywordtype">float</span> *model; <a name="l00084"></a>00084 std::string tmpl; <a name="l00086"></a>00086 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> cachesize; <a name="l00088"></a>00088 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> llabelsize; <a name="l00090"></a>00090 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> slabelsize; <a name="l00092"></a>00092 <a class="code" href="class_dic.html">Dic</a> *ufeatures; <a name="l00094"></a>00094 <a class="code" href="class_dic.html">Dic</a> *bfeatures; <a name="l00096"></a>00096 <a class="code" href="class_dic.html">Dic</a> *usegments; <a name="l00098"></a>00098 <a class="code" href="class_dic.html">Dic</a> *bsegments; <a name="l00100"></a>00100 <a class="code" href="class_pool_alloc.html">PoolAlloc</a> *ac; <a name="l00102"></a>00102 std::vector&lt;int&gt; fwit; <a name="l00104"></a>00104 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> sqcolsize; <a name="l00106"></a>00106 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> umid; <a name="l00108"></a>00108 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bmid; <a name="l00110"></a>00110 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> usid; <a name="l00112"></a>00112 <span class="keywordtype">unsigned</span> <span class="keywordtype">int</span> bsid; <a name="l00114"></a>00114 <span class="keywordtype">void</span> mapping(<span class="keywordtype">char</span> *l, <span class="keywordtype">int</span> <span class="keywordtype">id</span>); <a name="l00115"></a>00115 <a name="l00119"></a>00119 <span class="keywordtype">bool</span> check(std::string&amp; t); <a name="l00123"></a>00123 <span class="keywordtype">bool</span> tmplcheck(); <a name="l00130"></a>00130 <span class="keywordtype">char</span>* fexpand(std::string&amp; t, <a class="code" href="class_sequence.html">Sequence</a> *s, <span class="keywordtype">int</span> current); <a name="l00138"></a>00138 <span class="keywordtype">int</span> sexpand(std::string&amp; t, <a class="code" href="class_sequence.html">Sequence</a> *s, <span class="keywordtype">int</span> current, std::vector&lt;segments_t&gt;&amp; segments); <a name="l00142"></a>00142 <span class="keywordtype">void</span> storefset(<a class="code" href="class_sequence.html">Sequence</a> *s, std::vector&lt;vnode_t&gt;&amp; lattice, <a class="code" href="class_alloc_memdiscard.html">AllocMemdiscard</a> *cache); <a name="l00146"></a>00146 <span class="keywordtype">void</span> initlattice(std::vector&lt;vnode_t&gt;&amp; lattice); <a name="l00150"></a>00150 <span class="keywordtype">int</span> getbfbias(<span class="keywordtype">bool</span> bos, <span class="keywordtype">bool</span> eos, <span class="keywordtype">int</span> label); <a name="l00151"></a>00151 <span class="keywordtype">int</span> getbsid(<span class="keywordtype">bool</span> bos, <span class="keywordtype">bool</span> eos, <span class="keywordtype">int</span> bid, <span class="keywordtype">int</span> label); <a name="l00155"></a>00155 <span class="keywordtype">float</span> getfw(<span class="keywordtype">int</span> <span class="keywordtype">id</span>, <span class="keywordtype">int</span> tmpl); <a name="l00160"></a>00160 <span class="keywordtype">float</span> getbscost(<span class="keywordtype">int</span> <span class="keywordtype">id</span>, <span class="keywordtype">int</span> tmpl, <span class="keywordtype">int</span> label); <a name="l00165"></a>00165 <span class="keywordtype">float</span> getbfcost(<a class="code" href="struct_semi_cnf_1_1feature__t.html">feature_t</a> *f, <span class="keywordtype">int</span> bias, <span class="keywordtype">int</span> label); <a name="l00166"></a>00166 <a name="l00167"></a>00167 <span class="keywordtype">void</span> readparamsize(std::string&amp; line); <a name="l00168"></a>00168 <span class="keywordtype">void</span> readllabelsize(std::string&amp; line); <a name="l00169"></a>00169 <span class="keywordtype">void</span> readslabelsize(std::string&amp; line); <a name="l00170"></a>00170 <span class="keywordtype">void</span> readllabels(std::ifstream&amp; in); <a name="l00171"></a>00171 <span class="keywordtype">void</span> readmap(std::ifstream&amp; in); <a name="l00172"></a>00172 <span class="keywordtype">void</span> readparams(std::ifstream&amp; in); <a name="l00173"></a>00173 <span class="keywordtype">void</span> readfwit(std::ifstream&amp; in); <a name="l00174"></a>00174 <span class="keywordtype">void</span> readufeatures(std::ifstream&amp; in); <a name="l00175"></a>00175 <span class="keywordtype">void</span> readbfeatures(std::ifstream&amp; in); <a name="l00176"></a>00176 <span class="keywordtype">void</span> readusegments(std::ifstream&amp; in); <a name="l00177"></a>00177 <span class="keywordtype">void</span> readbsegments(std::ifstream&amp; in); <a name="l00178"></a>00178 <a name="l00180"></a>00180 std::map&lt;int, llabel_t&gt; sl2ll; <a name="l00181"></a>00181 <span class="keywordtype">bool</span> bonly; <a name="l00182"></a>00182 <span class="keywordtype">bool</span> tonly; <a name="l00183"></a>00183 <span class="keywordtype">int</span> botmpl; <a name="l00184"></a>00184 <span class="keywordtype">int</span> totmpl; <a name="l00185"></a>00185 <span class="keywordtype">int</span> tmpli; <a name="l00186"></a>00186 <span class="keywordtype">int</span> smaxlen; <a name="l00187"></a>00187 <span class="keywordtype">int</span> slen; <a name="l00188"></a>00188 }; <a name="l00189"></a>00189 } <a name="l00190"></a>00190 <span class="preprocessor"># endif </span><span class="comment">/* SEMI_CNF_T_H */</span> </pre></div></div> </div> <!--- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&nbsp;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&nbsp;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&nbsp;</span>Namespaces</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&nbsp;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&nbsp;</span>Variables</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <hr class="footer"/><address class="footer"><small>Generated on Sat Jul 24 2010 21:38:18 for cnf by&nbsp; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.1 </small></address> </body> </html>
{ "content_hash": "2178ddb65aff15bc73ff159b4426e656", "timestamp": "", "source": "github", "line_count": 172, "max_line_length": 689, "avg_line_length": 94.16279069767442, "alnum_prop": 0.6656581872067177, "repo_name": "jiangfeng1124/cnf", "id": "3e8d84ebf372f133243c57d2c69d1bcd9f9250a1", "size": "16196", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "html/semicnftagger_8h_source.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Bison", "bytes": "7143" }, { "name": "C++", "bytes": "247469" }, { "name": "CSS", "bytes": "14917" }, { "name": "HTML", "bytes": "781812" }, { "name": "JavaScript", "bytes": "20502" }, { "name": "Makefile", "bytes": "5530" }, { "name": "Perl", "bytes": "15507" } ], "symlink_target": "" }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.techhounds.commands.driving; import com.techhounds.commands.CommandBase; import com.techhounds.subsystems.DriveSubsystem; /** * * @author TechHOUNDS */ public class SetDrivePower extends CommandBase { private DriveSubsystem drive; private double left, right; public SetDrivePower() { this(0,0); } public SetDrivePower(double left, double right) { this.left = left; this.right = right; drive = DriveSubsystem.getInstance(); requires(drive); } // Called just before this Command runs the first time protected void initialize() { drive.setPower(left, right); } // Called repeatedly when this Command is scheduled to run protected void execute() { } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
{ "content_hash": "eb6db0384cab5afa419401615b5c2d67", "timestamp": "", "source": "github", "line_count": 55, "max_line_length": 79, "avg_line_length": 25.636363636363637, "alnum_prop": 0.6375886524822695, "repo_name": "frc868/2014-robot-iri", "id": "e61520db265d6b83e99e5b015f1a2bc8e841e917", "size": "1410", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/com/techhounds/commands/driving/SetDrivePower.java", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Java", "bytes": "138143" } ], "symlink_target": "" }
val* core__flat___CString___to_s_unsafe(char* self, val* p0, val* p1, val* p2, val* p3); short int core___core__BufferedReader___Reader__eof(val* self); val* NEW_core__FlatBuffer(const struct type* type); extern const struct type type_core__FlatBuffer; #define COLOR_core___core__FlatBuffer___core__kernel__Object__init 122 void core___core__BufferedReader___Reader__append_line_to(val* self, val* p0); val* core___core__FlatBuffer___core__abstract_text__Object__to_s(val* self); val* core___core__Text___chomp(val* self); val* core___core__BufferedReader___Reader__read_all_bytes(val* self); #define COLOR_core__bytes__Bytes___length 3 #define COLOR_core__bytes__Bytes___items 2 val* core__flat___CString___clean_utf8(char* self, long p0); #define COLOR_core__abstract_text__FlatText___byte_length 5 #define COLOR_core__abstract_text__FlatText___items 3 extern const struct type type_core__Int; extern const char FILE_core__kernel[]; val* NEW_core__FlatString(const struct type* type); extern const struct type type_core__FlatString; val* core___core__FlatString___with_infos(val* self, char* p0, long p1, long p2); #define COLOR_core__abstract_text__Text___43d 39 long core___core__CString___find_beginning_of_char_at(char* self, long p0); extern const struct type type_core__ropes__Concat; val* core__ropes___core__ropes__Concat___balance(val* self); val* core__abstract_text___Char___Object__to_s(uint32_t self); void core___core__FileWriter___core__stream__Writer__write(val* self, val* p0); void core___core__FileWriter___core__stream__Writer__write_bytes(val* self, val* p0); #define COLOR_core__stream__BufferedReader___buffer_length 6 #define COLOR_core__stream__BufferedReader___buffer_pos 4 val* NEW_core__Bytes(const struct type* type); extern const struct type type_core__Bytes; void core___core__Bytes___empty(val* self); void core___core__Bytes___with_capacity(val* self, long p0); long core___core__BufferedReader___read_intern(val* self, long p0, val* p1); #define COLOR_core__stream__BufferedReader___buffer 3 void core___core__Bytes___append_ns_from(val* self, char* p0, long p1, long p2); void core___core__FileReader___core__stream__BufferedReader__fill_buffer(val* self); extern const char FILE_core__stream[]; void core___core__Bytes___core__abstract_collection__SimpleCollection__add(val* self, unsigned char p0); #define COLOR_core__file__FileReader___end_reached 8 val* core___core__Bytes___core__abstract_text__Object__to_s(val* self); #define COLOR_core__abstract_text__Buffer__append 95 #define COLOR_core__stream__BufferedReader___buffer_capacity 7
{ "content_hash": "06ada355306a3035b9fa472abe0fbce3", "timestamp": "", "source": "github", "line_count": 42, "max_line_length": 104, "avg_line_length": 61.404761904761905, "alnum_prop": 0.7223730127956572, "repo_name": "jcbrinfo/nit", "id": "494a06125aec6c0fc21f8a3c5473e482a5a8b677", "size": "2700", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "c_src/core__stream.sep.0.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Brainfuck", "bytes": "4335" }, { "name": "C", "bytes": "31365506" }, { "name": "C++", "bytes": "48" }, { "name": "CSS", "bytes": "309007" }, { "name": "Go", "bytes": "655" }, { "name": "HTML", "bytes": "68671" }, { "name": "Haskell", "bytes": "770" }, { "name": "Java", "bytes": "38594" }, { "name": "JavaScript", "bytes": "393199" }, { "name": "Makefile", "bytes": "135205" }, { "name": "Nit", "bytes": "8146776" }, { "name": "Objective-C", "bytes": "586937" }, { "name": "Pep8", "bytes": "70032" }, { "name": "Perl", "bytes": "21800" }, { "name": "Python", "bytes": "1107" }, { "name": "R", "bytes": "956" }, { "name": "Ruby", "bytes": "181" }, { "name": "Shell", "bytes": "140896" }, { "name": "Smarty", "bytes": "51" }, { "name": "TeX", "bytes": "681" }, { "name": "Vim script", "bytes": "25082" }, { "name": "XSLT", "bytes": "3225" } ], "symlink_target": "" }
require "singleton" module EmberCLI class Configuration include Singleton def app(name, options={}) apps.store name, App.new(name, options) end def apps @apps ||= HashWithIndifferentAccess.new end def tee_path return @tee_path if defined?(@tee_path) @tee_path = Helpers.which("tee") end def npm_path @npm_path ||= Helpers.which("npm") end def bundler_path @bundler_path ||= Helpers.which("bundler") end def build_timeout @build_timeout ||= 5 end attr_writer :build_timeout attr_accessor :watcher end end
{ "content_hash": "0507291d87e70497feb34a11dbf8cc78", "timestamp": "", "source": "github", "line_count": 35, "max_line_length": 48, "avg_line_length": 17.65714285714286, "alnum_prop": 0.6148867313915858, "repo_name": "KeenRegard/ember-cli-rails", "id": "19fa9238350f9312fbe9a1a837d01143da192714", "size": "618", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "lib/ember-cli/configuration.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "16271" } ], "symlink_target": "" }
package org.ehcache.impl.internal.store.offheap; import org.ehcache.Cache; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; import org.ehcache.spi.resilience.StoreAccessException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.AbstractValueHolder; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.expiry.ExpiryPolicy; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.hamcrest.TypeSafeMatcher; import org.junit.After; import org.junit.Test; import org.terracotta.context.TreeNode; import org.terracotta.context.query.QueryBuilder; import org.terracotta.statistics.OperationStatistic; import org.terracotta.statistics.StatisticsManager; import java.time.Duration; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; import static org.ehcache.impl.internal.util.Matchers.valueHeld; import static org.ehcache.impl.internal.util.StatisticsTestUtils.validateStats; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.containsInAnyOrder; import static org.hamcrest.Matchers.lessThan; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.hamcrest.MockitoHamcrest.argThat; /** * * @author cdennis */ public abstract class AbstractOffHeapStoreTest { private TestTimeSource timeSource = new TestTimeSource(); private AbstractOffHeapStore<String, String> offHeapStore; @After public void after() { if(offHeapStore != null) { destroyStore(offHeapStore); } } @Test public void testGetAndRemoveNoValue() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.MISS)); } @Test public void testGetAndRemoveValue() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); offHeapStore.put("1", "one"); assertThat(offHeapStore.getAndRemove("1").get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.HIT_REMOVED)); assertThat(offHeapStore.get("1"), is(nullValue())); } @Test public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); offHeapStore.put("1", "one"); final AtomicReference<Store.ValueHolder<String>> invalidated = new AtomicReference<>(); offHeapStore.setInvalidationListener((key, valueHolder) -> { valueHolder.get(); invalidated.set(valueHolder); }); timeSource.advanceTime(20); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); assertThat(invalidated.get().get(), equalTo("one")); assertThat(invalidated.get().isExpired(timeSource.getTimeMillis()), is(true)); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(1L)); } @Test public void testInstallMapping() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InstallMappingOutcome.PUT)); timeSource.advanceTime(20); try { offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("un", timeSource.getTimeMillis(), 15)); fail("expected AssertionError"); } catch (AssertionError ae) { // expected } } @Test public void testInvalidateKeyAbsent() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); final AtomicReference<Store.ValueHolder<String>> invalidated = new AtomicReference<>(); offHeapStore.setInvalidationListener((key, valueHolder) -> invalidated.set(valueHolder)); offHeapStore.invalidate("1"); assertThat(invalidated.get(), is(nullValue())); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InvalidateOutcome.MISS)); } @Test public void testInvalidateKeyPresent() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); final AtomicReference<Store.ValueHolder<String>> invalidated = new AtomicReference<>(); offHeapStore.setInvalidationListener((key, valueHolder) -> { valueHolder.get(); invalidated.set(valueHolder); }); offHeapStore.invalidate("1"); assertThat(invalidated.get().get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InvalidateOutcome.REMOVED)); assertThat(offHeapStore.get("1"), is(nullValue())); } @Test public void testClear() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); offHeapStore.put("2", "two"); offHeapStore.put("3", "three"); offHeapStore.clear(); assertThat(offHeapStore.get("1"), is(nullValue())); assertThat(offHeapStore.get("2"), is(nullValue())); assertThat(offHeapStore.get("3"), is(nullValue())); } @Test public void testWriteBackOfValueHolder() throws StoreAccessException { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("key1", "value1"); timeSource.advanceTime(10); OffHeapValueHolder<String> valueHolder = (OffHeapValueHolder<String>)offHeapStore.get("key1"); assertThat(valueHolder.lastAccessTime(), is(10L)); timeSource.advanceTime(10); assertThat(offHeapStore.get("key1"), notNullValue()); timeSource.advanceTime(16); assertThat(offHeapStore.get("key1"), nullValue()); } @Test public void testEvictionAdvisor() throws StoreAccessException { ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor<String, byte[]> evictionAdvisor = (key, value) -> true; performEvictionTest(timeSource, expiry, evictionAdvisor); } @Test public void testBrokenEvictionAdvisor() throws StoreAccessException { ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor<String, byte[]> evictionAdvisor = (key, value) -> { throw new UnsupportedOperationException("Broken advisor!"); }; performEvictionTest(timeSource, expiry, evictionAdvisor); } @Test public void testFlushUpdatesAccessStats() throws StoreAccessException { ExpiryPolicy<Object, Object> expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); offHeapStore = createAndInitStore(timeSource, expiry); try { final String key = "foo"; final String value = "bar"; offHeapStore.put(key, value); final Store.ValueHolder<String> firstValueHolder = offHeapStore.getAndFault(key); offHeapStore.put(key, value); final Store.ValueHolder<String> secondValueHolder = offHeapStore.getAndFault(key); timeSource.advanceTime(10); ((AbstractValueHolder) firstValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, () -> value)); timeSource.advanceTime(10); ((AbstractValueHolder) secondValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, () -> value)); assertThat(offHeapStore.flush(key, new DelegatingValueHolder<>(firstValueHolder)), is(false)); assertThat(offHeapStore.flush(key, new DelegatingValueHolder<>(secondValueHolder)), is(true)); timeSource.advanceTime(10); // this should NOT affect assertThat(offHeapStore.getAndFault(key).lastAccessTime(), is(secondValueHolder.creationTime() + 20)); } finally { destroyStore(offHeapStore); } } @Test public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessException { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); final List<String> expiredKeys = new ArrayList<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { if (event.getType() == EventType.EXPIRED) { expiredKeys.add(event.getKey()); } }); offHeapStore.put("key1", "value1"); offHeapStore.put("key2", "value2"); offHeapStore.get("key1"); // Bring the entry to the caching tier timeSource.advanceTime(11); // Expire the elements offHeapStore.get("key1"); offHeapStore.get("key2"); assertThat(expiredKeys, containsInAnyOrder("key1", "key2")); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(2L)); } @Test public void testGetWithExpiryOnAccess() throws Exception { offHeapStore = createAndInitStore(timeSource, expiry().access(Duration.ZERO).build()); offHeapStore.put("key", "value"); final AtomicReference<String> expired = new AtomicReference<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { if (event.getType() == EventType.EXPIRED) { expired.set(event.getKey()); } }); assertThat(offHeapStore.get("key"), valueHeld("value")); assertThat(expired.get(), is("key")); } @Test public void testExpiryCreateException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy<String, String>() { @Override public Duration getExpiryForCreation(String key, String value) { throw new RuntimeException(); } @Override public Duration getExpiryForAccess(String key, Supplier<? extends String> value) { throw new AssertionError(); } @Override public Duration getExpiryForUpdate(String key, Supplier<? extends String> oldValue, String newValue) { throw new AssertionError(); } }); offHeapStore.put("key", "value"); assertNull(offHeapStore.get("key")); } @Test public void testExpiryAccessException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy<String, String>() { @Override public Duration getExpiryForCreation(String key, String value) { return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForAccess(String key, Supplier<? extends String> value) { throw new RuntimeException(); } @Override public Duration getExpiryForUpdate(String key, Supplier<? extends String> oldValue, String newValue) { return null; } }); offHeapStore.put("key", "value"); assertThat(offHeapStore.get("key"), valueHeld("value")); assertNull(offHeapStore.get("key")); } @Test public void testExpiryUpdateException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy<String, String>() { @Override public Duration getExpiryForCreation(String key, String value) { return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForAccess(String key, Supplier<? extends String> value) { return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForUpdate(String key, Supplier<? extends String> oldValue, String newValue) { if (timeSource.getTimeMillis() > 0) { throw new RuntimeException(); } return ExpiryPolicy.INFINITE; } }); offHeapStore.put("key", "value"); assertThat(offHeapStore.get("key").get(), is("value")); timeSource.advanceTime(1000); offHeapStore.put("key", "newValue"); assertNull(offHeapStore.get("key")); } @Test public void testGetAndFaultOnExpiredEntry() throws StoreAccessException { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); try { offHeapStore.put("key", "value"); timeSource.advanceTime(20L); Store.ValueHolder<String> valueHolder = offHeapStore.getAndFault("key"); assertThat(valueHolder, nullValue()); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(1L)); } finally { destroyStore(offHeapStore); } } @Test public void testComputeExpiresOnAccess() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, expiry().access(Duration.ZERO).update(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder<String> result = offHeapStore.computeAndGet("key", (s, s2) -> s2, () -> false, () -> false); assertThat(result, valueHeld("value")); } @Test public void testComputeExpiresOnUpdate() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, expiry().access(Duration.ZERO).update(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder<String> result = offHeapStore.computeAndGet("key", (s, s2) -> "newValue", () -> false, () -> false); assertThat(result, valueHeld("newValue")); } @Test public void testComputeOnExpiredEntry() throws StoreAccessException { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); offHeapStore.getAndCompute("key", (mappedKey, mappedValue) -> { assertThat(mappedKey, is("key")); assertThat(mappedValue, Matchers.nullValue()); return "value2"; }); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(1L)); } @Test public void testComputeIfAbsentOnExpiredEntry() throws StoreAccessException { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); offHeapStore.computeIfAbsent("key", mappedKey -> { assertThat(mappedKey, is("key")); return "value2"; }); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(1L)); } @Test public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); offHeapStore.put("key2", "value2"); timeSource.advanceTime(11L); offHeapStore.put("key3", "value3"); offHeapStore.put("key4", "value4"); final List<String> expiredKeys = new ArrayList<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { if (event.getType() == EventType.EXPIRED) { expiredKeys.add(event.getKey()); } }); List<String> iteratedKeys = new ArrayList<>(); Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator(); while(iterator.hasNext()) { iteratedKeys.add(iterator.next().getKey()); } assertThat(iteratedKeys, containsInAnyOrder("key1", "key2", "key3", "key4")); assertThat(expiredKeys.isEmpty(), is(true)); } @Test public void testIteratorWithSingleExpiredEntry() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); timeSource.advanceTime(11L); Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next().getKey(), equalTo("key1")); assertFalse(iterator.hasNext()); } @Test public void testIteratorWithSingleNonExpiredEntry() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); timeSource.advanceTime(5L); Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator(); assertTrue(iterator.hasNext()); assertThat(iterator.next().getKey(), is("key1")); } @Test public void testIteratorOnEmptyStore() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); Store.Iterator<Cache.Entry<String, Store.ValueHolder<String>>> iterator = offHeapStore.iterator(); assertFalse(iterator.hasNext()); } protected abstract AbstractOffHeapStore<String, String> createAndInitStore(final TimeSource timeSource, final ExpiryPolicy<? super String, ? super String> expiry); protected abstract AbstractOffHeapStore<String, byte[]> createAndInitStore(final TimeSource timeSource, final ExpiryPolicy<? super String, ? super byte[]> expiry, EvictionAdvisor<? super String, ? super byte[]> evictionAdvisor); protected abstract void destroyStore(AbstractOffHeapStore<?, ?> store); private void performEvictionTest(TestTimeSource timeSource, ExpiryPolicy<Object, Object> expiry, EvictionAdvisor<String, byte[]> evictionAdvisor) throws StoreAccessException { AbstractOffHeapStore<String, byte[]> offHeapStore = createAndInitStore(timeSource, expiry, evictionAdvisor); try { @SuppressWarnings("unchecked") StoreEventListener<String, byte[]> listener = mock(StoreEventListener.class); offHeapStore.getStoreEventSource().addEventListener(listener); byte[] value = getBytes(MemoryUnit.KB.toBytes(200)); offHeapStore.put("key1", value); offHeapStore.put("key2", value); offHeapStore.put("key3", value); offHeapStore.put("key4", value); offHeapStore.put("key5", value); offHeapStore.put("key6", value); Matcher<StoreEvent<String, byte[]>> matcher = eventType(EventType.EVICTED); verify(listener, atLeast(1)).onEvent(argThat(matcher)); } finally { destroyStore(offHeapStore); } } public static <K, V> Matcher<StoreEvent<K, V>> eventType(final EventType type) { return new TypeSafeMatcher<StoreEvent<K, V>>() { @Override protected boolean matchesSafely(StoreEvent<K, V> item) { return item.getType().equals(type); } @Override public void describeTo(Description description) { description.appendText("store event of type '").appendValue(type).appendText("'"); } }; } @SuppressWarnings("unchecked") private OperationStatistic<StoreOperationOutcomes.ExpirationOutcome> getExpirationStatistic(Store<?, ?> store) { StatisticsManager statisticsManager = new StatisticsManager(); statisticsManager.root(store); TreeNode treeNode = statisticsManager.queryForSingleton(QueryBuilder.queryBuilder() .descendants() .filter(org.terracotta.context.query.Matchers.context( org.terracotta.context.query.Matchers.allOf(org.terracotta.context.query.Matchers.identifier(org.terracotta.context.query.Matchers .subclassOf(OperationStatistic.class)), org.terracotta.context.query.Matchers.attributes(org.terracotta.context.query.Matchers.hasAttribute("name", "expiration"))))) .build()); return (OperationStatistic<StoreOperationOutcomes.ExpirationOutcome>) treeNode.getContext().attributes().get("this"); } private byte[] getBytes(long valueLength) { assertThat(valueLength, lessThan((long) Integer.MAX_VALUE)); int valueLengthInt = (int) valueLength; byte[] value = new byte[valueLengthInt]; new Random().nextBytes(value); return value; } private static class TestTimeSource implements TimeSource { private long time = 0; @Override public long getTimeMillis() { return time; } public void advanceTime(long step) { time += step; } } public static class DelegatingValueHolder<T> implements Store.ValueHolder<T> { private final Store.ValueHolder<T> valueHolder; public DelegatingValueHolder(final Store.ValueHolder<T> valueHolder) { this.valueHolder = valueHolder; } @Override public T get() { return valueHolder.get(); } @Override public long creationTime() { return valueHolder.creationTime(); } @Override public long expirationTime() { return valueHolder.expirationTime(); } @Override public boolean isExpired(long expirationTime) { return valueHolder.isExpired(expirationTime); } @Override public long lastAccessTime() { return valueHolder.lastAccessTime(); } @Override public long getId() { return valueHolder.getId(); } } static class SimpleValueHolder<T> extends AbstractValueHolder<T> { private final T value; public SimpleValueHolder(T v, long creationTime, long expirationTime) { super(-1, creationTime, expirationTime); this.value = v; } @Override public T get() { return value; } @Override public long creationTime() { return 0; } @Override public long expirationTime() { return 0; } @Override public boolean isExpired(long expirationTime) { return false; } @Override public long lastAccessTime() { return 0; } @Override public long getId() { return 0; } } }
{ "content_hash": "f04680bdf6c3ba974fd3ac79b09d76e8", "timestamp": "", "source": "github", "line_count": 634, "max_line_length": 230, "avg_line_length": 36.16876971608833, "alnum_prop": 0.7250883084034713, "repo_name": "lorban/ehcache3", "id": "c7a62d5751aad5a3740dd4005fa468470f4f70a3", "size": "23525", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Groovy", "bytes": "19592" }, { "name": "Java", "bytes": "7107931" }, { "name": "Shell", "bytes": "18768" } ], "symlink_target": "" }
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- * vim: sw=2 ts=8 et : */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef mozilla_layers_ShadowLayerParent_h #define mozilla_layers_ShadowLayerParent_h #include "mozilla/layers/PLayerParent.h" namespace mozilla { namespace layers { class ContainerLayer; class Layer; class LayerManager; class ShadowLayersParent; class ShadowLayerParent : public PLayerParent { public: ShadowLayerParent(); virtual ~ShadowLayerParent(); void Bind(Layer* layer); void Destroy(); Layer* AsLayer() const { return mLayer; } ContainerLayer* AsContainer() const; private: virtual void ActorDestroy(ActorDestroyReason why) MOZ_OVERRIDE; nsRefPtr<Layer> mLayer; }; } // namespace layers } // namespace mozilla #endif // ifndef mozilla_layers_ShadowLayerParent_h
{ "content_hash": "23175a2998099d17c64102f40144f66e", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 76, "avg_line_length": 23.441860465116278, "alnum_prop": 0.7301587301587301, "repo_name": "sergecodd/FireFox-OS", "id": "e81747488e59546e82bfecaf7234ed0f72b780e9", "size": "1008", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "B2G/gecko/gfx/layers/ipc/ShadowLayerParent.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Ada", "bytes": "443" }, { "name": "ApacheConf", "bytes": "85" }, { "name": "Assembly", "bytes": "5123438" }, { "name": "Awk", "bytes": "46481" }, { "name": "Batchfile", "bytes": "56250" }, { "name": "C", "bytes": "101720951" }, { "name": "C#", "bytes": "38531" }, { "name": "C++", "bytes": "148896543" }, { "name": "CMake", "bytes": "23541" }, { "name": "CSS", "bytes": "2758664" }, { "name": "DIGITAL Command Language", "bytes": "56757" }, { "name": "Emacs Lisp", "bytes": "12694" }, { "name": "Erlang", "bytes": "889" }, { "name": "FLUX", "bytes": "34449" }, { "name": "GLSL", "bytes": "26344" }, { "name": "Gnuplot", "bytes": "710" }, { "name": "Groff", "bytes": "447012" }, { "name": "HTML", "bytes": "43343468" }, { "name": "IDL", "bytes": "1455122" }, { "name": "Java", "bytes": "43261012" }, { "name": "JavaScript", "bytes": "46646658" }, { "name": "Lex", "bytes": "38358" }, { "name": "Logos", "bytes": "21054" }, { "name": "Makefile", "bytes": "2733844" }, { "name": "Matlab", "bytes": "67316" }, { "name": "Max", "bytes": "3698" }, { "name": "NSIS", "bytes": "421625" }, { "name": "Objective-C", "bytes": "877657" }, { "name": "Objective-C++", "bytes": "737713" }, { "name": "PHP", "bytes": "17415" }, { "name": "Pascal", "bytes": "6780" }, { "name": "Perl", "bytes": "1153180" }, { "name": "Perl6", "bytes": "1255" }, { "name": "PostScript", "bytes": "1139" }, { "name": "PowerShell", "bytes": "8252" }, { "name": "Protocol Buffer", "bytes": "26553" }, { "name": "Python", "bytes": "8453201" }, { "name": "Ragel in Ruby Host", "bytes": "3481" }, { "name": "Ruby", "bytes": "5116" }, { "name": "Scilab", "bytes": "7" }, { "name": "Shell", "bytes": "3383832" }, { "name": "SourcePawn", "bytes": "23661" }, { "name": "TeX", "bytes": "879606" }, { "name": "WebIDL", "bytes": "1902" }, { "name": "XSLT", "bytes": "13134" }, { "name": "Yacc", "bytes": "112744" } ], "symlink_target": "" }
package org.apache.spark.sql.catalyst.expressions import java.lang.{Boolean => JavaBoolean} import java.lang.{Byte => JavaByte} import java.lang.{Character => JavaChar} import java.lang.{Double => JavaDouble} import java.lang.{Float => JavaFloat} import java.lang.{Integer => JavaInteger} import java.lang.{Long => JavaLong} import java.lang.{Short => JavaShort} import java.math.{BigDecimal => JavaBigDecimal} import java.nio.charset.StandardCharsets import java.sql.{Date, Timestamp} import java.time.{Duration, Instant, LocalDate, LocalDateTime, Period, ZoneOffset} import java.util import java.util.Objects import scala.math.{BigDecimal, BigInt} import scala.reflect.runtime.universe.TypeTag import scala.util.Try import org.apache.commons.codec.binary.{Hex => ApacheHex} import org.json4s.JsonAST._ import org.apache.spark.sql.catalyst.{CatalystTypeConverters, InternalRow, ScalaReflection} import org.apache.spark.sql.catalyst.expressions.codegen._ import org.apache.spark.sql.catalyst.trees.TreePattern import org.apache.spark.sql.catalyst.trees.TreePattern.{LITERAL, NULL_LITERAL, TRUE_OR_FALSE_LITERAL} import org.apache.spark.sql.catalyst.util._ import org.apache.spark.sql.catalyst.util.DateTimeUtils.instantToMicros import org.apache.spark.sql.catalyst.util.IntervalStringStyles.ANSI_STYLE import org.apache.spark.sql.catalyst.util.IntervalUtils.{durationToMicros, periodToMonths, toDayTimeIntervalString, toYearMonthIntervalString} import org.apache.spark.sql.errors.{QueryCompilationErrors, QueryExecutionErrors} import org.apache.spark.sql.internal.SQLConf import org.apache.spark.sql.types._ import org.apache.spark.unsafe.types._ import org.apache.spark.util.Utils import org.apache.spark.util.collection.BitSet import org.apache.spark.util.collection.ImmutableBitSet object Literal { val TrueLiteral: Literal = Literal(true, BooleanType) val FalseLiteral: Literal = Literal(false, BooleanType) def apply(v: Any): Literal = v match { case i: Int => Literal(i, IntegerType) case l: Long => Literal(l, LongType) case d: Double => Literal(d, DoubleType) case f: Float => Literal(f, FloatType) case b: Byte => Literal(b, ByteType) case s: Short => Literal(s, ShortType) case s: String => Literal(UTF8String.fromString(s), StringType) case c: Char => Literal(UTF8String.fromString(c.toString), StringType) case ac: Array[Char] => Literal(UTF8String.fromString(String.valueOf(ac)), StringType) case b: Boolean => Literal(b, BooleanType) case d: BigDecimal => val decimal = Decimal(d) Literal(decimal, DecimalType.fromDecimal(decimal)) case d: JavaBigDecimal => val decimal = Decimal(d) Literal(decimal, DecimalType.fromDecimal(decimal)) case d: Decimal => Literal(d, DecimalType(Math.max(d.precision, d.scale), d.scale)) case i: Instant => Literal(instantToMicros(i), TimestampType) case t: Timestamp => Literal(DateTimeUtils.fromJavaTimestamp(t), TimestampType) case l: LocalDateTime => Literal(DateTimeUtils.localDateTimeToMicros(l), TimestampNTZType) case ld: LocalDate => Literal(ld.toEpochDay.toInt, DateType) case d: Date => Literal(DateTimeUtils.fromJavaDate(d), DateType) case d: Duration => Literal(durationToMicros(d), DayTimeIntervalType()) case p: Period => Literal(periodToMonths(p), YearMonthIntervalType()) case a: Array[Byte] => Literal(a, BinaryType) case a: collection.mutable.WrappedArray[_] => apply(a.array) case a: Array[_] => val elementType = componentTypeToDataType(a.getClass.getComponentType()) val dataType = ArrayType(elementType) val convert = CatalystTypeConverters.createToCatalystConverter(dataType) Literal(convert(a), dataType) case i: CalendarInterval => Literal(i, CalendarIntervalType) case null => Literal(null, NullType) case v: Literal => v case _ => throw QueryExecutionErrors.literalTypeUnsupportedError(v) } /** * Returns the Spark SQL DataType for a given class object. Since this type needs to be resolved * in runtime, we use match-case idioms for class objects here. However, there are similar * functions in other files (e.g., HiveInspectors), so these functions need to merged into one. */ private[this] def componentTypeToDataType(clz: Class[_]): DataType = clz match { // primitive types case JavaShort.TYPE => ShortType case JavaInteger.TYPE => IntegerType case JavaLong.TYPE => LongType case JavaDouble.TYPE => DoubleType case JavaByte.TYPE => ByteType case JavaFloat.TYPE => FloatType case JavaBoolean.TYPE => BooleanType case JavaChar.TYPE => StringType // java classes case _ if clz == classOf[LocalDate] => DateType case _ if clz == classOf[Date] => DateType case _ if clz == classOf[Instant] => TimestampType case _ if clz == classOf[Timestamp] => TimestampType case _ if clz == classOf[LocalDateTime] => TimestampNTZType case _ if clz == classOf[Duration] => DayTimeIntervalType() case _ if clz == classOf[Period] => YearMonthIntervalType() case _ if clz == classOf[JavaBigDecimal] => DecimalType.SYSTEM_DEFAULT case _ if clz == classOf[Array[Byte]] => BinaryType case _ if clz == classOf[Array[Char]] => StringType case _ if clz == classOf[JavaShort] => ShortType case _ if clz == classOf[JavaInteger] => IntegerType case _ if clz == classOf[JavaLong] => LongType case _ if clz == classOf[JavaDouble] => DoubleType case _ if clz == classOf[JavaByte] => ByteType case _ if clz == classOf[JavaFloat] => FloatType case _ if clz == classOf[JavaBoolean] => BooleanType // other scala classes case _ if clz == classOf[String] => StringType case _ if clz == classOf[BigInt] => DecimalType.SYSTEM_DEFAULT case _ if clz == classOf[BigDecimal] => DecimalType.SYSTEM_DEFAULT case _ if clz == classOf[CalendarInterval] => CalendarIntervalType case _ if clz.isArray => ArrayType(componentTypeToDataType(clz.getComponentType)) case _ => throw QueryCompilationErrors.arrayComponentTypeUnsupportedError(clz) } /** * Constructs a [[Literal]] of [[ObjectType]], for example when you need to pass an object * into code generation. */ def fromObject(obj: Any, objType: DataType): Literal = new Literal(obj, objType) def fromObject(obj: Any): Literal = new Literal(obj, ObjectType(obj.getClass)) def create(v: Any, dataType: DataType): Literal = { dataType match { case _: YearMonthIntervalType if v.isInstanceOf[Period] => Literal(CatalystTypeConverters.createToCatalystConverter(dataType)(v), dataType) case _: DayTimeIntervalType if v.isInstanceOf[Duration] => Literal(CatalystTypeConverters.createToCatalystConverter(dataType)(v), dataType) case _ => Literal(CatalystTypeConverters.convertToCatalyst(v), dataType) } } def create[T : TypeTag](v: T): Literal = Try { val ScalaReflection.Schema(dataType, _) = ScalaReflection.schemaFor[T] val convert = CatalystTypeConverters.createToCatalystConverter(dataType) Literal(convert(v), dataType) }.getOrElse { Literal(v) } /** * Create a literal with default value for given DataType */ def default(dataType: DataType): Literal = dataType match { case NullType => create(null, NullType) case BooleanType => Literal(false) case ByteType => Literal(0.toByte) case ShortType => Literal(0.toShort) case IntegerType => Literal(0) case LongType => Literal(0L) case FloatType => Literal(0.0f) case DoubleType => Literal(0.0) case dt: DecimalType => Literal(Decimal(0, dt.precision, dt.scale)) case DateType => create(0, DateType) case TimestampType => create(0L, TimestampType) case TimestampNTZType => create(0L, TimestampNTZType) case it: DayTimeIntervalType => create(0L, it) case it: YearMonthIntervalType => create(0, it) case StringType => Literal("") case BinaryType => Literal("".getBytes(StandardCharsets.UTF_8)) case CalendarIntervalType => Literal(new CalendarInterval(0, 0, 0)) case arr: ArrayType => create(Array(), arr) case map: MapType => create(Map(), map) case struct: StructType => create(InternalRow.fromSeq(struct.fields.map(f => default(f.dataType).value)), struct) case udt: UserDefinedType[_] => Literal(default(udt.sqlType).value, udt) case other => throw QueryExecutionErrors.noDefaultForDataTypeError(dataType) } private[expressions] def validateLiteralValue(value: Any, dataType: DataType): Unit = { def doValidate(v: Any, dataType: DataType): Boolean = dataType match { case _ if v == null => true case BooleanType => v.isInstanceOf[Boolean] case ByteType => v.isInstanceOf[Byte] case ShortType => v.isInstanceOf[Short] case IntegerType | DateType | _: YearMonthIntervalType => v.isInstanceOf[Int] case LongType | TimestampType | TimestampNTZType | _: DayTimeIntervalType => v.isInstanceOf[Long] case FloatType => v.isInstanceOf[Float] case DoubleType => v.isInstanceOf[Double] case _: DecimalType => v.isInstanceOf[Decimal] case CalendarIntervalType => v.isInstanceOf[CalendarInterval] case BinaryType => v.isInstanceOf[Array[Byte]] case StringType => v.isInstanceOf[UTF8String] case st: StructType => v.isInstanceOf[InternalRow] && { val row = v.asInstanceOf[InternalRow] st.fields.map(_.dataType).zipWithIndex.forall { case (dt, i) => doValidate(row.get(i, dt), dt) } } case at: ArrayType => v.isInstanceOf[ArrayData] && { val ar = v.asInstanceOf[ArrayData] ar.numElements() == 0 || doValidate(ar.get(0, at.elementType), at.elementType) } case mt: MapType => v.isInstanceOf[MapData] && { val map = v.asInstanceOf[MapData] doValidate(map.keyArray(), ArrayType(mt.keyType)) && doValidate(map.valueArray(), ArrayType(mt.valueType)) } case ObjectType(cls) => cls.isInstance(v) case udt: UserDefinedType[_] => doValidate(v, udt.sqlType) case _ => false } require(doValidate(value, dataType), s"Literal must have a corresponding value to ${dataType.catalogString}, " + s"but class ${Utils.getSimpleName(value.getClass)} found.") } } /** * An extractor that matches non-null literal values */ object NonNullLiteral { def unapply(literal: Literal): Option[(Any, DataType)] = { Option(literal.value).map(_ => (literal.value, literal.dataType)) } } /** * Extractor for retrieving Float literals. */ object FloatLiteral { def unapply(a: Any): Option[Float] = a match { case Literal(a: Float, FloatType) => Some(a) case _ => None } } /** * Extractor for retrieving Double literals. */ object DoubleLiteral { def unapply(a: Any): Option[Double] = a match { case Literal(a: Double, DoubleType) => Some(a) case _ => None } } /** * Extractor for retrieving Int literals. */ object IntegerLiteral { def unapply(a: Any): Option[Int] = a match { case Literal(a: Int, IntegerType) => Some(a) case _ => None } } /** * Extractor for retrieving String literals. */ object StringLiteral { def unapply(a: Any): Option[String] = a match { case Literal(s: UTF8String, StringType) => Some(s.toString) case _ => None } } /** * Extractor for and other utility methods for decimal literals. */ object DecimalLiteral { def apply(v: Long): Literal = Literal(Decimal(v)) def apply(v: Double): Literal = Literal(Decimal(v)) def unapply(e: Expression): Option[Decimal] = e match { case Literal(v, _: DecimalType) => Some(v.asInstanceOf[Decimal]) case _ => None } def largerThanLargestLong(v: Decimal): Boolean = v > Decimal(Long.MaxValue) def smallerThanSmallestLong(v: Decimal): Boolean = v < Decimal(Long.MinValue) } object LiteralTreeBits { // Singleton tree pattern BitSet for all Literals that are not true, false, or null. val literalBits: BitSet = new ImmutableBitSet(TreePattern.maxId, LITERAL.id) // Singleton tree pattern BitSet for all Literals that are true or false. val booleanLiteralBits: BitSet = new ImmutableBitSet( TreePattern.maxId, LITERAL.id, TRUE_OR_FALSE_LITERAL.id) // Singleton tree pattern BitSet for all Literals that are nulls. val nullLiteralBits: BitSet = new ImmutableBitSet(TreePattern.maxId, LITERAL.id, NULL_LITERAL.id) } /** * In order to do type checking, use Literal.create() instead of constructor */ case class Literal (value: Any, dataType: DataType) extends LeafExpression { Literal.validateLiteralValue(value, dataType) override def foldable: Boolean = true override def nullable: Boolean = value == null private def timeZoneId = DateTimeUtils.getZoneId(SQLConf.get.sessionLocalTimeZone) override lazy val treePatternBits: BitSet = { value match { case null => LiteralTreeBits.nullLiteralBits case true | false => LiteralTreeBits.booleanLiteralBits case _ => LiteralTreeBits.literalBits } } override def toString: String = value match { case null => "null" case binary: Array[Byte] => s"0x" + ApacheHex.encodeHexString(binary, false) case d: ArrayBasedMapData => s"map(${d.toString})" case other => dataType match { case DateType => DateFormatter().format(value.asInstanceOf[Int]) case TimestampType => TimestampFormatter.getFractionFormatter(timeZoneId).format(value.asInstanceOf[Long]) case TimestampNTZType => TimestampFormatter.getFractionFormatter(ZoneOffset.UTC).format(value.asInstanceOf[Long]) case DayTimeIntervalType(startField, endField) => toDayTimeIntervalString(value.asInstanceOf[Long], ANSI_STYLE, startField, endField) case YearMonthIntervalType(startField, endField) => toYearMonthIntervalString(value.asInstanceOf[Int], ANSI_STYLE, startField, endField) case _ => other.toString } } override def hashCode(): Int = { val valueHashCode = value match { case null => 0 case binary: Array[Byte] => util.Arrays.hashCode(binary) case other => other.hashCode() } 31 * Objects.hashCode(dataType) + valueHashCode } override def equals(other: Any): Boolean = other match { case o: Literal if !dataType.equals(o.dataType) => false case o: Literal => (value, o.value) match { case (null, null) => true case (a: Array[Byte], b: Array[Byte]) => util.Arrays.equals(a, b) case (a: ArrayBasedMapData, b: ArrayBasedMapData) => a.keyArray == b.keyArray && a.valueArray == b.valueArray case (a: Double, b: Double) if a.isNaN && b.isNaN => true case (a: Float, b: Float) if a.isNaN && b.isNaN => true case (a, b) => a != null && a == b } case _ => false } override protected def jsonFields: List[JField] = { // Turns all kinds of literal values to string in json field, as the type info is hard to // retain in json format, e.g. {"a": 123} can be an int, or double, or decimal, etc. val jsonValue = (value, dataType) match { case (null, _) => JNull case (i: Int, DateType) => JString(toString) case (l: Long, TimestampType) => JString(toString) case (other, _) => JString(other.toString) } ("value" -> jsonValue) :: ("dataType" -> dataType.jsonValue) :: Nil } override def eval(input: InternalRow): Any = value override def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = { val javaType = CodeGenerator.javaType(dataType) if (value == null) { ExprCode.forNullValue(dataType) } else { def toExprCode(code: String): ExprCode = { ExprCode.forNonNullValue(JavaCode.literal(code, dataType)) } dataType match { case BooleanType | IntegerType | DateType | _: YearMonthIntervalType => toExprCode(value.toString) case FloatType => value.asInstanceOf[Float] match { case v if v.isNaN => toExprCode("Float.NaN") case Float.PositiveInfinity => toExprCode("Float.POSITIVE_INFINITY") case Float.NegativeInfinity => toExprCode("Float.NEGATIVE_INFINITY") case _ => toExprCode(s"${value}F") } case DoubleType => value.asInstanceOf[Double] match { case v if v.isNaN => toExprCode("Double.NaN") case Double.PositiveInfinity => toExprCode("Double.POSITIVE_INFINITY") case Double.NegativeInfinity => toExprCode("Double.NEGATIVE_INFINITY") case _ => toExprCode(s"${value}D") } case ByteType | ShortType => ExprCode.forNonNullValue(JavaCode.expression(s"($javaType)$value", dataType)) case TimestampType | TimestampNTZType | LongType | _: DayTimeIntervalType => toExprCode(s"${value}L") case _ => val constRef = ctx.addReferenceObj("literal", value, javaType) ExprCode.forNonNullValue(JavaCode.global(constRef, dataType)) } } } override def sql: String = (value, dataType) match { case (_, NullType | _: ArrayType | _: MapType | _: StructType) if value == null => "NULL" case _ if value == null => s"CAST(NULL AS ${dataType.sql})" case (v: UTF8String, StringType) => // Escapes all backslashes and single quotes. "'" + v.toString.replace("\\", "\\\\").replace("'", "\\'") + "'" case (v: Byte, ByteType) => v + "Y" case (v: Short, ShortType) => v + "S" case (v: Long, LongType) => v + "L" // Float type doesn't have a suffix case (v: Float, FloatType) => val castedValue = v match { case _ if v.isNaN => "'NaN'" case Float.PositiveInfinity => "'Infinity'" case Float.NegativeInfinity => "'-Infinity'" case _ => s"'$v'" } s"CAST($castedValue AS ${FloatType.sql})" case (v: Double, DoubleType) => v match { case _ if v.isNaN => s"CAST('NaN' AS ${DoubleType.sql})" case Double.PositiveInfinity => s"CAST('Infinity' AS ${DoubleType.sql})" case Double.NegativeInfinity => s"CAST('-Infinity' AS ${DoubleType.sql})" case _ => v + "D" } case (v: Decimal, t: DecimalType) => v + "BD" case (v: Int, DateType) => s"DATE '$toString'" case (v: Long, TimestampType) => s"TIMESTAMP '$toString'" case (v: Long, TimestampNTZType) => s"TIMESTAMP_NTZ '$toString'" case (i: CalendarInterval, CalendarIntervalType) => s"INTERVAL '${i.toString}'" case (v: Array[Byte], BinaryType) => s"X'${ApacheHex.encodeHexString(v, false)}'" case (i: Long, DayTimeIntervalType(startField, endField)) => toDayTimeIntervalString(i, ANSI_STYLE, startField, endField) case (i: Int, YearMonthIntervalType(startField, endField)) => toYearMonthIntervalString(i, ANSI_STYLE, startField, endField) case _ => value.toString } }
{ "content_hash": "fb73aba40bfa2aa4f4f09041ec8f8daa", "timestamp": "", "source": "github", "line_count": 474, "max_line_length": 142, "avg_line_length": 40.34177215189873, "alnum_prop": 0.6718962451626399, "repo_name": "chuckchen/spark", "id": "cc207e51f85c48fd00bdfb3193b97c99ef03b6c8", "size": "19922", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/literals.scala", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "50108" }, { "name": "Batchfile", "bytes": "25676" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "26852" }, { "name": "Dockerfile", "bytes": "9127" }, { "name": "HTML", "bytes": "40529" }, { "name": "HiveQL", "bytes": "1890736" }, { "name": "Java", "bytes": "4156231" }, { "name": "JavaScript", "bytes": "209968" }, { "name": "Makefile", "bytes": "1587" }, { "name": "PLSQL", "bytes": "6658" }, { "name": "PLpgSQL", "bytes": "380488" }, { "name": "PowerShell", "bytes": "3865" }, { "name": "Python", "bytes": "3222278" }, { "name": "R", "bytes": "1203999" }, { "name": "Roff", "bytes": "36516" }, { "name": "SQLPL", "bytes": "9325" }, { "name": "Scala", "bytes": "32613994" }, { "name": "Shell", "bytes": "209299" }, { "name": "TSQL", "bytes": "473509" }, { "name": "Thrift", "bytes": "67584" }, { "name": "q", "bytes": "79845" } ], "symlink_target": "" }
LDNS module documentation ================================ Here you can find the documentation of pyLDNS extension module. This module consists of several classes and a couple of functions. .. toctree:: :maxdepth: 1 :glob: ldns_resolver ldns_pkt ldns_rr ldns_rdf ldns_dname ldns_rr_list ldns_zone ldns_key ldns_key_list ldns_buffer ldns_dnssec ldns_func **Differences against libLDNS** * You don't need to use ldns-compare functions, instances can be compared using standard operators <, >, = :: if (some_rr.owner() == another_rr.rdf(1)): pass * Classes contain static methods that create new instances, the name of these methods starts with the new\_ prefix (e.g. :meth:`ldns.ldns_pkt.new_frm_file`). * Is it possible to print the content of an object using ``print objinst`` (see :meth:`ldns.ldns_resolver.get_addr_by_name`). * Classes contain write_to_buffer method that writes the content into buffer. * All the methods that consume parameter of (const ldns_rdf) type allows to use string instead (see :meth:`ldns.ldns_resolver.query`).
{ "content_hash": "279f8314551eaa77f423fba8be82eab5", "timestamp": "", "source": "github", "line_count": 40, "max_line_length": 157, "avg_line_length": 26.825, "alnum_prop": 0.7157502329916123, "repo_name": "steakknife/ldns", "id": "2c5e7b2455d6f602bdbfbb243cf66ea709bbce30", "size": "1073", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "contrib/python/docs/source/modules/ldns.rst", "mode": "33261", "license": "bsd-3-clause", "language": [ { "name": "C", "bytes": "1786391" }, { "name": "C++", "bytes": "4642" }, { "name": "CSS", "bytes": "9080" }, { "name": "JavaScript", "bytes": "5211" }, { "name": "Perl", "bytes": "184149" }, { "name": "Python", "bytes": "274120" }, { "name": "Ruby", "bytes": "20420" }, { "name": "Shell", "bytes": "320314" }, { "name": "VimL", "bytes": "19597" } ], "symlink_target": "" }
<div class="panel panel-default"> <div class="panel-heading"> Surgery Center <span class="pull-right btn-group"> <a href="" class="btn btn-xs btn-success" ui-sref="^.add()"> <i class="fa fa-plus"></i> </a> </span> </div> <div class='list-group'> <div ng-repeat="item in ctrl.center" class="list-group-item"> <span class="pull-right btn-group"> <a href="" class="btn btn-xs btn-default" ui-sref="^.edit({id: item.id})"> <i class="fa fa-pencil"></i> </a> <a href="" class="btn btn-xs btn-danger" ui-sref="^.delete({id: item.id})"> <i class="fa fa-trash-o"></i> </a> </span> <h4 class="list-group-item-heading"> <a href="" ui-sref="^.view({id: item.id})">{{item.id}}</a> </h4> <p class="list-group-item-text">{{item.name}}</p> </div> <div ng-show="!ctrl.center.length" class="list-group-item"> <h4 class="list-group-item-heading" translate> There are no Surgery Centers </h4> <p class="list-group-item-text" translate>Click <a href="" ui-sref="^.add">here</a> to add a Center!</p> </div> </div> </div>
{ "content_hash": "afaa6376972c0acb45de506604dd80b8", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 110, "avg_line_length": 32.083333333333336, "alnum_prop": 0.5558441558441558, "repo_name": "rsvasanth/Advancednurosurgery", "id": "a958c5c1aeb9cf8db815f7f3af4a04a702b6fa9a", "size": "1155", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "client/app/modules/center/views/list.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "90230" }, { "name": "HTML", "bytes": "37489" }, { "name": "JavaScript", "bytes": "105318" } ], "symlink_target": "" }
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context=".JokeActivity"> <item android:id="@+id/action_settings" android:title="@string/action_settings" android:orderInCategory="100" app:showAsAction="never" /> </menu>
{ "content_hash": "8d4fb71fc408466958eb0a07f558ce49", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 83, "avg_line_length": 60.166666666666664, "alnum_prop": 0.7174515235457064, "repo_name": "Wertros/GradleTutorial", "id": "aa1b8a6b765f390f9a64c3ddf204be5f6dea5c74", "size": "361", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "4.04-Exercise-CreateAnAndroidLibrary/solution/jokedisplay/src/main/res/menu/menu_joke.xml", "mode": "33188", "license": "mit", "language": [ { "name": "HTML", "bytes": "973" }, { "name": "Java", "bytes": "3176579" } ], "symlink_target": "" }
''' This checks if all command line args are documented. Return value is 0 to indicate no error. Author: @MarcoFalke ''' from subprocess import check_output import re import sys FOLDER_GREP = 'src' FOLDER_TEST = 'src/test/' REGEX_ARG = '(?:ForceSet|SoftSet|Get|Is)(?:Bool)?Args?(?:Set)?\("(-[^"]+)"' REGEX_DOC = 'AddArg\("(-[^"=]+?)(?:=|")' CMD_ROOT_DIR = '`git rev-parse --show-toplevel`/{}'.format(FOLDER_GREP) CMD_GREP_ARGS = r"git grep --perl-regexp '{}' -- {} ':(exclude){}'".format(REGEX_ARG, CMD_ROOT_DIR, FOLDER_TEST) CMD_GREP_DOCS = r"git grep --perl-regexp '{}' {}".format(REGEX_DOC, CMD_ROOT_DIR) # list unsupported, deprecated and duplicate args as they need no documentation SET_DOC_OPTIONAL = set(['-h', '-help', '-dbcrashratio', '-forcecompactdb']) def main(): if sys.version_info >= (3, 6): used = check_output(CMD_GREP_ARGS, shell=True, universal_newlines=True, encoding='utf8') docd = check_output(CMD_GREP_DOCS, shell=True, universal_newlines=True, encoding='utf8') else: used = check_output(CMD_GREP_ARGS, shell=True).decode('utf8').strip() docd = check_output(CMD_GREP_DOCS, shell=True).decode('utf8').strip() args_used = set(re.findall(re.compile(REGEX_ARG), used)) args_docd = set(re.findall(re.compile(REGEX_DOC), docd)).union(SET_DOC_OPTIONAL) args_need_doc = args_used.difference(args_docd) args_unknown = args_docd.difference(args_used) print("Args used : {}".format(len(args_used))) print("Args documented : {}".format(len(args_docd))) print("Args undocumented: {}".format(len(args_need_doc))) print(args_need_doc) print("Args unknown : {}".format(len(args_unknown))) print(args_unknown) sys.exit(len(args_need_doc)) if __name__ == "__main__": main()
{ "content_hash": "7cb0347823dc688cf6ab08cd09aa8d58", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 112, "avg_line_length": 38.06382978723404, "alnum_prop": 0.6467300167691448, "repo_name": "droark/bitcoin", "id": "3b05d5055cf1da072017458e0a698a487da1dafe", "size": "2004", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "test/lint/check-doc.py", "mode": "33261", "license": "mit", "language": [ { "name": "Assembly", "bytes": "28453" }, { "name": "C", "bytes": "696871" }, { "name": "C++", "bytes": "6310531" }, { "name": "HTML", "bytes": "21860" }, { "name": "Java", "bytes": "30290" }, { "name": "M4", "bytes": "198257" }, { "name": "Makefile", "bytes": "119862" }, { "name": "Objective-C", "bytes": "123749" }, { "name": "Objective-C++", "bytes": "5382" }, { "name": "Python", "bytes": "1583778" }, { "name": "QMake", "bytes": "756" }, { "name": "Shell", "bytes": "98048" } ], "symlink_target": "" }
package net.winterly.dropwizard.hk2bundle; import net.winterly.dropwizard.hk2bundle.health.ExampleHealthCheck; import net.winterly.dropwizard.hk2bundle.metric.ExampleGauge; import net.winterly.dropwizard.hk2bundle.spi.DropwizardBinder; public class ExampleAppBinder extends DropwizardBinder { @Override protected void configure() { metric(ExampleGauge.class); healthCheck(ExampleHealthCheck.class); } }
{ "content_hash": "0a28527684689f13a3d28ec0edc22783", "timestamp": "", "source": "github", "line_count": 14, "max_line_length": 67, "avg_line_length": 31, "alnum_prop": 0.7903225806451613, "repo_name": "alex-shpak/dropwizard-hk2bundle", "id": "f8c016871d0b4f5a02d6ff8db60f7ef22aa556b8", "size": "434", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/net/winterly/dropwizard/hk2bundle/ExampleAppBinder.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "24264" } ], "symlink_target": "" }
if ( typeof bbop == "undefined" ){ var bbop = {}; } if ( typeof bbop.widget == "undefined" ){ bbop.widget = {}; } if ( typeof bbop.widget.phylo_tree == "undefined" ){ bbop.widget.phylo_tree = {}; } (function() { bbop.widget.phylo_tree.renderer = renderer; // if there is more than one phylo tree on the page, this counter // makes the CSS prefixes unique var id_counter = 0; // see default_config for a description of possible config settings function renderer(parent, config){ this.parent = ( ( "string" == typeof parent ) ? document.getElementById(parent) : parent ); if (this.parent === undefined) { throw "can't find parent element " + parent; } this.tree = new tree(); this.node_hidden = {}; this.children_hidden = {}; this._sort = "ladderize_up"; this._layout_dirty = true; this._css_prefix = "phylo_tree_" + (id_counter++) + "_"; var self = this; this.node_elem_click_handler = function(event) { var node_elem = (event.currentTarget) ? event.currentTarget : event.srcElement; var node = self.tree.nodes[node_elem.node_id]; if (node) return self.node_clicked(node, node_elem, event); }; var default_config = { // these are in pixels // leaf box vertical height, including padding and borders box_height: 24, // vertical space between leaf boxes box_spacing: 10, // space between leaf box edge and leaf label leaf_padding: 4, // leaf border thickness leaf_border: 2, // leaf left offset leaf_margin: 1, // width/height of internal nodes node_size: 8, // leaf border color leaf_border_color: "blue", // font for leaf labels leaf_font: "Helvetica, Arial, sans-serif", transition_time: "0.8s" }; this.config = ("object" == typeof config ? bbop.core.merge(default_config, config) : default_config); //config settings with default values dependent on other config values this.config.parent_padding = ( (this.config.parent_padding === undefined) ? ((this.config.box_spacing / 2) | 0) : this.config.parent_padding ); this.node_style = { position: "absolute", background: "white", "z-index": 2, width: this.config.node_size + "px", height: this.config.node_size + "px", "margin-top": (-this.config.node_size / 2) + "px", "margin-left": (-this.config.node_size / 2) + "px", border: "1px solid black", "transition-property": "top, left", "transition-duration": this.config.transition_time, "transition-timing-function": "ease-in-out, ease-in-out", "box-sizing": "content-box", "-moz-box-sizing": "content-box" }; this.leaf_style = { position: "absolute", background: "#f1f1ff", "z-index": 1, padding: this.config.leaf_padding + "px", // if leaf_padding is too low, the branch line will touch the text "padding-left": Math.max(this.config.leaf_padding, 3) + "px", // so that the leaves don't cover up the connection lines "margin-left": this.config.leaf_margin + "px", "margin-top": (-this.config.box_height / 2) + "px", // setting font size from box height. We'd like to set font cap height // directly, but we can only set em box size. Cap height on average is // 70% of em box size, so we'll set the font size to the intended // height divided by 0.7 font: ( ( this.config.box_height - ( this.config.leaf_padding * 2 ) - ( this.config.leaf_border * 2 ) ) / 0.7 ) + "px " + this.config.leaf_font, // this.config.box_height includes padding and borders, so we // subtract those out to set the CSS height, which doesn't include // padding or borders height: ( this.config.box_height - ( this.config.leaf_padding * 2 ) - ( this.config.leaf_border * 2 ) ) + "px", // center vertically by setting the line height to 0.7em // (corresponding to the way we set font size above) "line-height": "0.7em", "border-radius": (this.config.leaf_padding + 1) + "px", "white-space": "nowrap", "transition-property": "top, left", "transition-duration": this.config.transition_time, "transition-timing-function": "ease-in-out, ease-in-out", "box-sizing": "content-box", "-moz-box-sizing": "content-box" }; if (this.config.leaf_border > 0) { this.leaf_style.border = this.config.leaf_border + "px solid " + this.config.leaf_border_color; } this.connection_style = { position: "absolute", "border-left": "2px solid black", "border-top": "2px solid black", "border-bottom": "2px solid black", "border-right": "none", "transition-property": "top, height, left, width, border", "transition-duration": this.config.transition_time, "transition-timing-function": "ease-in-out, ease-in-out, ease-in-out, ease-in-out, step-start" }; }; renderer.prototype.subtree_hidden = function(node_id) { return this.children_hidden[node_id]; }; // sets the given css_string as a new stylesheet, or replaces this object's // stylesheet with css_string if one has already been set renderer.prototype.set_styles = function(css_string) { if (! this._style_node) { head = document.getElementsByTagName('head')[0], this._style_node = document.createElement('style'); this._style_node.type = 'text/css'; head.appendChild(this._style_node); } if (this._style_node.styleSheet) { // IE this._style_node.styleSheet.cssText = css_string; } else { while (this._style_node.firstChild) { this._style_node.removeChild(this._style_node.firstChild); } this._style_node.appendChild(document.createTextNode(css_string)); } }; renderer.prototype.add_node = function(unique_id, label, meta){ this.tree.add_node(unique_id, label, meta); this._layout_dirty = true; }; renderer.prototype.add_edge = function(nid1, nid2, dist){ this.tree.add_edge(nid1, nid2, dist); this._layout_dirty = true; }; renderer.prototype.display = function () { if (this.container) this.parent.removeChild(this.container); this.container = document.createElement("div"); this.container.style.cssText = [ "position: absolute", "top: 0px", "left: " + ( (this.config.node_size / 2) + this.config.parent_padding ) + "px", "margin: 0px", "padding: 0px", "transition-property: width, height", "transition-duration: " + this.config.transition_time, "transition-timing-function: ease-in-out" ].join(";") + ";"; var node_class = this._css_prefix + "node"; var leaf_class = this._css_prefix + "leaf"; var conn_class = this._css_prefix + "conn"; this.set_styles([ "div." + node_class + " {" + css_string(this.node_style) + "}", "div." + leaf_class + " {" + css_string(this.leaf_style) + "}", "div." + conn_class + " {" + css_string(this.connection_style) + "}" ].join("\n")); var phynodes = {}; for (var node_id in this.tree.nodes) { var node = this.tree.nodes[node_id]; var phynode = new graph_pnode(node, node_class, leaf_class, this.config.box_height); this.container.appendChild(phynode.node_elem); phynode.node_elem.onclick = this.node_elem_click_handler; phynodes[node.id] = phynode; } this._phynodes = phynodes; var container = this.container; var self = this; this.tree.iterate_edges(function(parent, child) { if (self.node_hidden[child.id]) return; var child_phynode = phynodes[child.id]; child_phynode.set_parent( phynodes[parent.id], conn_class ); container.appendChild(child_phynode.conn_elem); }); this.position_nodes(); this.parent.appendChild(this.container); this.width_changed(this.parent.clientWidth); }; renderer.prototype.position_nodes = function() { // x_scale will be percentage units var x_scale = 100 / this.max_distance(); // row_height is in pixel units var row_height = this.config.box_height + this.config.box_spacing; // the position values from the tree layout are center // positions, and the very top one has a y-position of 0. // if a leaf node box is centered at that point, then the // top half of the top box would get cut off. So we move // all of the positions down by top_margin pixels. var top_margin = ( (this.config.box_height / 2) + this.config.parent_padding ); var layout = this.layout(); var self = this; this.tree.iterate_preorder(function(node) { var node_pos = layout[node.id]; var x = (node_pos.x * x_scale); var y = (node_pos.y * row_height) + top_margin; self._phynodes[node_pos.id].set_position(x, y); if (self.subtree_hidden(node.id)) return true; }); this.tree_height = ( (this.leaves().length * row_height) - this.config.box_spacing + (this.config.parent_padding * 2) ); this.parent.style.transition = "height " + this.config.transition_time + " ease-in-out"; this.parent.style.height = this.tree_height + "px"; this.container.style.height = this.tree_height + "px"; }; renderer.prototype.max_distance = function() { if (this._layout_dirty) this._update_layout(); return this._max_distance; }; renderer.prototype.leaves = function() { if (this._layout_dirty) this._update_layout(); return this._leaves; }; renderer.prototype.layout = function() { if (this._layout_dirty) this._update_layout(); return this._layout; }; renderer.prototype._update_layout = function() { this._do_sort(this._sort); var self = this; var visible_leaves = []; this.tree.iterate_preorder(function(node) { if (self.node_hidden[node.id]) return; // nodes with hidden children are leaves for layout purposes if (node.is_leaf() || self.children_hidden[node.id]) { visible_leaves.push(node); } }); this._leaves = visible_leaves; var roots = this.tree.roots(); var root_distances = []; for (var i = 0; i < roots.length; i++) { root_distances.push(roots[i].parent_distance); } // if we're only showing a subtree, position the leftmost subtree // root all the way to the left this.x_offset = -min(root_distances); this._max_distance = max(this.tree.traverse( function(node, down_data) { return down_data + node.parent_distance; }, this.x_offset, function(node, child_results, down_data) { if (self.node_hidden[node.id]) return 0; return Math.max(down_data, max(child_results)); } ) ); this._layout = this._do_layout(); this._layout_dirty = false; }; // returns an array of {id, x, y} objects (one per node) renderer.prototype._do_layout = function() { var leaf_counter = 0; var self = this; var layout_list = Array.prototype.concat.apply([], this.tree.traverse( function(node, down_data) { return down_data + node.parent_distance; }, this.x_offset, function(node, child_results, down_data) { // don't lay out the node if it's hidden if (self.node_hidden[node.id]) return []; // don't try to average child positions if children are hidden if (! (node.id in self.children_hidden)) { var immediate_child_y_sum = 0; for (var i = 0; i < child_results.length; i++) { // child_results will be an array with one element // for each child. Each of those elements is an // array of position objects. The first position // object is the position of the immediate child, // and the rest of the position objects are for // that child's descendants. (see how the return // value is constructed below) immediate_child_y_sum += child_results[i][0].y; } } var my_pos = [{ id: node.id, x: down_data, y: ( ( node.is_leaf() || self.children_hidden[node.id] ) // The traverse method goes depth-first, so we'll // encounter the leaves in leaf-order. So the // y-coord for leaves is just the number of // leaves we've seen so far. ? leaf_counter++ // The internal node y-coord is the mean of its // child y-coords : ( immediate_child_y_sum / child_results.length ) ) }]; // flatten child result arrays and append the result to my_pos return Array.prototype.concat.apply(my_pos, child_results); } ) ); var layout_hash = {}; for (var i = 0; i < layout_list.length; i++) { layout_hash[layout_list[i].id] = layout_list[i]; } return layout_hash; }; // call this when the width of the tree's parent element changes renderer.prototype.width_changed = function(parent_width) { var leaves = this.leaves(); var avail_width = ( parent_width - (this.config.node_size / 2) - (this.config.parent_padding * 2) - this.config.leaf_margin ); var min_width = Number.MAX_VALUE; for (var li = 0; li < leaves.length; li++) { var leaf_id = leaves[li].id; var phynode = this._phynodes[leaf_id]; // Each potential width is the width that this.container // would have to be so that the leaf label fits into this.parent. // We take the minimum because that's the most conservative of // all the potential widths we calculate here. var potential_width = // dividing px by 100 because px is in percentage units (avail_width - phynode.width()) / (phynode.px / 100) min_width = Math.min(min_width, potential_width); } this.container.style.width = Math.max(0, min_width | 0) + "px"; }; // hides the subtree under the given node_id; for that node, // it shows the label and a visual ellipsis renderer.prototype.hide_subtree = function(node_id) { var to_hide_under = this.tree.nodes[node_id]; if (to_hide_under === undefined) { throw "asked to hide non-existent node " + node_id; } // there's nothing to hide under a leaf node if (to_hide_under.is_leaf()) return; var self = this; to_hide_under.iterate_preorder(function(node) { // don't hide the given node if (node === to_hide_under) return; self.node_hidden[node.id] = true; self._phynodes[node.id].hide(); }); self.children_hidden[to_hide_under.id] = true; self._phynodes[to_hide_under.id].set_children_hidden(); this._layout_dirty = true; this.position_nodes(); this.width_changed(this.parent.clientWidth); }; // show a previously-hidden subtree renderer.prototype.show_subtree = function(node_id) { var to_show_under = this.tree.nodes[node_id]; if (to_show_under === undefined) { throw "asked to show non-existent node " + node_id; } var self = this; // remove this node from children_hidden delete self.children_hidden[to_show_under.id]; to_show_under.iterate_preorder(function(node) { if (node === to_show_under) return; delete self.node_hidden[node.id]; self._phynodes[node.id].show(); // returning true stops the iteration: if we encounter a // previously-hidden subtree under the node that we're // showing, we'll leave its children hidden unless it's // specifically shown if (self.children_hidden[node.id]) return true; }); self._phynodes[to_show_under.id].set_children_visible(); this._layout_dirty = true; this.position_nodes(); this.width_changed(this.parent.clientWidth); }; // hide everything except the subtree rooted at the given node renderer.prototype.show_only_subtree = function(node_id) { var to_show = this.tree.nodes[node_id]; if (to_show === undefined) { throw "asked to show non-existent node " + node_id; } // hide all nodes except those under the given node var self = this; this.tree.iterate_preorder(function(node) { // returning true stops the iteration: we don't want to hide // any nodes under this node, so we'll stop the iteration here // for the subtree rooted at the current node if (node === to_show) return true; self.node_hidden[node.id] = true; self._phynodes[node.id].hide(); }); this.tree.set_roots([to_show.id]); this._phynodes[node_id].hide_connector(); this._layout_dirty = true; this.position_nodes(); this.width_changed(this.parent.clientWidth); }; // returns true if we're showing only a subtree rooted at the node // with the given id, false otherwise renderer.prototype.only_subtree_shown = function(node_id) { var node = this.tree.nodes[node_id]; return contains(this.tree.roots(), node) && node.has_parent(); }; // undo show_only_subtree renderer.prototype.show_global_root = function() { this.tree.clear_roots(); var self = this; this.tree.iterate_preorder(function(node) { delete self.node_hidden[node.id]; var phynode = self._phynodes[node.id]; phynode.show(); if (! phynode.connector_shown) phynode.show_connector(); // returning true stops the iteration: if we encounter a // previously-hidden subtree under the node that we're // showing, we'll leave its children hidden unless it's // specifically shown if (self.children_hidden[node.id]) return true; }); this._layout_dirty = true; this.position_nodes(); this.width_changed(this.parent.clientWidth); }; renderer.prototype.node_clicked = function() {}; renderer.prototype.set_sort = function(sort) { if (sort == this._sort) return; this._sort = sort; this._layout_dirty = true; }; // sort the tree according to the given sort ordering // see available_sorts for available sort arguments renderer.prototype._do_sort = function(sort) { // leaf_counts: for each node, contains the number of its descendant leaves var leaf_counts = {}; this.tree.traverse( function() {}, null, function(node, child_results, down_data) { // if this is a leaf, call the leaf count 1 var leaf_count = node.is_leaf() ? 1 : sum(child_results); leaf_counts[node.id] = leaf_count; return leaf_count; } ); var available_sorts = { ladderize_up: function(a, b) { return leaf_counts[b.id] - leaf_counts[a.id]; }, ladderize_down: function(a, b) { return leaf_counts[a.id] - leaf_counts[b.id]; }, alphabetical: function(a, b) { if( a.id == b.id ) return 0; return (a.id < b.id) ? -1 : 1; } }; if ("string" == typeof sort) { if( ! sort in available_sorts ) throw "unknown sort " + sort; this.tree.sort_children(available_sorts[sort]); } else if ("function" == typeof sort) { this.tree.sort_children(sort); } }; renderer.prototype.iterate_preorder = function(callback) { var self = this; this.tree.iterate_preorder(function(node) { // if the node is hidden, there won't be anything in self._phynodes if (self.node_hidden[node.id]) return; return callback(node.id, node.label, node.meta, self._phynodes[node.id].node_elem, node.children); }); }; renderer.prototype.traverse = function(down_fun, down_data, up_aggregator) { var self = this; return this.tree.traverse(down_fun, down_data, up_aggregator); }; /// /// phylo node html renderer /// function graph_pnode(node, node_class, leaf_class, height){ this.node = node; this.height = height; this.leaf_class = leaf_class; this.connector_shown = false; var node_elem = document.createElement("div"); if (node.is_leaf()) { node_elem.appendChild(document.createTextNode(node.label)); node_elem.className = leaf_class; } else { node_elem.title = node.label; node_elem.className = node_class; } node_elem.node_id = node.id; this.node_elem = node_elem; } graph_pnode.prototype.set_children_hidden = function() { var left_offset = 10; this.subtree_box = document.createElement("div"); this.subtree_box.className = this.leaf_class; this.subtree_box.style.backgroundColor = "#eee"; this.subtree_box.style.left = left_offset + "px"; this.subtree_box.style.top = ((this.height / 2) - (this.node_elem.offsetHeight / 2 ) ) + "px"; this.subtree_box.appendChild( document.createTextNode(this.node.label + " ...") ); this.subtree_box.node_id = this.node.id; this.node_elem.appendChild(this.subtree_box); this._width = left_offset + this.subtree_box.offsetWidth; }; graph_pnode.prototype.set_children_visible = function() { this._width = this.node_elem.offsetWidth; this.node_elem.removeChild(this.subtree_box); }; graph_pnode.prototype.hide = function() { this.node_elem.style.display = "none"; if (this.parent) this.conn_elem.style.display = "none"; }; graph_pnode.prototype.hide_connector = function() { if (this.parent) this.conn_elem.style.display = "none"; this.connector_shown = false; }; graph_pnode.prototype.show = function() { this.node_elem.style.display = ""; if (this.parent) this.conn_elem.style.display = ""; }; graph_pnode.prototype.show_connector = function() { if (this.parent) this.conn_elem.style.display = ""; this.connector_shown = true; }; graph_pnode.prototype.set_position = function(x, y) { this.px = x; this.py = y; this.node_elem.style.left = x + "%"; this.node_elem.style.top = y + "px"; if (this.parent && this.connector_shown) { var conn_style = "top: " + Math.min(this.parent.py, this.py) + "px;" + "left: " + this.parent.px + "%;" + "width: " + (this.px - this.parent.px) + "%;" + "height: " + Math.abs(this.parent.py - this.py) + "px;"; if (this.py < this.parent.py) { // upward connection conn_style += "border-bottom: none;"; } else { // downward connection conn_style += "border-top: none;"; } this.conn_elem.style.cssText = conn_style; } } graph_pnode.prototype.set_parent = function(parent, conn_class) { this.parent = parent; this.conn_elem = document.createElement("div"); this.conn_elem.className = conn_class; this.conn_elem.id=parent.node.id + "-" + this.node.id; this.connector_shown = true; }; graph_pnode.prototype.width = function() { if (! ("_width" in this)) this._width = this.node_elem.offsetWidth; return this._width; }; /// /// a tree with distances on each edge /// function tree() { this.nodes = {}; // if _dirty is true, then the stuff that's calculated in _summarize() // is out of date this._dirty = true; } tree.prototype.add_node = function(id, label, meta) { this.nodes[id] = new node(id, label, meta); this._dirty = true; }; tree.prototype.add_edge = function(parent_id, child_id, distance) { var parent = this.nodes[parent_id]; var child = this.nodes[child_id]; if( "undefined" == typeof parent ){ throw "parent node " + parent_id + " not found"; } if( "undefined" == typeof child ){ throw "child node " + child_id + " not found"; } parent.add_child(child, distance); this._dirty = true; }; tree.prototype.sort_children = function(compare_fun) { var roots = this.roots(); roots.sort(compare_fun); for (var i = 0; i < roots.length; i++) { roots[i].sort_children(compare_fun); } }; tree.prototype.iterate_preorder = function(fun) { var roots = this.roots() for (var i = 0; i < roots.length; i++) { roots[i].iterate_preorder(fun); } }; tree.prototype.iterate_edges = function(fun) { for (var id in this.nodes) { var parent = this.nodes[id]; for (var i = 0; i < parent.children.length; i++) { fun(parent, parent.children[i]); } } }; tree.prototype._summarize = function() { if (this._dirty) this.clear_roots(); this._dirty = false; }; tree.prototype.roots = function() { if (this._dirty) this._summarize(); return this._roots; }; // set the roots to be specific nodes // i.e. to only show a subtree, set_roots(subtree_node_id) tree.prototype.set_roots = function(root_ids) { var roots = []; for (var i = 0; i < root_ids.length; i++) { roots.push(this.nodes[root_ids[i]]); } this._roots = roots; }; // set the list of roots back to the "natural" list of nodes without // parents tree.prototype.clear_roots = function() { var roots = []; for (var id in this.nodes) { var node = this.nodes[id]; if( ! node.has_parent() ) roots.push(node); } this._roots = roots; }; // see node.traverse for description tree.prototype.traverse = function(down_fun, down_data, up_aggregator) { var roots = this.roots(); var results = []; for (var i = 0; i < roots.length; i++) { results.push(roots[i].traverse(down_fun, down_data, up_aggregator)); } return results; }; /// /// tree node /// function node(id, label, meta) { this.id = id; this.label = label; this.meta = meta; this.parent = null; this.parent_distance = 0; this.children = []; }; node.prototype.add_child = function(child_node, distance) { child_node.parent_distance = distance; child_node.parent = this; this.children.push(child_node); }; node.prototype.is_leaf = function() { return 0 == this.children.length; }; node.prototype.has_parent = function() { return null != this.parent; }; node.prototype.sort_children = function(compare_fun) { for (var i = 0; i < this.children.length; i++) { this.children[i].sort_children(compare_fun); } this.children.sort(compare_fun); }; // return true from the callback to stop iterating at a node // (the iteration will continue with siblings but not with children of the // node where the callback returns true node.prototype.iterate_preorder = function(fun) { if (! (true == fun(this))) { for (var i = 0; i < this.children.length; i++) { this.children[i].iterate_preorder(fun); } } }; // traverse down and then up the tree, passing some data down // at each step, and aggregating traversal results from the // children on the way up // down_fun: gets called on each node on the way down // arguments: node, down_data // down_data: starting value for the data to pass down // (down_fun on a root gets this value for down_data) // up_aggregator: function to aggregate results on the way back up // arguments: node, child_results, down_data node.prototype.traverse = function(down_fun, down_data, up_aggregator) { down_data = down_fun(this, down_data); var child_results = new Array(this.children.length);; for (var i = 0; i < this.children.length; i++) { child_results[i] = this.children[i].traverse(down_fun, down_data, up_aggregator) } return up_aggregator(this, child_results, down_data); }; /// /// Util functions /// // takes an object like {"top": "10px", "left": "5px"} // and return a string like "top: 10px; left: 5px;" function css_string(css_object) { var result = ""; if ("object" == typeof css_object) { for (var key in css_object) { result += key + ":" + css_object[key] + ";"; } } return result; } function contains(arr, elem) { for (var i = 0; i < arr.length; i++) { if (elem == arr[i]) return true; } return false; } function max(list) { if (0 == list.length) return null; var result = list[0]; for (var i = 1; i < list.length; i++) { if (list[i] > result) result = list[i]; } return result; } function min(list) { if (0 == list.length) return null; var result = list[0]; for (var i = 1; i < list.length; i++) { if (list[i] < result) result = list[i]; } return result; } function sum(list) { var result = 0; for (var i = 0; i < list.length; i++) { result += list[i]; } return result; } })();
{ "content_hash": "90f082f114f917534bab5ca7fd6d4166", "timestamp": "", "source": "github", "line_count": 885, "max_line_length": 83, "avg_line_length": 33.289265536723164, "alnum_prop": 0.5946166117918604, "repo_name": "berkeleybop/bbop-js", "id": "3ac6a2ed32a1a511d81a54513d9e1ab509bb4482", "size": "29461", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "lib/bbop/widget/phylo-tree.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Common Lisp", "bytes": "6316" }, { "name": "HTML", "bytes": "22997" }, { "name": "JavaScript", "bytes": "1986596" }, { "name": "Makefile", "bytes": "4978" }, { "name": "Perl", "bytes": "17689" }, { "name": "Python", "bytes": "1358" } ], "symlink_target": "" }
layout: post title: "The End" subtitle: "Walking was the easy part." date: "2017-09-12 23:42:38" author: "Randall" header-img: "img/The-EndHeader.JPG" mile: "2650" --- I tried to sleep in today, but it felt like Christmas. All night long I thought about finishing the trail. When morning finally came I got up and started hiking. The guys I was with were meeting one of their girlfriends at the border a little later so I hiked on alone. ![photo0](/img/The EndPost0.JPG) Hiking today was surreal. It was a perfect day with amazing views. The last 14 miles are some of the best on the whole trail. I saw a guy I shared a hotel room with way back in Southern California. He had finished the day before and was hiking back to Hart's Pass. We talked for awhile about how crazy this hike has been. Then I hiked on. ![photo1](/img/The EndPost1.JPG) I loved this sign. It's such an American thing to do to make a sign saying we're heading to the US border, when we're in the US. It's not incorrect to say I started and finished at he US border. Just before noon, I arrived at the northern terminus of the PCT. It came faster than I thought it would and I had it all to myself. I didn't cry. I didn't yell. I was just happy. Four months of hiking was over. I accomplished my goal. It was an amazing feeling. ![photo2](/img/The EndPost2.JPG) Not too long later a woman showed up from the Canadian side. She was waiting for Bubba and Lunch to finish. I told her I had been hiking with them and they should be there soon. She took my picture and we talked while I ate lunch. Everyone showed up and we celebrated at the monument. We shared stories and then hiked out. It's another 8 miles from the border to Manning Park. It went by fast. What's 8 miles after you've done 2650? At the resort I got some food and checked into my hotel room. I went to the pool and hung out for a few hours. Finishing something like this is incredible. As I look back at what I had to go through, I can't believe I did it. Thank you to everyone that helped me along the way. The packages, the places to stay, the rides, and the support of everyone made this possible. Walking was the easy part.
{ "content_hash": "d76f15892bfdbb6cdf927478960f5b3b", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 322, "avg_line_length": 75.96551724137932, "alnum_prop": 0.7494325919201089, "repo_name": "blladnar/blladnar.github.io", "id": "d83ad5d34294e49df76db52bdc95529508718216", "size": "2207", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "_posts/2017-09-12-The-End.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "33822" }, { "name": "HTML", "bytes": "1942623" }, { "name": "JavaScript", "bytes": "105327" }, { "name": "PHP", "bytes": "2484" }, { "name": "Ruby", "bytes": "2442" } ], "symlink_target": "" }
export default { log() { // Change this after the server is started to test console.log('First log...'); } };
{ "content_hash": "6d4f8ab55f11575b65d72eda7f045d5e", "timestamp": "", "source": "github", "line_count": 6, "max_line_length": 54, "avg_line_length": 20.333333333333332, "alnum_prop": 0.5983606557377049, "repo_name": "TheDutchCoder/webpack-guides-code-examples", "id": "2e773ce323256d3221f97b6ce1456f04fc73094a", "size": "122", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "examples/hot-module-replacement/src/library.js", "mode": "33188", "license": "mit", "language": [ { "name": "Shell", "bytes": "305" } ], "symlink_target": "" }
namespace Microsoft.Azure.Management.NotificationHubs { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// NotificationHubsOperations operations. /// </summary> public partial interface INotificationHubsOperations { /// <summary> /// Checks the availability of the given notificationHub in a /// namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// The notificationHub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<CheckAvailabilityResult>> CheckNotificationHubAvailabilityWithHttpMessagesAsync(string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Update a NotificationHub in a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update a NotificationHub /// Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NotificationHubResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a notification hub associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<NotificationHubResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates/Updates an authorization rule for a NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a notificationHub authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an authorization rule for a NotificationHub by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the Primary and Secondary ConnectionStrings to the /// NotificationHub /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the Primary/Secondary Keys to the NotificationHub /// Authorization Rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='authorizationRuleName'> /// The connection string of the NotificationHub for the specified /// authorizationRule. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate the NotificationHub Authorization /// Rule Key. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, PolicykeyResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the PNS Credentials associated with a notification hub . /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='notificationHubName'> /// The notification hub name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<PnsCredentialsResource>> GetPnsCredentialsWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the notification hubs associated with a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the authorization rules for a NotificationHub. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
{ "content_hash": "b124ea923dc9d3e9df70f6e9a040bd34", "timestamp": "", "source": "github", "line_count": 419, "max_line_length": 422, "avg_line_length": 49.21002386634845, "alnum_prop": 0.6254910519423832, "repo_name": "pilor/azure-sdk-for-net", "id": "e6e7b808df441601d92149801ca5d5a53c690b55", "size": "20972", "binary": false, "copies": "7", "ref": "refs/heads/psSdkJson6", "path": "src/SDKs/NotificationHubs/Management.NotificationHubs/Generated/INotificationHubsOperations.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "18102" }, { "name": "C#", "bytes": "117130489" }, { "name": "JavaScript", "bytes": "7875" }, { "name": "PowerShell", "bytes": "105037" }, { "name": "Shell", "bytes": "31578" }, { "name": "XSLT", "bytes": "6114" } ], "symlink_target": "" }
 namespace FluentExample { public partial class Coffee { public int RawOunces { get; private set; } public string Ounces { get { return RawOunces + " oz"; } } public Coffee WithOuncesToServe(int ounces) { RawOunces = ounces; return this; } } }
{ "content_hash": "f2afef0d92b86c44c8f97da8d6d7b088", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 60, "avg_line_length": 16.625, "alnum_prop": 0.6691729323308271, "repo_name": "kenwilcox/FluentExample", "id": "afed117c1da727894e17ab02aa7150ad6214bf4e", "size": "268", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "FluentExample/Coffee.WithOuncesToServe.cs", "mode": "33188", "license": "mit", "language": [ { "name": "C#", "bytes": "3896" } ], "symlink_target": "" }
package main import ( "github.com/stretchr/testify/assert" "testing" ) func Test_ToStringWithoutKeys(t *testing.T) { env := Environment{Name: "production"} assert.Equal(t, env.ToString(), "") } func Test_ToStringWithKeys(t *testing.T) { env := Environment{ Name: "production", Keys: []Key{ Key{Name: "foo", Value: "bar"}, Key{Name: "hello", Value: "world"}, }, } assert.Equal(t, env.ToString(), "FOO=bar\nHELLO=world") } func Test_readEnvironments(t *testing.T) { envs := readEnvironments("./examples/myapp") assert.Equal(t, len(envs), 2) assert.Equal(t, envs[0].Name, "production") assert.Equal(t, len(envs[0].Keys), 4) assert.Equal(t, len(envs[0].Hosts), 3) assert.Equal(t, envs[0].Hosts, []string{"192.168.1.1", "192.168.1.2", "192.168.1.3"}) assert.Equal(t, envs[0].Token, "foo") assert.Equal(t, envs[1].Name, "staging") assert.Equal(t, len(envs[1].Keys), 4) assert.Equal(t, len(envs[1].Hosts), 0) assert.Equal(t, envs[1].Token, "") } func Test_HostEnabled(t *testing.T) { env := Environment{Name: "foo", Hosts: []string{"foo"}} assert.False(t, env.HostEnabled("bar")) assert.True(t, env.HostEnabled("foo")) }
{ "content_hash": "5bdd1926332ca1e6c3f4c638b23bcacc", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 86, "avg_line_length": 24.617021276595743, "alnum_prop": 0.6525496974935178, "repo_name": "sosedoff/envd", "id": "afd3199a0a7e84fab16c617026d439e135296e37", "size": "1157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "environment_test.go", "mode": "33188", "license": "mit", "language": [ { "name": "Go", "bytes": "13842" }, { "name": "Makefile", "bytes": "159" } ], "symlink_target": "" }
<html> <head> <title>Complex Layout</title> <link rel="stylesheet" type="text/css" href="../../resources/css/ext-all.css" /> <style type="text/css"> html, body { font:normal 12px verdana; margin:0; padding:0; border:0 none; overflow:hidden; height:100%; } p { margin:5px; } .settings { background-image:url(../shared/icons/fam/folder_wrench.png); } .nav { background-image:url(../shared/icons/fam/folder_go.png); } </style> <!-- GC --> <!-- LIBS --> <script type="text/javascript" src="../../adapter/ext/ext-base.js"></script> <!-- ENDLIBS --> <script type="text/javascript" src="../../ext-all.js"></script> <!-- EXAMPLES --> <script type="text/javascript" src="../shared/examples.js"></script> <script type="text/javascript"> Ext.onReady(function(){ // NOTE: This is an example showing simple state management. During development, // it is generally best to disable state management as dynamically-generated ids // can change across page loads, leading to unpredictable results. The developer // should ensure that stable state ids are set for stateful components in real apps. Ext.state.Manager.setProvider(new Ext.state.CookieProvider()); var viewport = new Ext.Viewport({ layout: 'border', items: [ // create instance immediately new Ext.BoxComponent({ region: 'north', height: 32, // give north and south regions a height autoEl: { tag: 'div', html:'<p>north - generally for menus, toolbars and/or advertisements</p>' } }), { // lazily created panel (xtype:'panel' is default) region: 'south', contentEl: 'south', split: true, height: 100, minSize: 100, maxSize: 200, collapsible: true, title: 'South', margins: '0 0 0 0' }, { region: 'east', title: 'East Side', collapsible: true, split: true, width: 225, // give east and west regions a width minSize: 175, maxSize: 400, margins: '0 5 0 0', layout: 'fit', // specify layout manager for items items: // this TabPanel is wrapped by another Panel so the title will be applied new Ext.TabPanel({ border: false, // already wrapped so don't add another border activeTab: 1, // second tab initially active tabPosition: 'bottom', items: [{ html: '<p>A TabPanel component can be a region.</p>', title: 'A Tab', autoScroll: true }, new Ext.grid.PropertyGrid({ title: 'Property Grid', closable: true, source: { "(name)": "Properties Grid", "grouping": false, "autoFitColumns": true, "productionQuality": false, "created": new Date(Date.parse('10/15/2006')), "tested": false, "version": 0.01, "borderWidth": 1 } })] }) }, { region: 'west', id: 'west-panel', // see Ext.getCmp() below title: 'West', split: true, width: 200, minSize: 175, maxSize: 400, collapsible: true, margins: '0 0 0 5', layout: { type: 'accordion', animate: true }, items: [{ contentEl: 'west', title: 'Navigation', border: false, iconCls: 'nav' // see the HEAD section for style used }, { title: 'Settings', html: '<p>Some settings in here.</p>', border: false, iconCls: 'settings' }] }, // in this instance the TabPanel is not wrapped by another panel // since no title is needed, this Panel is added directly // as a Container new Ext.TabPanel({ region: 'center', // a center region is ALWAYS required for border layout deferredRender: false, activeTab: 0, // first tab initially active items: [{ contentEl: 'center1', title: 'Close Me', closable: true, autoScroll: true }, { contentEl: 'center2', title: 'Center Panel', autoScroll: true }] })] }); // get a reference to the HTML element with id "hideit" and add a click listener to it Ext.get("hideit").on('click', function(){ // get a reference to the Panel that was created with id = 'west-panel' var w = Ext.getCmp('west-panel'); // expand or collapse that Panel based on its collapsed property state w.collapsed ? w.expand() : w.collapse(); }); }); </script> </head> <body> <!-- use class="x-hide-display" to prevent a brief flicker of the content --> <div id="west" class="x-hide-display"> <p>Hi. I'm the west panel.</p> </div> <div id="center2" class="x-hide-display"> <a id="hideit" href="#">Toggle the west region</a> <p>My closable attribute is set to false so you can't close me. The other center panels can be closed.</p> <p>The center panel automatically grows to fit the remaining space in the container that isn't taken up by the border regions.</p> <hr> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed metus nibh, sodales a, porta at, vulputate eget, dui. Pellentesque ut nisl. Maecenas tortor turpis, interdum non, sodales non, iaculis ac, lacus. Vestibulum auctor, tortor quis iaculis malesuada, libero lectus bibendum purus, sit amet tincidunt quam turpis vel lacus. In pellentesque nisl non sem. Suspendisse nunc sem, pretium eget, cursus a, fringilla vel, urna. Aliquam commodo ullamcorper erat. Nullam vel justo in neque porttitor laoreet. Aenean lacus dui, consequat eu, adipiscing eget, nonummy non, nisi. Morbi nunc est, dignissim non, ornare sed, luctus eu, massa. Vivamus eget quam. Vivamus tincidunt diam nec urna. Curabitur velit. Quisque dolor magna, ornare sed, elementum porta, luctus in, leo.</p> <p>Donec quis dui. Sed imperdiet. Nunc consequat, est eu sollicitudin gravida, mauris ligula lacinia mauris, eu porta dui nisl in velit. Nam congue, odio id auctor nonummy, augue lectus euismod nunc, in tristique turpis dolor sed urna. Donec sit amet quam eget diam fermentum pharetra. Integer tincidunt arcu ut purus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Nulla blandit malesuada odio. Nam augue. Aenean molestie sapien in mi. Suspendisse tincidunt. Pellentesque tempus dui vitae sapien. Donec aliquam ipsum sit amet pede. Sed scelerisque mi a erat. Curabitur rutrum ullamcorper risus. Maecenas et lorem ut felis dictum viverra. Fusce sem. Donec pharetra nibh sit amet sapien.</p> <p>Aenean ut orci sed ligula consectetuer pretium. Aliquam odio. Nam pellentesque enim. Nam tincidunt condimentum nisi. Maecenas convallis luctus ligula. Donec accumsan ornare risus. Vestibulum id magna a nunc posuere laoreet. Integer iaculis leo vitae nibh. Nam vulputate, mauris vitae luctus pharetra, pede neque bibendum tellus, facilisis commodo diam nisi eget lacus. Duis consectetuer pulvinar nisi. Cras interdum ultricies sem. Nullam tristique. Suspendisse elementum purus eu nisl. Nulla facilisi. Phasellus ultricies ullamcorper lorem. Sed euismod ante vitae lacus. Nam nunc leo, congue vehicula, luctus ac, tempus non, ante. Morbi suscipit purus a nulla. Sed eu diam.</p> <p>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras imperdiet felis id velit. Ut non quam at sem dictum ullamcorper. Vestibulum pharetra purus sed pede. Aliquam ultrices, nunc in varius mattis, felis justo pretium magna, eget laoreet justo eros id eros. Aliquam elementum diam fringilla nulla. Praesent laoreet sapien vel metus. Cras tempus, sapien condimentum dictum dapibus, lorem augue fringilla orci, ut tincidunt eros nisi eget turpis. Nullam nunc nunc, eleifend et, dictum et, pharetra a, neque. Ut feugiat. Aliquam erat volutpat. Donec pretium odio nec felis. Phasellus sagittis lacus eget sapien. Donec est. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p> <p>Vestibulum semper. Nullam non odio. Aliquam quam. Mauris eu lectus non nunc auctor ullamcorper. Sed tincidunt molestie enim. Phasellus lobortis justo sit amet quam. Duis nulla erat, varius a, cursus in, tempor sollicitudin, mauris. Aliquam mi velit, consectetuer mattis, consequat tristique, pulvinar ac, nisl. Aliquam mattis vehicula elit. Proin quis leo sed tellus scelerisque molestie. Quisque luctus. Integer mattis. Donec id augue sed leo aliquam egestas. Quisque in sem. Donec dictum enim in dolor. Praesent non erat. Nulla ultrices vestibulum quam.</p> <p>Duis hendrerit, est vel lobortis sagittis, tortor erat scelerisque tortor, sed pellentesque sem enim id metus. Maecenas at pede. Nulla velit libero, dictum at, mattis quis, sagittis vel, ante. Phasellus faucibus rutrum dui. Cras mauris elit, bibendum at, feugiat non, porta id, neque. Nulla et felis nec odio mollis vehicula. Donec elementum tincidunt mauris. Duis vel dui. Fusce iaculis enim ac nulla. In risus.</p> <p>Donec gravida. Donec et enim. Morbi sollicitudin, lacus a facilisis pulvinar, odio turpis dapibus elit, in tincidunt turpis felis nec libero. Nam vestibulum tempus ipsum. In hac habitasse platea dictumst. Nulla facilisi. Donec semper ligula. Donec commodo tortor in quam. Etiam massa. Ut tempus ligula eget tellus. Curabitur id velit ut velit varius commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Fusce ornare pellentesque libero. Nunc rhoncus. Suspendisse potenti. Ut consequat, leo eu accumsan vehicula, justo sem lobortis elit, ac sollicitudin ipsum neque nec ante.</p> <p>Aliquam elementum mauris id sem. Vivamus varius, est ut nonummy consectetuer, nulla quam bibendum velit, ac gravida nisi felis sit amet urna. Aliquam nec risus. Maecenas lacinia purus ut velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse sit amet dui vitae lacus fermentum sodales. Donec varius dapibus nisl. Praesent at velit id risus convallis bibendum. Aliquam felis nibh, rutrum nec, blandit non, mattis sit amet, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam varius dignissim nibh. Quisque id orci ac ante hendrerit molestie. Aliquam malesuada enim non neque.</p> </div> <div id="center1" class="x-hide-display"> <p><b>Done reading me? Close me by clicking the X in the top right corner.</b></p> <p>Vestibulum semper. Nullam non odio. Aliquam quam. Mauris eu lectus non nunc auctor ullamcorper. Sed tincidunt molestie enim. Phasellus lobortis justo sit amet quam. Duis nulla erat, varius a, cursus in, tempor sollicitudin, mauris. Aliquam mi velit, consectetuer mattis, consequat tristique, pulvinar ac, nisl. Aliquam mattis vehicula elit. Proin quis leo sed tellus scelerisque molestie. Quisque luctus. Integer mattis. Donec id augue sed leo aliquam egestas. Quisque in sem. Donec dictum enim in dolor. Praesent non erat. Nulla ultrices vestibulum quam.</p> <p>Duis hendrerit, est vel lobortis sagittis, tortor erat scelerisque tortor, sed pellentesque sem enim id metus. Maecenas at pede. Nulla velit libero, dictum at, mattis quis, sagittis vel, ante. Phasellus faucibus rutrum dui. Cras mauris elit, bibendum at, feugiat non, porta id, neque. Nulla et felis nec odio mollis vehicula. Donec elementum tincidunt mauris. Duis vel dui. Fusce iaculis enim ac nulla. In risus.</p> <p>Donec gravida. Donec et enim. Morbi sollicitudin, lacus a facilisis pulvinar, odio turpis dapibus elit, in tincidunt turpis felis nec libero. Nam vestibulum tempus ipsum. In hac habitasse platea dictumst. Nulla facilisi. Donec semper ligula. Donec commodo tortor in quam. Etiam massa. Ut tempus ligula eget tellus. Curabitur id velit ut velit varius commodo. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Fusce ornare pellentesque libero. Nunc rhoncus. Suspendisse potenti. Ut consequat, leo eu accumsan vehicula, justo sem lobortis elit, ac sollicitudin ipsum neque nec ante.</p> <p>Aliquam elementum mauris id sem. Vivamus varius, est ut nonummy consectetuer, nulla quam bibendum velit, ac gravida nisi felis sit amet urna. Aliquam nec risus. Maecenas lacinia purus ut velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse sit amet dui vitae lacus fermentum sodales. Donec varius dapibus nisl. Praesent at velit id risus convallis bibendum. Aliquam felis nibh, rutrum nec, blandit non, mattis sit amet, magna. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam varius dignissim nibh. Quisque id orci ac ante hendrerit molestie. Aliquam malesuada enim non neque.</p> </div> <div id="props-panel" class="x-hide-display" style="width:200px;height:200px;overflow:hidden;"> </div> <div id="south" class="x-hide-display"> <p>south - generally for informational stuff, also could be for status bar</p> </div> </body> </html>
{ "content_hash": "10d9d42010fb1ddf36890e0d60dd04fe", "timestamp": "", "source": "github", "line_count": 188, "max_line_length": 784, "avg_line_length": 78.75531914893617, "alnum_prop": 0.6364311765500473, "repo_name": "kenglishhi/mest", "id": "efb19d59abcc913fdb8477d8d160b55651776045", "size": "14806", "binary": false, "copies": "11", "ref": "refs/heads/master", "path": "public/javascripts/ext-3.0.0/examples/layout/complex.html", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "11052021" }, { "name": "PHP", "bytes": "50334" }, { "name": "Ruby", "bytes": "210523" }, { "name": "Shell", "bytes": "324" } ], "symlink_target": "" }
package org.opensextant.extractors.test; import static org.junit.Assert.assertEquals; import org.apache.commons.text.similarity.LevenshteinDistance; import org.junit.Test; public class TestNameScoreUtils { @Test public void test() { String a = "who dat"; String b = "me too"; int editDist = LevenshteinDistance.getDefaultInstance().apply(a, b); assertEquals(6, editDist); editDist = LevenshteinDistance.getDefaultInstance().apply(a, a); assertEquals(0, editDist); String c = "who dem"; editDist = LevenshteinDistance.getDefaultInstance().apply(a, c); assertEquals(2, editDist); } }
{ "content_hash": "90353bc8d2a841ab1d421e5281725b85", "timestamp": "", "source": "github", "line_count": 24, "max_line_length": 76, "avg_line_length": 28, "alnum_prop": 0.6741071428571429, "repo_name": "OpenSextant/Xponents", "id": "a191a157a7e0bb6fdaf553107cd2c6538ad0d05f", "size": "672", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/test/java/org/opensextant/extractors/test/TestNameScoreUtils.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "72623" }, { "name": "Java", "bytes": "1344792" }, { "name": "Python", "bytes": "343525" }, { "name": "Shell", "bytes": "106459" } ], "symlink_target": "" }
package com.scipionyx.butterflyeffect.frontend.core.ui.view.panel.bottom; import com.vaadin.ui.Alignment; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; /** * * @author Renato Mendes * */ public class BottomPanel extends HorizontalLayout { /** * */ private static final long serialVersionUID = 5264502784084569574L; /** * */ public void build() { // this.setSizeFull(); this.setMargin(true); Label title = new Label(); title.setCaption("Copyright ® 2015 - Scipionyx Software"); this.addComponent(title); this.setComponentAlignment(title, Alignment.MIDDLE_CENTER); } }
{ "content_hash": "94fbb948247aa8dad81033a944e2b3cc", "timestamp": "", "source": "github", "line_count": 36, "max_line_length": 73, "avg_line_length": 17.52777777777778, "alnum_prop": 0.7083993660855784, "repo_name": "scipionyx/ButterflyEffect", "id": "fd9add341e0407d1e3361290e98abac9309ee641", "size": "632", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "butterfly-effect-frontend-core/src/main/java/com/scipionyx/butterflyeffect/frontend/core/ui/view/panel/bottom/BottomPanel.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "293796" }, { "name": "Java", "bytes": "253394" }, { "name": "Shell", "bytes": "929" } ], "symlink_target": "" }
Provides a method to convert json markup into actual views. ### builder.build(markup) Converts `markup` into views and returns `Collection` containing those views. build({ view: 'Button', label: 'Hello World' }); `build` is extremely simple and strait-forward: it will create a view object based on `view` property and copy remaining properties using the `utils.prop` function. _Build steps_ First it will resolve the actual view class using the `view` property. If `view` is a class object it will be used without transformation. If `view` is a `String` build will try to find object with the given path in `builder.viewNamespaces`. After the `view` is resolved it will be instantiated with the optional `init` parameter. `{ vertical: true }` will be passed to `new SplitPane`. build({ view: 'SplitPane', init: { vertical: true }) Once the view object is ready `build` will simply copy all the remaining properties to the build object using `utils.prop`. build({ view: 'SplitPane', init: { vertical: true }, handlePosition: 100) ... equals to: var s = new SplitPane({ vertical: true }); s.handlePosition(300); There's no additional magic here. For example `childViews` will be just passed as a json array to the view. And view will build those `childViews` itself. ### builder.viewNamespaces Array containing all namespaces to search when resolving view class.
{ "content_hash": "f1a238dcde55a21484f4757b59391e38", "timestamp": "", "source": "github", "line_count": 41, "max_line_length": 78, "avg_line_length": 34.19512195121951, "alnum_prop": 0.7368045649072753, "repo_name": "GunioRobot/uki", "id": "d143509fd8c50a601cb85e74edadac6b24bdec36", "size": "1414", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/core/builder.markdown", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "178235" } ], "symlink_target": "" }
package com.graphhopper.storage; /** * Manages in-memory DataAccess objects. * <p/> * @see RAMDataAccess * @see RAMIntDataAccess * @author Peter Karich */ public class RAMDirectory extends GHDirectory { public RAMDirectory() { this("", false); } public RAMDirectory( String location ) { this(location, false); } /** * @param store true if you want that the RAMDirectory can be loaded or saved on demand, false * if it should be entirely in RAM */ public RAMDirectory( String _location, boolean store ) { super(_location, store ? DAType.RAM_STORE : DAType.RAM); } }
{ "content_hash": "a6c8a40f30ebd3e69072c243a1d6e936", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 98, "avg_line_length": 21.096774193548388, "alnum_prop": 0.6314984709480123, "repo_name": "engaric/graphhopper", "id": "8bc65dde6822160bce93ffd4c545b113ba109c55", "size": "1471", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "core/src/main/java/com/graphhopper/storage/RAMDirectory.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "29019" }, { "name": "Gherkin", "bytes": "257135" }, { "name": "HTML", "bytes": "18540" }, { "name": "Java", "bytes": "2928898" }, { "name": "JavaScript", "bytes": "376593" }, { "name": "Shell", "bytes": "23743" } ], "symlink_target": "" }
import Feature from './feature'; import * as Constants from '../constants'; import hat from 'hat'; import MultiPoint from './point'; import MultiLineString from './line_string'; import MultiPolygon from './polygon'; const models = { MultiPoint, MultiLineString, MultiPolygon }; const takeAction = (features, action, path, lng, lat) => { const parts = path.split('.'); const idx = parseInt(parts[0], 10); const tail = (!parts[1]) ? null : parts.slice(1).join('.'); return features[idx][action](tail, lng, lat); }; const MultiFeature = function(ctx, geojson) { Feature.call(this, ctx, geojson); delete this.coordinates; this.model = models[geojson.geometry.type]; if (this.model === undefined) throw new TypeError(`${geojson.geometry.type} is not a valid type`); this.features = this._coordinatesToFeatures(geojson.geometry.coordinates); }; MultiFeature.prototype = Object.create(Feature.prototype); MultiFeature.prototype._coordinatesToFeatures = function(coordinates) { const Model = this.model.bind(this); return coordinates.map(coords => new Model(this.ctx, { id: hat(), type: Constants.geojsonTypes.FEATURE, properties: {}, geometry: { coordinates: coords, type: this.type.replace('Multi', '') } })); }; MultiFeature.prototype.isValid = function() { return this.features.every(f => f.isValid()); }; MultiFeature.prototype.setCoordinates = function(coords) { this.features = this._coordinatesToFeatures(coords); this.changed(); }; MultiFeature.prototype.getCoordinate = function(path) { return takeAction(this.features, 'getCoordinate', path); }; MultiFeature.prototype.getCoordinates = function() { return JSON.parse(JSON.stringify(this.features.map((f) => { if (f.type === Constants.geojsonTypes.POLYGON) return f.getCoordinates(); return f.coordinates; }))); }; MultiFeature.prototype.updateCoordinate = function(path, lng, lat) { takeAction(this.features, 'updateCoordinate', path, lng, lat); this.changed(); }; MultiFeature.prototype.addCoordinate = function(path, lng, lat) { takeAction(this.features, 'addCoordinate', path, lng, lat); this.changed(); }; MultiFeature.prototype.removeCoordinate = function(path) { takeAction(this.features, 'removeCoordinate', path); this.changed(); }; MultiFeature.prototype.getFeatures = function() { return this.features; }; export default MultiFeature;
{ "content_hash": "342c9908bc5417b2569a09f572d8c2ba", "timestamp": "", "source": "github", "line_count": 85, "max_line_length": 100, "avg_line_length": 28.352941176470587, "alnum_prop": 0.7091286307053942, "repo_name": "mapbox/gl-draw", "id": "4e9f9f38aca5496d8aa7394b497f19bb01b670dc", "size": "2410", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/feature_types/multi_feature.js", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1389" }, { "name": "HTML", "bytes": "5317" }, { "name": "JavaScript", "bytes": "69490" } ], "symlink_target": "" }
package com.palomamobile.android.sdk.user; import android.support.annotation.Nullable; import com.palomamobile.android.sdk.auth.IUserCredentialsProvider; import com.palomamobile.android.sdk.core.IServiceManager; import com.palomamobile.android.sdk.core.qos.BaseRetryPolicyAwareJob; /** * Methods in this interface provide convenient job creation methods that provide easy access * to the underlying {@link IUserService} functionality. App developers can either use {@link BaseRetryPolicyAwareJob} * job instances returned by the {@code createJob...()} methods, or create custom jobs that invoke * methods of the {@link IUserService} returned by {@link IServiceManager#getService()} * * <br/> * To get a concrete implementation of this interface call * {@code ServiceSupport.Instance.getServiceManager(IUserManager.class)} * <br/> * * <br/> * */ public interface IUserManager extends IUserCredentialsProvider, IServiceManager<IUserService> { /** * Synchronous call returns the current {@link User} from local cache. * * @return current user */ @Nullable User getUser(); }
{ "content_hash": "fdfb060f93ec4a9e71d6e2dc3a23d29a", "timestamp": "", "source": "github", "line_count": 31, "max_line_length": 118, "avg_line_length": 36, "alnum_prop": 0.7580645161290323, "repo_name": "PalomaMobile/paloma-android-sdk", "id": "dc0c9a193ccb5901d9ce93cfdbc5ec70d6e0fd31", "size": "1116", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "palomamobile-android-sdk-user/android-sdk-user-library/src/main/java/com/palomamobile/android/sdk/user/IUserManager.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "HTML", "bytes": "3782" }, { "name": "Java", "bytes": "549418" }, { "name": "Shell", "bytes": "1984" } ], "symlink_target": "" }
package com.yeungeek.mvvm.sample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Chronometer; import com.yeungeek.mvvm.sample.mvvm.glass.GlassActivity; import com.yeungeek.mvvm.sample.ui.GithubActivity; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button mGithubBtn; private Chronometer mTimer; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGithubBtn = findViewById(R.id.github_btn); mGithubBtn.setOnClickListener(this); mTimer = findViewById(R.id.glass_timer); findViewById(R.id.glass_btn).setOnClickListener(this); } @Override protected void onStart() { super.onStart(); mTimer.start(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.github_btn: startActivity(new Intent(this, GithubActivity.class)); break; case R.id.glass_btn: startActivity(new Intent(this, GlassActivity.class)); break; } } }
{ "content_hash": "f4ee8d8bcb1399a0a6f23a9e8703cf17", "timestamp": "", "source": "github", "line_count": 46, "max_line_length": 85, "avg_line_length": 28.782608695652176, "alnum_prop": 0.6722054380664653, "repo_name": "yeungeek/AndroidRoad", "id": "2edeebe71c447fbf8df5316442133612f53d0cd1", "size": "1324", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "MVVM-Arsenal/app/src/main/java/com/yeungeek/mvvm/sample/MainActivity.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "C++", "bytes": "5498" }, { "name": "CMake", "bytes": "1657" }, { "name": "GLSL", "bytes": "1721" }, { "name": "Java", "bytes": "771064" }, { "name": "Kotlin", "bytes": "107817" } ], "symlink_target": "" }
if RUBY_ENGINE == 'ruby' && RUBY_VERSION >= '2.2.3' if ENV['CI'] require 'codeclimate-test-reporter' CodeClimate::TestReporter.start else require 'simplecov' end begin require 'pry-byebug' rescue LoadError puts 'Pry unavailable' end end require 'rspec' require 'rspec/its' begin require 'celluloid/current' rescue LoadError warn 'Celluloid is old' require 'celluloid' end require 'celluloid/test' Celluloid.boot require 'sidekiq' require 'sidekiq/util' require 'sidekiq-unique-jobs' require 'sidekiq_unique_jobs/testing' require 'timecop' require 'rspec-sidekiq' Sidekiq::Testing.disable! Sidekiq.logger.level = "Logger::#{ENV.fetch('LOGLEVEL') { 'error' }.upcase}".constantize require 'sidekiq/redis_connection' REDIS_URL ||= ENV['REDIS_URL'] || 'redis://localhost/15'.freeze REDIS_NAMESPACE ||= 'unique-test'.freeze REDIS ||= Sidekiq::RedisConnection.create(url: REDIS_URL, namespace: REDIS_NAMESPACE) Sidekiq.configure_client do |config| config.redis = { url: REDIS_URL, namespace: REDIS_NAMESPACE } end Dir[File.join(File.dirname(__FILE__), 'support', '**', '*.rb')].each { |f| require f } RSpec.configure do |config| config.expect_with :rspec do |expectations| expectations.include_chain_clauses_in_custom_matcher_descriptions = true end config.mock_with :rspec do |mocks| mocks.verify_partial_doubles = true end config.filter_run :focus unless ENV['CI'] config.run_all_when_everything_filtered = true config.disable_monkey_patching! config.warnings = false config.default_formatter = 'doc' if config.files_to_run.one? config.order = :random Kernel.srand config.seed end RSpec::Sidekiq.configure do |config| # Clears all job queues before each example config.clear_all_enqueued_jobs = true # Whether to use terminal colours when outputting messages config.enable_terminal_colours = true # Warn when jobs are not enqueued to Redis but to a job array config.warn_when_jobs_not_processed_by_sidekiq = false end Dir[File.join(File.dirname(__FILE__), 'jobs', '**', '*.rb')].each { |f| require f }
{ "content_hash": "2030db944c65390cf46b443a296645bc", "timestamp": "", "source": "github", "line_count": 75, "max_line_length": 88, "avg_line_length": 27.88, "alnum_prop": 0.7216642754662841, "repo_name": "antek-drzewiecki/sidekiq-unique-jobs", "id": "5c0fb4866fc509b4ff1ebae1033d38dd9d9493f0", "size": "2091", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/spec_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Lua", "bytes": "773" }, { "name": "Ruby", "bytes": "69857" } ], "symlink_target": "" }
package org.springframework.richclient.application.support; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.binding.convert.ConversionService; import org.springframework.binding.form.FieldFaceSource; import org.springframework.binding.form.FormModel; import org.springframework.binding.form.support.MessageSourceFieldFaceSource; import org.springframework.binding.value.ValueChangeDetector; import org.springframework.binding.value.support.DefaultValueChangeDetector; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.MessageSource; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.MessageSourceAccessor; import org.springframework.context.support.ResourceBundleMessageSource; import org.springframework.context.support.ResourceMapFactoryBean; import org.springframework.core.enums.LabeledEnumResolver; import org.springframework.core.enums.StaticLabeledEnumResolver; import org.springframework.core.io.ClassPathResource; import org.springframework.richclient.application.ApplicationPageFactory; import org.springframework.richclient.application.ApplicationServices; import org.springframework.richclient.application.ApplicationWindowFactory; import org.springframework.richclient.application.DefaultConversionServiceFactoryBean; import org.springframework.richclient.application.PageComponentPaneFactory; import org.springframework.richclient.application.PageDescriptorRegistry; import org.springframework.richclient.application.ServiceNotFoundException; import org.springframework.richclient.application.ViewDescriptorRegistry; import org.springframework.richclient.application.config.ApplicationObjectConfigurer; import org.springframework.richclient.application.config.DefaultApplicationObjectConfigurer; import org.springframework.richclient.command.CommandServices; import org.springframework.richclient.command.config.CommandConfigurer; import org.springframework.richclient.command.config.DefaultCommandConfigurer; import org.springframework.richclient.command.support.DefaultCommandServices; import org.springframework.richclient.factory.ButtonFactory; import org.springframework.richclient.factory.ComponentFactory; import org.springframework.richclient.factory.DefaultButtonFactory; import org.springframework.richclient.factory.DefaultComponentFactory; import org.springframework.richclient.factory.DefaultMenuFactory; import org.springframework.richclient.factory.MenuFactory; import org.springframework.richclient.form.binding.BinderSelectionStrategy; import org.springframework.richclient.form.binding.BindingFactoryProvider; import org.springframework.richclient.form.binding.swing.SwingBinderSelectionStrategy; import org.springframework.richclient.form.binding.swing.SwingBindingFactoryProvider; import org.springframework.richclient.form.builder.FormComponentInterceptor; import org.springframework.richclient.form.builder.FormComponentInterceptorFactory; import org.springframework.richclient.image.DefaultIconSource; import org.springframework.richclient.image.DefaultImageSource; import org.springframework.richclient.image.IconSource; import org.springframework.richclient.image.ImageSource; import org.springframework.richclient.security.ApplicationSecurityManager; import org.springframework.richclient.security.SecurityControllerManager; import org.springframework.richclient.security.support.DefaultApplicationSecurityManager; import org.springframework.richclient.security.support.DefaultSecurityControllerManager; import org.springframework.richclient.util.Assert; import org.springframework.rules.RulesSource; import org.springframework.rules.reporting.DefaultMessageTranslatorFactory; import org.springframework.rules.reporting.MessageTranslatorFactory; import org.springframework.rules.support.DefaultRulesSource; import org.springframework.util.ClassUtils; /** * A default implementation of the ApplicationServices (service locator) interface. This implementation allows for the * direct registration of service implementations by using various setter methods (like * {@link #setImageSource(ImageSource)}). Service registry entries can also be added in bulk using the * {@link #setRegistryEntries(Map)} method. * <p> * Except in testing environments, this class will typically be instantiated in the application context and the various * service implementations will be set <b>BY ID</b>. The use of service bean ids instead of direct bean references is * to avoid numerous problems with cyclic dependencies and other order dependent operations. So, a typical incarnation * might look like this: * * <pre> * &lt;bean id=&quot;applicationServices&quot; * class=&quot;org.springframework.richclient.application.support.DefaultApplicationServices&quot;&gt; * &lt;property name=&quot;applicationObjectConfigurerId&quot;&gt;&lt;idref bean=&quot;applicationObjectConfigurer&quot; /&gt;&lt;/property&gt; * &lt;property name=&quot;imageSourceId&quot;&gt;&lt;idref bean=&quot;imageSource&quot;/&gt;&lt;/property&gt; * &lt;property name=&quot;rulesSourceId&quot;&gt;&lt;idref bean=&quot;rulesSource&quot;/&gt;&lt;/property&gt; * &lt;property name=&quot;conversionServiceId&quot;&gt;&lt;idref bean=&quot;conversionService&quot;/&gt;&lt;/property&gt; * &lt;property name=&quot;formComponentInterceptorFactoryId&quot;&gt;&lt;idref bean=&quot;formComponentInterceptorFactory&quot;/&gt;&lt;/property&gt; * &lt;/bean&gt; * </pre> * * Note the use of the <code>idref</code> form instead of just using a string value. This is the preferred syntax in * order to avoid having misspelled bean names go unreported. * <p> * Which service implementation is returned by {@link #getService(Class)} will be determined through the following * steps: * <ol> * <li>Consult the current registry of service implementations which have been explicitly defined through bean * definition. If a registry entry was made using a bean id, this is the point at which it will be dereferenced into the * actual bean implementation. So, the bean impementation will not be referenced until it is requested.</li> * <li>If the service impl. is not found yet the short string name of the service' Java class in decapitalized * JavaBeans property format will be used to lookup the service implementation in the current application context.<br/> * If the service class is <code>org.springframework.richclient.factory.MenuFactory</code> the bean name * <code>menuFactory</code> will be used to find the bean</li> * <li>If the service impl. is not found yet and a default implementation can be provided, it will be constructed at * that time. Default implementations are provided for essentially all services referenced by the platform.</li> * </ol> * * @author Larry Streepy */ public class DefaultApplicationServices implements ApplicationServices, ApplicationContextAware { private static final Log logger = LogFactory.getLog( DefaultApplicationServices.class ); /** Map of services, keyed by service type (class). */ private final Map services = Collections.synchronizedMap( new HashMap() ); /** Map of service types to default implementation builders. */ private static final Map serviceImplBuilders = new HashMap(); /** Application context with needed bean definitions. */ private ApplicationContext applicationContext; /** ID of the ApplicationObjectConfigurer bean. */ private String applicationObjectConfigurerBeanId; /** * Default Constructor. */ public DefaultApplicationServices() { } /** * Constuct using the given application context. * * @param applicationContext to use for locating named services (beans) */ public DefaultApplicationServices( ApplicationContext applicationContext ) { setApplicationContext( applicationContext ); } /** * Set the application context. We are ApplicationContextAware so this will happen * automatically if we are defined in the context. If not, then this method should be * called directly. */ public void setApplicationContext( ApplicationContext applicationContext ) { this.applicationContext = applicationContext; } /** * @return application context */ public ApplicationContext getApplicationContext() { if (applicationContext == null) { applicationContext = new GenericApplicationContext(); } return applicationContext; } /** * Get a service of the indicated type. If no service definition for the requested * type is found in the application context, then a reasonable default implementation * will be created. * * @param serviceType Type of service being requested * @return Service instance * @throws ServiceNotFoundException if the service is not found and no suitable * default implementation is available. */ public synchronized Object getService( Class serviceType ) { Assert.required( serviceType, "serviceType" ); Object service = services.get( serviceType ); if( service == null ) { service = getServiceForClassType(serviceType); if (service == null) { service = getDefaultImplementation(serviceType); } if (service != null) { services.put(serviceType, service); } } else { // Runtime derefence of refid's if( service instanceof String ) { service = getApplicationContext().getBean( (String) service, serviceType ); services.put( serviceType, service ); } } // If we still don't have an implementation, then it's a bust if( service == null ) { throw new ServiceNotFoundException(serviceType); } return service; } public boolean containsService( Class serviceType ) { Assert.required( serviceType, "serviceType" ); return services.containsKey( serviceType ) || containsServiceForClassType(serviceType) || containsDefaultImplementation( serviceType ); } /** * Add entries to the service registry. This is typically called from a bean * definition in the application context. The entryMap parameter must be a map with * keys that are either class instances (the serviceType) or the String name of the * class and values that are the implementation to use for that service or an idref to * a bean that is the implementation (passed as a String). * * @param entryMap Map of entries */ public void setRegistryEntries( Map entryMap ) { Iterator iter = entryMap.entrySet().iterator(); while( iter.hasNext() ) { Map.Entry entry = (Map.Entry) iter.next(); Class serviceType = null; Object key = entry.getKey(); // If the key is a String, convert it to a class if( key instanceof String ) { try { serviceType = Class.forName( (String) key ); } catch( ClassNotFoundException e ) { logger.error( "Unable to convert key to Class", e ); } } else if( key instanceof Class ) { serviceType = (Class) key; } else { logger.error( "Invalid service entry key; must be String or Class, got: " + key.getClass() ); } // If we got something usable, then add the map entry if( serviceType != null ) { services.put( serviceType, entry.getValue() ); } } } /** * Set the application object configurer service implementation. * * @param applicationObjectConfigurer */ public void setApplicationObjectConfigurer( ApplicationObjectConfigurer applicationObjectConfigurer ) { services.put( ApplicationObjectConfigurer.class, applicationObjectConfigurer ); } /** * Set the application object configurer service implementation bean id * * @param applicationObjectConfigurerId bean id */ public void setApplicationObjectConfigurerId( String applicationObjectConfigurerId ) { services.put( ApplicationObjectConfigurer.class, applicationObjectConfigurerId ); } /** * Set the application security manager service implementation. * * @param applicationSecurityManager instance to use */ public void setApplicationSecurityManager( ApplicationSecurityManager applicationSecurityManager ) { services.put( ApplicationSecurityManager.class, applicationSecurityManager ); } /** * Set the application security manager service implementation bean id * * @param applicationSecurityManagerId bean id */ public void setApplicationSecurityManagerId( String applicationSecurityManagerId ) { services.put( ApplicationSecurityManager.class, applicationSecurityManagerId ); } /** * Set the <code>ApplicationWindow</code> factory service implementation * * @param factory */ public void setApplicationWindowFactory( ApplicationWindowFactory factory ) { services.put( ApplicationWindowFactory.class, factory ); } /** * Set the <code>ApplicationWindow</code> factory service implementation bean id * * @param factoryId bean id */ public void setApplicationWindowFactoryId( String factoryId ) { services.put( ApplicationWindowFactory.class, factoryId ); } /** * Set the <code>ApplicationPage</code> factory service implementation * * @param factory */ public void setApplicationPageFactory( ApplicationPageFactory factory ) { services.put( ApplicationPageFactory.class, factory ); } /** * Set the <code>ApplicationPage</code> factory service implementation bean id * * @param factoryId bean id */ public void setApplicationPageFactoryId( String factoryId ) { services.put( ApplicationPageFactory.class, factoryId ); } /** * Set the <code>PageComponentPane</code> factory service implementation bean * * @param factory bean id */ public void setPageComponentPaneFactory( PageComponentPaneFactory factory ) { services.put( PageComponentPaneFactory.class, factory ); } /** * Set the <code>PageComponentPane</code> factory service implementation bean id * * @param factoryId bean id */ public void setPageComponentPaneFactoryId( String factoryId ) { services.put( PageComponentPaneFactory.class, factoryId ); } /** * Set the binder selection strategy service implementation * * @param binderSelectionStrategy */ public void setBinderSelectionStrategy( BinderSelectionStrategy binderSelectionStrategy ) { services.put( BinderSelectionStrategy.class, binderSelectionStrategy ); } /** * Set the binder selection strategy service implementation bean id * * @param binderSelectionStrategyId bean id */ public void setBinderSelectionStrategyId( String binderSelectionStrategyId ) { services.put( BinderSelectionStrategy.class, binderSelectionStrategyId ); } /** * Set the binding factory provider service implementation * * @param bindingFactoryProvider */ public void setBindingFactoryProvider( BindingFactoryProvider bindingFactoryProvider ) { services.put( BindingFactoryProvider.class, bindingFactoryProvider ); } /** * Set the binding factory provider service implementation bean id * * @param bindingFactoryProviderId bean id */ public void setBindingFactoryProviderId( String bindingFactoryProviderId ) { services.put( BindingFactoryProvider.class, bindingFactoryProviderId ); } /** * Set the command services service implementation * * @param commandServices */ public void setCommandServices( CommandServices commandServices ) { services.put( CommandServices.class, commandServices ); } /** * Set the command services service implementation bean id * * @param commandServicesId bean id */ public void setCommandServicesId( String commandServicesId ) { services.put( CommandServices.class, commandServicesId ); } /** * Set the command configurer service implementation * * @param commandConfigurer */ public void setCommandConfigurer( CommandConfigurer commandConfigurer ) { services.put( CommandConfigurer.class, commandConfigurer ); } /** * Set the command configurer service implementation bean id * * @param commandConfigurerId bean id */ public void setCommandConfigurerId( String commandConfigurerId ) { services.put( CommandConfigurer.class, commandConfigurerId ); } /** * Set the button factory service implementation * * @param buttonFactory */ public void setButtonFactory( ButtonFactory buttonFactory ) { services.put( ButtonFactory.class, buttonFactory ); } /** * Set the button factory service implementation bean id * * @param buttonFactoryId bean id */ public void setButtonFactoryId( String buttonFactoryId ) { services.put( ButtonFactory.class, buttonFactoryId ); } /** * Set the menu factory service implementation * * @param menuFactory */ public void setMenuFactory( MenuFactory menuFactory ) { services.put( MenuFactory.class, menuFactory ); } /** * Set the menu factory service implementation bean id * * @param menuFactoryId bean id */ public void setMenuFactoryId( String menuFactoryId ) { services.put( MenuFactory.class, menuFactoryId ); } /** * Set the component factory service implementation * * @param componentFactory */ public void setComponentFactory( ComponentFactory componentFactory ) { services.put( ComponentFactory.class, componentFactory ); } /** * Set the component factory service implementation bean id * * @param componentFactoryId bean id */ public void setComponentFactoryId( String componentFactoryId ) { services.put( ComponentFactory.class, componentFactoryId ); } /** * Set the conversion service service implementation * * @param conversionService */ public void setConversionService( ConversionService conversionService ) { services.put( ConversionService.class, conversionService ); } /** * Set the conversion service service implementation bean id * * @param conversionServiceId bean id */ public void setConversionServiceId( String conversionServiceId ) { services.put( ConversionService.class, conversionServiceId ); } /** * Set the form component interceptor factory service implementation * * @param formComponentInterceptorFactory */ public void setFormComponentInterceptorFactory( FormComponentInterceptorFactory formComponentInterceptorFactory ) { services.put( FormComponentInterceptorFactory.class, formComponentInterceptorFactory ); } /** * Set the form component interceptor factory service implementation bean id * * @param formComponentInterceptorFactoryId bean id */ public void setFormComponentInterceptorFactoryId( String formComponentInterceptorFactoryId ) { services.put( FormComponentInterceptorFactory.class, formComponentInterceptorFactoryId ); } /** * Set the field face descriptor source service implementation * * @param fieldFaceSource */ public void setFieldFaceSource( FieldFaceSource fieldFaceSource ) { services.put( FieldFaceSource.class, fieldFaceSource ); } /** * Set the field face descriptor source service implementation bean id * * @param fieldFaceSourceId bean id */ public void setFieldFaceSourceId( String fieldFaceSourceId ) { services.put( FieldFaceSource.class, fieldFaceSourceId ); } /** * Set the icon source service implementation * * @param iconSource */ public void setIconSource( IconSource iconSource ) { services.put( IconSource.class, iconSource ); } /** * Set the icon source service implementation bean id * * @param iconSourceId bean id */ public void setIconSourceId( String iconSourceId ) { services.put( IconSource.class, iconSourceId ); } /** * Set the image source service implementation * * @param imageSource */ public void setImageSource( ImageSource imageSource ) { services.put( ImageSource.class, imageSource ); } /** * Set the image source service implementation bean id * * @param imageSourceId bean id */ public void setImageSourceId( String imageSourceId ) { services.put( ImageSource.class, imageSourceId ); } /** * Set the labeled enum resolver service implementation * * @param labeledEnumResolver */ public void setLabeledEnumResolver( LabeledEnumResolver labeledEnumResolver ) { services.put( LabeledEnumResolver.class, labeledEnumResolver ); } /** * Set the labeled enum resolver service implementation bean id * * @param labeledEnumResolverId bean id */ public void setLabeledEnumResolverId( String labeledEnumResolverId ) { services.put( LabeledEnumResolver.class, labeledEnumResolverId ); } /** * Set the message source service implementation * * @param messageSource */ public void setMessageSource( MessageSource messageSource ) { services.put( MessageSource.class, messageSource ); } /** * Set the message source service implementation bean id * * @param messageSourceId bean id */ public void setMessageSourceId( String messageSourceId ) { services.put( MessageSource.class, messageSourceId ); } /** * Set the message source accessor service implementation * * @param messageSourceAccessor */ public void setMessageSourceAccesor( MessageSourceAccessor messageSourceAccessor ) { services.put( MessageSourceAccessor.class, messageSourceAccessor ); } /** * Set the message source accessor service implementation bean id * * @param messageSourceAccessorId bean id */ public void setMessageSourceAccesorId( String messageSourceAccessorId ) { services.put( MessageSourceAccessor.class, messageSourceAccessorId ); } /** * Set the rules source service implementation * * @param rulesSource */ public void setRulesSource( RulesSource rulesSource ) { services.put( RulesSource.class, rulesSource ); } /** * Set the rules source service implementation bean id * * @param rulesSourceId bean id */ public void setRulesSourceId( String rulesSourceId ) { services.put( RulesSource.class, rulesSourceId ); } /** * Set the security controller manager service implementation * * @param securityControllerManager instance to use */ public void setSecurityControllerManager( SecurityControllerManager securityControllerManager ) { services.put( SecurityControllerManager.class, securityControllerManager ); } /** * Set the security controller manager service implementation bean id * * @param securityControllerManagerId bean id */ public void setSecurityControllerManagerId( String securityControllerManagerId ) { services.put( SecurityControllerManager.class, securityControllerManagerId ); } /** * Set the value change detector service imlpementation. * * @param valueChangeDetector instance to use */ public void setValueChangeDetector( ValueChangeDetector valueChangeDetector ) { services.put( ValueChangeDetector.class, valueChangeDetector ); } /** * Set the value change detector service imlpementation bean id * * @param valueChangeDetectorId bean id */ public void setValueChangeDetectorId( String valueChangeDetectorId ) { services.put( ValueChangeDetector.class, valueChangeDetectorId ); } /** * Set the view descriptor registry service implementation * * @param viewDescriptorRegistry */ public void setViewDescriptorRegistry( ViewDescriptorRegistry viewDescriptorRegistry ) { services.put( ViewDescriptorRegistry.class, viewDescriptorRegistry ); } /** * Set the page descriptor registry service implementation * * @param pageDescriptorRegistry */ public void setPageDescriptorRegistry( PageDescriptorRegistry pageDescriptorRegistry ) { services.put( PageDescriptorRegistry.class, pageDescriptorRegistry ); } /** * Set the message translator registry service implementation * * @param messageTranslatorFactory */ public void setMessageTranslatorFactory( MessageTranslatorFactory messageTranslatorFactory ) { services.put( MessageTranslatorFactory.class, messageTranslatorFactory ); } /** * Set the message translator registry service implementation bean id * * @param messageTranslatorFactory */ public void setMessageTranslatorFactoryId( String messageTranslatorFactoryId ) { services.put( MessageTranslatorFactory.class, messageTranslatorFactoryId ); } /** * Set the view descriptor registry service implementation bean id * * @param viewDescriptorRegistryId bean id */ public void setViewDescriptorRegistryId( String viewDescriptorRegistryId ) { services.put( ViewDescriptorRegistry.class, viewDescriptorRegistryId ); } /** * Set the page descriptor registry service implementation bean id * * @param pageDescriptorRegistryId bean id */ public void setPageDescriptorRegistryId( String pageDescriptorRegistryId ) { services.put( PageDescriptorRegistry.class, pageDescriptorRegistryId ); } /** * Get the implementation of a service by using the decapitalized shortname of the serviceType class name. * * @param serviceType * the service class to lookup the bean definition * @return the found service implementation if a bean definition can be found and it implements the required service * type, otherwise null * @see ClassUtils#getShortNameAsProperty(Class) */ protected Object getServiceForClassType(Class serviceType) { String lookupName = ClassUtils.getShortNameAsProperty(serviceType); ApplicationContext ctx = getApplicationContext(); if (ctx.containsBean(lookupName)) { Object bean = ctx.getBean(lookupName); if (serviceType.isAssignableFrom(bean.getClass())) { if(logger.isDebugEnabled()) { logger.debug("Using bean '" + lookupName + "' (" + bean.getClass().getName() + ") for service " + serviceType.getName()); } return bean; } else if(logger.isDebugEnabled()){ logger.debug("Bean with id '" + lookupName + "' (" + bean.getClass().getName() + ") does not implement " + serviceType.getName()); } } else if(logger.isDebugEnabled()){ logger.debug("No Bean with id '" + lookupName + "' found for service " + serviceType.getName()); } return null; } /** * Get the default implementation of a service according to the service type. If no * default implementation is available, then a null is returned. * * @param serviceType Type of service requested * @return Default service implementation, or null if none defined */ protected Object getDefaultImplementation( Class serviceType ) { Object impl = null; ImplBuilder builder = (ImplBuilder) serviceImplBuilders.get( serviceType ); if( builder != null ) { impl = builder.build( this ); } return impl; } /** * Tests if the application context contains a bean definition by using the decapitalized shortname of the serviceType class name * @param serviceType the service class to lookup the bean definition * @return true if a bean definition is found in the current application context, otherwise false * * @see ClassUtils#getShortNameAsProperty(Class) */ protected boolean containsServiceForClassType(Class serviceType) { return getApplicationContext().containsBean(ClassUtils.getShortNameAsProperty(serviceType)); } /** * Tests if a default implementation for the requested service type is available * * @param serviceType the requested service type * @return true if a default implementation is available otherwise false. */ protected boolean containsDefaultImplementation( Class serviceType ) { return serviceImplBuilders.containsKey( serviceType ); } /** * Internal interface used to provide default implementation builders. */ protected interface ImplBuilder { /** * Build the service implementation. * * @param applicationServices reference to service locator * @return service implementation */ Object build( DefaultApplicationServices applicationServices ); } protected static final ImplBuilder applicationContextImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { return applicationServices.getApplicationContext(); } }; protected static final ImplBuilder menuFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: MenuFactory" ); return new DefaultMenuFactory(); } }; protected static final ImplBuilder buttonFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ButtonFactory" ); return new DefaultButtonFactory(); } }; protected static final ImplBuilder commandServicesImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: CommandServices" ); return new DefaultCommandServices(); } }; protected static final ImplBuilder componentFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ComponentFactory" ); return new DefaultComponentFactory(); } }; protected static final ImplBuilder formComponentInterceptorFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: FormComponentInterceptorFactory" ); return new FormComponentInterceptorFactory() { public FormComponentInterceptor getInterceptor( FormModel formModel ) { return null; } }; } }; protected static final ImplBuilder applicationObjectConfigurerImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { // First see if there is an AOC in the context, if not construct a default Object impl = null; String aocBeanId = applicationServices.applicationObjectConfigurerBeanId; if( aocBeanId != null ) { try { impl = applicationServices.getApplicationContext().getBean( aocBeanId, ApplicationObjectConfigurer.class ); } catch( NoSuchBeanDefinitionException e ) { logger.info( "No object configurer found in context under name '" + aocBeanId + "'; configuring defaults." ); impl = new DefaultApplicationObjectConfigurer((MessageSource)applicationServices.getService(MessageSource.class)); } } else { logger.info( "No object configurer bean Id has been set; configuring defaults." ); impl = new DefaultApplicationObjectConfigurer((MessageSource)applicationServices.getService(MessageSource.class)); } return impl; } }; protected static final ImplBuilder commandConfigurerImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: CommandConfigurer" ); return new DefaultCommandConfigurer(); } }; protected static final ImplBuilder imageSourceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ImageSource" ); try { ResourceMapFactoryBean imageResourcesFactory = new ResourceMapFactoryBean(); imageResourcesFactory.setLocation(new ClassPathResource("org/springframework/richclient/image/images.properties")); imageResourcesFactory.afterPropertiesSet(); return new DefaultImageSource((Map)imageResourcesFactory.getObject()); } catch (IOException e) { return new DefaultImageSource(new HashMap()); } } }; protected static final ImplBuilder iconSourceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: IconSource" ); return new DefaultIconSource(); } }; protected static final ImplBuilder rulesSourceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: RulesSource" ); return new DefaultRulesSource(); } }; protected static final ImplBuilder conversionServiceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ConversionService" ); return new DefaultConversionServiceFactoryBean().getConversionService(); } }; protected static final ImplBuilder binderSelectionStrategyImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: BinderSelectionStrategy" ); return new SwingBinderSelectionStrategy(); } }; protected static final ImplBuilder FieldFaceSourceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: FieldFaceSource" ); return new MessageSourceFieldFaceSource(); } }; protected static final ImplBuilder bindingFactoryProviderImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: BindingFactoryProvider" ); return new SwingBindingFactoryProvider(); } }; protected static final ImplBuilder valueChangeDetectorImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ValueChangeDetector" ); return new DefaultValueChangeDetector(); } }; protected static final ImplBuilder applicationSecurityManagerImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ApplicationSecurityManager" ); return new DefaultApplicationSecurityManager( true ); } }; protected static final ImplBuilder SecurityControllerManagerImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: SecurityControllerManager" ); return new DefaultSecurityControllerManager(); } }; protected static final ImplBuilder viewDescriptorRegistryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ViewDescriptorRegistry" ); BeanFactoryViewDescriptorRegistry impl = new BeanFactoryViewDescriptorRegistry(); impl.setApplicationContext( applicationServices.getApplicationContext() ); return impl; } }; protected static final ImplBuilder pageDescriptorRegistryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: PageDescriptorRegistry" ); BeanFactoryPageDescriptorRegistry impl = new BeanFactoryPageDescriptorRegistry(); impl.setApplicationContext( applicationServices.getApplicationContext() ); return impl; } }; protected static final ImplBuilder messageTranslatorFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: MessageTranslatorFactory" ); DefaultMessageTranslatorFactory impl = new DefaultMessageTranslatorFactory(); impl.setMessageSource( applicationServices.getApplicationContext() ); return impl; } }; protected static final ImplBuilder labeledEnumResolverImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: LabeledEnumResolver" ); return new StaticLabeledEnumResolver(); } }; protected static final ImplBuilder messageSourceImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { // The application context is our properly configured message source logger.info( "Using MessageSource from application context" ); ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("org.springframework.richclient.application.messages"); return messageSource; } }; protected static final ImplBuilder messageSourceAccessorImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { // Just construct one on top of the current message source return new MessageSourceAccessor( (MessageSource) applicationServices.getService( MessageSource.class ) ); } }; protected static final ImplBuilder applicationWindowFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ApplicationWindowFactory" ); return new DefaultApplicationWindowFactory(); } }; protected static final ImplBuilder applicationPageFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: ApplicationPageFactory" ); return new DefaultApplicationPageFactory(); } }; protected static final ImplBuilder pageComponentPaneFactoryImplBuilder = new ImplBuilder() { public Object build( DefaultApplicationServices applicationServices ) { logger.info( "Creating default service impl: PageComponentPaneFactory" ); return new DefaultPageComponentPaneFactory(); } }; /** * Static initializer to construct the implementation builder map. */ static { // Default service implementation builders serviceImplBuilders.put( ApplicationContext.class, applicationContextImplBuilder ); serviceImplBuilders.put( ApplicationObjectConfigurer.class, applicationObjectConfigurerImplBuilder ); serviceImplBuilders.put( ApplicationSecurityManager.class, applicationSecurityManagerImplBuilder ); serviceImplBuilders.put( ApplicationPageFactory.class, applicationPageFactoryImplBuilder ); serviceImplBuilders.put( ApplicationWindowFactory.class, applicationWindowFactoryImplBuilder ); serviceImplBuilders.put( PageComponentPaneFactory.class, pageComponentPaneFactoryImplBuilder ); serviceImplBuilders.put( BinderSelectionStrategy.class, binderSelectionStrategyImplBuilder ); serviceImplBuilders.put( BindingFactoryProvider.class, bindingFactoryProviderImplBuilder ); serviceImplBuilders.put( ButtonFactory.class, buttonFactoryImplBuilder ); serviceImplBuilders.put( MenuFactory.class, menuFactoryImplBuilder ); serviceImplBuilders.put( CommandServices.class, commandServicesImplBuilder ); serviceImplBuilders.put( CommandConfigurer.class, commandConfigurerImplBuilder ); serviceImplBuilders.put( ComponentFactory.class, componentFactoryImplBuilder ); serviceImplBuilders.put( ConversionService.class, conversionServiceImplBuilder ); serviceImplBuilders.put( FormComponentInterceptorFactory.class, formComponentInterceptorFactoryImplBuilder ); serviceImplBuilders.put( FieldFaceSource.class, FieldFaceSourceImplBuilder ); serviceImplBuilders.put( IconSource.class, iconSourceImplBuilder ); serviceImplBuilders.put( ImageSource.class, imageSourceImplBuilder ); serviceImplBuilders.put( LabeledEnumResolver.class, labeledEnumResolverImplBuilder ); serviceImplBuilders.put( MessageSource.class, messageSourceImplBuilder ); serviceImplBuilders.put( MessageSourceAccessor.class, messageSourceAccessorImplBuilder ); serviceImplBuilders.put( RulesSource.class, rulesSourceImplBuilder ); serviceImplBuilders.put( SecurityControllerManager.class, SecurityControllerManagerImplBuilder ); serviceImplBuilders.put( ValueChangeDetector.class, valueChangeDetectorImplBuilder ); serviceImplBuilders.put( ViewDescriptorRegistry.class, viewDescriptorRegistryImplBuilder ); serviceImplBuilders.put( PageDescriptorRegistry.class, pageDescriptorRegistryImplBuilder ); serviceImplBuilders.put( MessageTranslatorFactory.class, messageTranslatorFactoryImplBuilder ); } }
{ "content_hash": "cb255fd977c6532d37566b56f0754389", "timestamp": "", "source": "github", "line_count": 1044, "max_line_length": 160, "avg_line_length": 42.07854406130268, "alnum_prop": 0.7095606646938311, "repo_name": "springrichclient/springrcp", "id": "52bb451b08bdbf30a1b674f721d76075842bc21f", "size": "44545", "binary": false, "copies": "3", "ref": "refs/heads/master", "path": "spring-richclient-core/src/main/java/org/springframework/richclient/application/support/DefaultApplicationServices.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Haskell", "bytes": "1484" }, { "name": "Java", "bytes": "4963844" }, { "name": "JavaScript", "bytes": "22973" }, { "name": "Shell", "bytes": "2550" } ], "symlink_target": "" }
package org.apache.shiro.authz.permission; import org.apache.shiro.authz.Permission; /** * <tt>PermissionResolver</tt> implementation that returns a new {@link WildcardPermission WildcardPermission} * based on the input string. * * @since 0.9 */ public class WildcardPermissionResolver implements PermissionResolver { boolean caseSensitive; /** * Constructor to specify case sensitivity for the resolved permissions. * @param caseSensitive true if permissions should be case sensitive. */ public WildcardPermissionResolver(boolean caseSensitive) { this.caseSensitive=caseSensitive; } /** * Default constructor. * Equivalent to calling WildcardPermissionResolver(false) * * @see WildcardPermissionResolver#WildcardPermissionResolver(boolean) */ public WildcardPermissionResolver() { this(WildcardPermission.DEFAULT_CASE_SENSITIVE); } /** * Set the case sensitivity of the resolved Wildcard permissions. * @param state the caseSensitive flag state for resolved permissions. */ public void setCaseSensitive(boolean state) { this.caseSensitive = state; } /** * Return true if this resolver produces case sensitive permissions. * @return true if this resolver produces case sensitive permissions. */ public boolean isCaseSensitive() { return caseSensitive; } /** * Returns a new {@link WildcardPermission WildcardPermission} instance constructed based on the specified * <tt>permissionString</tt>. * * @param permissionString the permission string to convert to a {@link Permission Permission} instance. * @return a new {@link WildcardPermission WildcardPermission} instance constructed based on the specified * <tt>permissionString</tt> */ public Permission resolvePermission(String permissionString) { return new WildcardPermission(permissionString, caseSensitive); } }
{ "content_hash": "8ac4a657baa84fcd7d077fda96fd0b1e", "timestamp": "", "source": "github", "line_count": 60, "max_line_length": 110, "avg_line_length": 33.45, "alnum_prop": 0.7065271549576483, "repo_name": "apache/shiro", "id": "0adffada7c5f190c11514d52b0a45877fc024bdd", "size": "2816", "binary": false, "copies": "3", "ref": "refs/heads/main", "path": "core/src/main/java/org/apache/shiro/authz/permission/WildcardPermissionResolver.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "2608" }, { "name": "Groovy", "bytes": "362841" }, { "name": "Java", "bytes": "3130466" }, { "name": "Shell", "bytes": "2479" } ], "symlink_target": "" }
template <typename M, typename Ms> constexpr bool testConstexpr() { M m1{1}; if (static_cast<unsigned>(m1 += Ms{ 1}) != 2) return false; if (static_cast<unsigned>(m1 += Ms{ 2}) != 4) return false; if (static_cast<unsigned>(m1 += Ms{ 8}) != 12) return false; if (static_cast<unsigned>(m1 -= Ms{ 1}) != 11) return false; if (static_cast<unsigned>(m1 -= Ms{ 2}) != 9) return false; if (static_cast<unsigned>(m1 -= Ms{ 8}) != 1) return false; return true; } int main(int, char**) { using month = std::chrono::month; using months = std::chrono::months; ASSERT_NOEXCEPT(std::declval<month&>() += std::declval<months&>()); ASSERT_NOEXCEPT(std::declval<month&>() -= std::declval<months&>()); ASSERT_SAME_TYPE(month&, decltype(std::declval<month&>() += std::declval<months&>())); ASSERT_SAME_TYPE(month&, decltype(std::declval<month&>() -= std::declval<months&>())); static_assert(testConstexpr<month, months>(), ""); for (unsigned i = 1; i <= 10; ++i) { month month(i); int exp = i + 10; while (exp > 12) exp -= 12; assert(static_cast<unsigned>(month += months{10}) == static_cast<unsigned>(exp)); assert(static_cast<unsigned>(month) == static_cast<unsigned>(exp)); } for (unsigned i = 1; i <= 10; ++i) { month month(i); int exp = i - 9; while (exp < 1) exp += 12; assert(static_cast<unsigned>(month -= months{ 9}) == static_cast<unsigned>(exp)); assert(static_cast<unsigned>(month) == static_cast<unsigned>(exp)); } return 0; }
{ "content_hash": "75fbf12b0583e81616a7005636941fb7", "timestamp": "", "source": "github", "line_count": 47, "max_line_length": 90, "avg_line_length": 35.1063829787234, "alnum_prop": 0.5581818181818182, "repo_name": "llvm-mirror/libcxx", "id": "a792072afa26dba73c641b95499d20189040fa99", "size": "2301", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "test/std/utilities/time/time.cal/time.cal.month/time.cal.month.members/plus_minus_equal.pass.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "2035" }, { "name": "C", "bytes": "19789" }, { "name": "C++", "bytes": "25847968" }, { "name": "CMake", "bytes": "147482" }, { "name": "CSS", "bytes": "1237" }, { "name": "HTML", "bytes": "228687" }, { "name": "Objective-C++", "bytes": "2263" }, { "name": "Python", "bytes": "279305" }, { "name": "Shell", "bytes": "21350" } ], "symlink_target": "" }
title: Post an expense report workflow action layout: reference --- ## Description Posts a workflow action for the supplied expense report. The workflow action moves the expense report through the workflow process. ### Workflow actions The available actions are: * **Approve**: The report successfully completes the current workflow step. The report will continue in the workflow, and may require additional approvals based on configuration. If the report was in the Processing Payment status, it will be moved to the Paid status. **NOTES**: 1. Reports can't be moved from Processing Payment to Paid until all of their expense entries have been extracted or manually paid. Wait until the extract process completes for the report, then send the Approve workflow action. 2. This API is not supported for the Processor role or expense reports pending the Processor workflow step. * **Send Back to Employee**: The report is sent back to the employee for revision. When the user resubmits the report, it travels through the entire workflow again. * **Recall to Employee**: This workflow action is initiated by the employee, and is only available after the report has been submitted. This workflow action may not be available to some clients due to configuration. **WARNING:** Prior to calling this endpoint the Caller _must_ check the Approval Status found in the **ApprovalStatusName** element in the response for [Get Report Details][1] to ensure the report is at the workflow step the Caller expects.  Under no circumstance should a Caller make a call to this endpoint without being certain the report is at the workflow step the Caller expects. ### Workflow roles Each workflow step in a workflow is associated with a workflow role. Professional clients can configure workflow steps and roles in the Workflows area of Expense Admin. The OAuth consumer is evaluated to determine which role(s) the consumer has in Concur. There are two different types of workflow roles as described in the following sections. #### System role The System role is used when the workflow actions can be completed programatically. Any workflow action can be completed this way, depending on the client's business process. The workflow role can be configured while adding the report workflow step. Some steps may require the System role. When using this role, the OAuth consumer must have the following user role: * Standard/Developer Sandbox: Can Administer * Professional: Company Admin or Web Services Administrator The expense report owner must have an approver or processor assigned to them before the System role can make changes to their reports. #### Approver role The Approver role is used when the workflow action should be completed by a particular user. Developers who want to present a list of reports to approve and send the workflow action when the reports have been evaluated by the approver use the Approver role. This role requires that a user with the correct Concur role (Expense Approver, Authorized Approver, Cost Object Approver, or Expense Processor for Professional, or the Can Administer or Can Approve Reports roles for Standard) authenticates using Standard OAuth before supplying the workflow action. The user must also have access (be a valid approver or processor) for the supplied report ID. ## Request ### Request parameters #### Path parameters | Parameter |Required/Optional| Description | |-----------------|--------|-----------------------------| |{_workflowstepID_}/workflowaction | required | The identifier for the desired workflow step and the **workflowaction** keyword.| Example: `https://www.concursolutions.com/api/expense/expensereport/v1.1/report/{workflowstepId}/workflowaction` **URI Source:** The URI is returned in the WorkflowActionURL element of the [Get Report Details][1] response. ### Headers #### Authorization header Authorization header with OAuth token for valid Concur user. Required. ### Content-Type header application/xml ### Request body #### Root elements This request should contain a **WorkflowAction** parent element with the following child elements. #### WorkflowAction child elements | Element | Required/optional | Description | |----------|--------------------|--------------| | Action | required | The name of the workflow action. Possible values are: **Approve**, **Send Back to Employee**, or **Recall to Employee**. Must be one of the workflow actions available for the workflow step. Consult Expense Admin > Workflow to learn details. | | Comment | required, for Send Back to Employee | Must be used with the **Send Back to Employee** workflow action. This comment is visible wherever report comments are available to the employee, approver, authorization request administrator, and/or processor. Max length: 2000 | ### Response #### Response body This request will return an **ActionStatus** parent element with the following child elements. #### ActionStatus elements | Element | Description | |----------|-------------| | Message | The error message. Only appears if a workflow action error was generated. | | Status | The status of the report workflow action. | ## Examples ### XML example request ```http POST https://www.concursolutions.com/api/expense/expensereport/v1.1/report/nx2WRNzp18$wjehk%wqEL6EDHRwi9r$paQS1UqyL6a454QitqQ/workflowaction HTTP/1.1 Authorization: OAuth {access token} ... <WorkflowAction xmlns="http://www.concursolutions.com/api/expense/expensereport/2011/03"> <Action>Approve</Action> <Comment>Approved via Concur Connect</Comment> </WorkflowAction> ``` ### XML example of successful response ```xml <?xml version="1.0" encoding="utf-8"?> <ActionStatus xmlns="http://www.concursolutions.com/api/expense/expensereport/2011/03" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Message>SUCCESS!</Message> <Status>SUCCESS!</Status> </ActionStatus> ``` ### XML example of response With error ```xml <?xml version="1.0" encoding="utf-8"?> <ActionStatus xmlns="http://www.concursolutions.com/api/expense/expensereport/2011/03" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"> <Message>The action cannot be executed because the item has recently been changed. Please refresh your list and try again.</Message> <Status>FAILURE</Status> </ActionStatus> ``` [1]: /api-reference/expense/expense-report/reports.html#getID [2]: https://developer.concur.com/reference/http-codes
{ "content_hash": "2d77382dd15a11166d5d63799b1b6ae8", "timestamp": "", "source": "github", "line_count": 123, "max_line_length": 650, "avg_line_length": 52.40650406504065, "alnum_prop": 0.7595408004964319, "repo_name": "bhague1281/developer.concur.com", "id": "74afa92043836a675ea98372a1070fe0bee616a6", "size": "6451", "binary": false, "copies": "2", "ref": "refs/heads/preview", "path": "src/api-reference/expense/expense-report/post-report-workflow-action.markdown", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "150887" }, { "name": "HTML", "bytes": "282158" }, { "name": "JavaScript", "bytes": "2478409" }, { "name": "PHP", "bytes": "16968" }, { "name": "Ruby", "bytes": "20671" }, { "name": "Shell", "bytes": "11663" }, { "name": "XSLT", "bytes": "366862" } ], "symlink_target": "" }
from utils.codegen import format_type, get_detailed_extern_callinfos from utils.extern import extern_has_tuple_params from compiler_common import generate_var_name from more_itertools import unique_everseen #[ #include "dpdk_lib.h" #[ #include "util_debug.h" detailed_callinfos = get_detailed_extern_callinfos(hlir) def get_externtype(part, partypeinfolen, partype_suffix, varname): return f'EXTERNTYPE{partypeinfolen}({part}{partype_suffix})* {varname}' for partypeinfolen, mname_parts, partype_suffix, params, params_as_buf, ret, mname_postfix, mname_postfix_as_buf, args, args_as_buf, refvars, arginfos, parinfos in sorted(unique_everseen(detailed_callinfos, key=lambda c: c[0:3])): if len(mname_parts) == 1: call = f'SHORT_EXTERNCALL{partypeinfolen + len(mname_parts)-1}' else: call = f'EXTERNCALL{partypeinfolen + len(mname_parts)-2}' varname = generate_var_name('extern') externtype = get_externtype(mname_parts[0], partypeinfolen, partype_suffix, varname) params = f'{externtype}, {params}' args_as_buf = f'{varname}, ' + args_as_buf return_stmt = '' if ret != 'void' else 'return ' #[ $ret $call(${",".join(mname_parts)}${partype_suffix})($params); #[ for partypeinfolen, mname_parts, partype_suffix, params, params_as_buf, ret, mname_postfix, mname_postfix_as_buf, args, args_as_buf, refvars, arginfos, parinfos in sorted(unique_everseen(detailed_callinfos, key=lambda c: (c[0:2], c[4]))): if len(mname_parts) == 1: call = f'SHORT_EXTERNCALL{partypeinfolen + len(mname_parts)-1}' else: call = f'EXTERNCALL{partypeinfolen + len(mname_parts)-2}' varname = generate_var_name('extern') externtype = get_externtype(mname_parts[0], partypeinfolen, partype_suffix, varname) params_as_buf = f'{externtype}, {params_as_buf}' args_as_buf = f'{varname}, ' + args_as_buf #[ $ret EXTERNIMPL${partypeinfolen + len(mname_parts)-1}(${",".join(mname_parts)}${mname_postfix_as_buf})(${params_as_buf}); #[
{ "content_hash": "2318f1b7de6278a913a1b7829b0aefcc", "timestamp": "", "source": "github", "line_count": 43, "max_line_length": 238, "avg_line_length": 47.325581395348834, "alnum_prop": 0.6845208845208846, "repo_name": "P4ELTE/t4p4s", "id": "6e0c6aeb50bf5d1bedef1213804d82d4cde5ddae", "size": "2135", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/hardware_indep/dpdkx_gen_extern.h.py", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C", "bytes": "462753" }, { "name": "Makefile", "bytes": "2617" }, { "name": "Python", "bytes": "313481" }, { "name": "Shell", "bytes": "86070" } ], "symlink_target": "" }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var schema = [{ enum: ['always', 'never'], type: 'string' }]; var create = function create(context) { var always = (context.options[0] || 'always') === 'always'; if (always) { var sourceCode = context.getSourceCode(); // nodes representing type and import declarations var ignoredNodes = [ // import ... function (node) { return node.type === 'ImportDeclaration'; }, // export type Foo = ... // export opaque type Foo = ... // export type Foo from ... // export opaque type Foo from ... function (node) { return node.type === 'ExportNamedDeclaration' && node.exportKind === 'type'; }, // type Foo = ... function (node) { return node.type === 'TypeAlias'; }, // opaque type Foo = ... function (node) { return node.type === 'OpaqueType'; }]; var isIgnoredNode = function isIgnoredNode(node) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = ignoredNodes[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var predicate = _step.value; if (predicate(node)) { return true; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } return false; }; var regularCodeStartRange = void 0; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = sourceCode.ast.body[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var node = _step2.value; if (!isIgnoredNode(node)) { regularCodeStartRange = node.range; break; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } if (!_lodash2.default.isArray(regularCodeStartRange)) { // a source with only ignored nodes return {}; } return { 'TypeAlias, OpaqueType'(node) { if (node.range[0] > regularCodeStartRange[0]) { context.report({ message: 'All type declaration should be at the top of the file, after any import declarations.', node }); } } }; } else { return {}; } }; exports.default = { create, schema }; module.exports = exports.default;
{ "content_hash": "9457f66110b1e6c6b6eded7cbae573f3", "timestamp": "", "source": "github", "line_count": 134, "max_line_length": 179, "avg_line_length": 24.78358208955224, "alnum_prop": 0.5624811803673593, "repo_name": "BigBoss424/portfolio", "id": "acf204a9a6c934b60eafaecda5e6faa2d7ca998e", "size": "3321", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "v7/development/node_modules/eslint-plugin-flowtype/dist/rules/requireTypesAtTop.js", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
[![Latest Stable Version](https://poser.pugx.org/bigpaulie/yii2-social-share/v/stable)](https://packagist.org/packages/bigpaulie/yii2-social-share) [![Total Downloads](https://poser.pugx.org/bigpaulie/yii2-social-share/downloads)](https://packagist.org/packages/bigpaulie/yii2-social-share) [![Latest Unstable Version](https://poser.pugx.org/bigpaulie/yii2-social-share/v/unstable)](https://packagist.org/packages/bigpaulie/yii2-social-share) [![License](https://poser.pugx.org/bigpaulie/yii2-social-share/license)](https://packagist.org/packages/bigpaulie/yii2-social-share) Yii2 Social Link Sharer Built using <a href="http://lipis.github.io/bootstrap-social/" target="_blank">Bootstrap Social</a> and <a href="http://fontawesome.io/" target="_blank">Font Awesome</a> , two very cool projects ! Please keep in mind that this is a work in progress. ## Install The preferred way of installing is through composer ``` composer require --prefer-dist bigpaulie/yii2-social-share "dev-master" ``` OR add to composer.json ``` "bigpaulie/yii2-social-share": "dev-master" ``` ## Example usage : ```php use bigpaulie\social\share\Share; ``` By default you can run the widget with no configuration parameters ```php echo Share::widget(); ``` this will produce an unordered list "ul" tag like ```HTML <ul> <li><a>....</a></li> <li><a>....</a></li> <li><a>....</a></li> </ul> ``` #### Changing the layout of the widget ```php echo Share::widget([ 'type' => 'small', 'tag' => 'div', 'template' => '<div>{button}</div>', ]); ``` The output of this will be something similar to : ```HTML <div> <div><a> .... </a></div> <div><a> .... </a></div> <div><a> .... </a></div> </div> ``` #### The shared URL By default the widget set's the URL to the current route, you can change that as needed by using the "url" property. ```php echo Share::widget([ 'url' => 'http://www.domain.com', ]); ``` Or ```php echo Share::widget([ 'url' => Url::to(['site/index'] , TRUE), ]); ``` Don't forget to require the helper library Url and to use the second parameter of the method for the full URL to the page. ```php use yii\helpers\Url; ``` #### The shared data By default the widget pass to social network only URL. Some networks, for example Pinterest, allow pass title, description and image. You can change that as needed by using the "title", "description" or "image" properties. ```php echo Share::widget([ 'title' => 'Some title', 'description' => 'Some description', 'image' => '/path-to-some-image.jpg', ]); ``` #### Attributes of main container You can add or change attributes of the main container using the htmlOptions property. By default the main container has an id attribute similar to #w0, you can change that if you want. ```php echo Share::widget([ 'htmlOptions' => [ 'id' => 'new-id', 'class' => 'my-class', ], ]); ``` #### Widget button types The widget provides three types of buttons extra-small (small icons only) small (icon only) large (icon + text) ```php echo Share::widget([ 'type' => Share::TYPE_EXTRA_SMALL ``` ```php echo Share::widget([ 'type' => Share::TYPE_SMALL ]); ``` ```php echo Share::widget([ 'type' => Share::TYPE_LARGE ]); ``` The default text for the large buttons is "Share on NETWORK", where NETWORK is the name of the social network ex : Facebook. You can change the default text by using the "text" property of the widget. ```php echo Share::widget([ 'text' => 'Click to share on {network}', ]); ``` #### Networks Currently the widget provides 6 buttons Facebook Google Plus Twitter Pinterest Linkedin Vk odnoklassniki #### Including only some networks For some reason you may need to include only some networks. In order to do that you can use the "include" property of the widget ```php echo Share::widget([ 'include' => ['network1', 'network2'] ]); ``` Presented social networks will be shown in that order in which you put them. #### Excluding some networks For some reason you may need to exclude one or more networks. In order to do that you can use the "exclude" property of the widget ```php echo Share::widget([ 'exclude' => ['network1', 'network2'] ]); ``` #### Add utm marks For enterprise apps you mostly need to add UTM mark for analytics. ```php // add by default echo Share::widget([ 'addUtm' => true, ]); // little customization echo Share::widget([ 'addUtm' => true, // necessary flag 'utmMedium' => 'social_share', 'utmCampaign' => 'viral_retention', ]); ``` ### Contributions Contributions are most welcomed, just fork modify and submit a pull request.
{ "content_hash": "624e1ce26be517420b7a3cc6e88e3814", "timestamp": "", "source": "github", "line_count": 184, "max_line_length": 575, "avg_line_length": 26.972826086956523, "alnum_prop": 0.6304654442877292, "repo_name": "bigpaulie/yii2-social-share", "id": "59dd191884f00068b3c86f8e1d827fc489909895", "size": "4983", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "README.md", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "118" }, { "name": "PHP", "bytes": "8160" } ], "symlink_target": "" }
module DescriptionsHelper end
{ "content_hash": "2449b7ac37dd03dc20156c07df98fc0c", "timestamp": "", "source": "github", "line_count": 2, "max_line_length": 25, "avg_line_length": 15, "alnum_prop": 0.9, "repo_name": "jpascal/hummer-server", "id": "2666331b377b98578ab2579b5ca10f03beb25b02", "size": "30", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "app/helpers/descriptions_helper.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "10508" }, { "name": "CoffeeScript", "bytes": "2640" }, { "name": "JavaScript", "bytes": "1262" }, { "name": "Ruby", "bytes": "68946" } ], "symlink_target": "" }
layout: default title: Page 1 description: This is my site. Welcome. --- <h1 class="mtl">Markup: HTML Tags and Formatting</h1> <p>This page shows how all the html tags render on this thing. Taken from <a href="http://codex.wordpress.org/Theme_Unit_Test">WordPress Theme Unit Test</a></p> <h2>Headings</h2> <h1>Header one</h1> <h2>Header two</h2> <h3>Header three</h3> <h4>Header four</h4> <h5>Header five</h5> <h6>Header six</h6> <h2>Blockquotes</h2> Single line blockquote: <blockquote>Stay hungry. Stay foolish.</blockquote> Multi-line blockquote with a cite reference: <blockquote>People think focus means saying yes to the thing you've got to focus on. But that's not what it means at all. It means saying no to the hundred other good ideas that there are. You have to pick carefully. I'm actually as proud of the things we haven't done as the things I have done. Innovation is saying no to 1,000 things. <cite>Steve Jobs - Apple Worldwide Developers' Conference, 1997</cite></blockquote> <h2>Tables</h2> <table> <tbody> <tr> <th>Employee</th> <th class="views">Salary</th> <th></th> </tr> <tr class="odd"> <td><a href="http://example.org/">John Doe</a></td> <td>$1</td> <td>Because that's all Steve Job' needed for a salary.</td> </tr> <tr class="even"> <td><a href="http://example.org/">Jane Doe</a></td> <td>$100K</td> <td>For all the blogging he does.</td> </tr> <tr class="odd"> <td><a href="http://example.org/">Fred Bloggs</a></td> <td>$100M</td> <td>Pictures are worth a thousand words, right? So Tom x 1,000.</td> </tr> <tr class="even"> <td><a href="http://example.org/">Jane Bloggs</a></td> <td>$100B</td> <td>With hair like that?! Enough said...</td> </tr> </tbody> </table> <h2>Definition Lists</h2> <dl><dt>Definition List Title</dt><dd>Definition list division.</dd><dt>Startup</dt><dd>A startup company or startup is a company or temporary organization designed to search for a repeatable and scalable business model.</dd><dt>#dowork</dt><dd>Coined by Rob Dyrdek and his personal body guard Christopher "Big Black" Boykins, "Do Work" works as a self motivator, to motivating your friends.</dd><dt>Do It Live</dt><dd>I'll let Bill O'Reilly <a title="We'll Do It Live" href="https://www.youtube.com/watch?v=O_HyZ5aW76c">explain</a> this one.</dd></dl> <h2>Unordered Lists (Nested)</h2> <ul> <li>List item one <ul> <li>List item one <ul> <li>List item one</li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ul> </li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ul> </li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ul> <h2>Ordered List (Nested)</h2> <ol> <li>List item one <ol> <li>List item one <ol> <li>List item one</li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ol> </li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ol> </li> <li>List item two</li> <li>List item three</li> <li>List item four</li> </ol> <h2>HTML Tags</h2> <p> These supported tags come from the WordPress.com code <a title="Code" href="http://en.support.wordpress.com/code/">FAQ</a>. </p> <p> <strong>Address Tag</strong><br/></p> <address>1 Infinite Loop Cupertino, CA 95014 United States</address> <p> <strong>Anchor Tag (aka. Link)</strong><br/> This is an example of a <a title="Apple" href="http://apple.com">link</a>.<br/> <strong>Abbreviation Tag</strong><br/> The abbreviation <abbr title="Seriously">srsly</abbr> stands for "seriously".<br/> <strong>Acronym Tag (<em>deprecated in HTML5</em>)</strong><br/> The acronym <acronym title="For The Win">ftw</acronym> stands for "for the win".<br/> <strong>Big Tag <strong>(<em>deprecated in HTML5</em>)</strong></strong><br/> These tests are a <big>big</big> deal, but this tag is no longer supported in HTML5.<br/> <strong>Cite Tag</strong><br/> "Code is poetry." --<cite>Automattic</cite><br/> <strong>Code Tag</strong><br/> You will learn later on in these tests that <code>word-wrap: break-word;</code> will be your best friend.<br/> <strong>Delete Tag</strong><br/> This tag will let you <del>strikeout text</del>, but this tag is no longer supported in HTML5 (use the <code>&lt;strike&gt;</code> instead).<br/> <strong>Emphasize Tag</strong><br/> The emphasize tag should <em>italicize</em> text.<br/> <strong>Insert Tag</strong><br/> This tag should denote <ins>inserted</ins> text.<br/> <strong>Keyboard Tag</strong><br/> This scarsly known tag emulates <kbd>keyboard text</kbd>, which is usually styled like the <code>&lt;code&gt;</code> tag.<br/> <strong>Preformatted Tag</strong><br/> This tag styles large blocks of code.</p> <pre>.post-title { margin: 0 0 5px; font-weight: bold; font-size: 38px; line-height: 1.2; and here's a line of some really, really, really, really long text, just to see how the PRE tag handles it and to find out how it overflows; }</pre> <p> <strong>Quote Tag</strong><br/> <q>Developers, developers, developers...</q> --Steve Ballmer<br/> <strong>Strike Tag <strong>(<em>deprecated in HTML5</em>)</strong></strong><br/> This tag shows <span style="text-decoration:line-through;">strike-through text</span><br/> <strong>Strong Tag</strong><br/> This tag shows <strong>bold<strong> text.</strong></strong><br/> <strong>Subscript Tag</strong><br/> Getting our science styling on with H<sub>2</sub>O, which should push the "2" down.<br/> <strong>Superscript Tag</strong><br/> Still sticking with science and Isaac Newton's E = MC<sup>2</sup>, which should lift the 2 up.<br/> <strong>Teletype Tag <strong>(<em>deprecated in HTML5</em>)</strong></strong><br/> This rarely used tag emulates <tt>teletype text</tt>, which is usually styled like the <code>&lt;code&gt;</code> tag.<br/> <strong>Variable Tag</strong><br/> This allows you to denote <var>variables</var>. </p> <h1 class="mtl">Forms and form validation using Abide</h1> <form data-abide novalidate> <div data-abide-error class="alert callout" style="display: none;"> <p><i class="fi-alert"></i> There are some errors in your form.</p> </div> <div class="grid-x grid-padding-x"> <div class="small-12 cell"> <label>Number Required <input type="text" placeholder="1234" aria-describedby="exampleHelpText" required pattern="number"> <span class="form-error"> Yo, you had better fill this out, it's required. </span> </label> <p class="help-text" id="exampleHelpText">Here's how you use this input field!</p> </div> <div class="small-12 cell"> <label>Nothing Required! <input type="text" placeholder="Use me, or don't" aria-describedby="exampleHelpTex" data-abide-ignore> </label> <p class="help-text" id="exampleHelpTex">This input is ignored by Abide using `data-abide-ignore`</p> </div> <div class="small-12 cell"> <label>Password Required <input type="password" id="password" placeholder="yeti4preZ" aria-describedby="exampleHelpText" required > <span class="form-error"> I'm required! </span> </label> <p class="help-text" id="exampleHelpText">Enter a password please.</p> </div> <div class="small-12 cell"> <label>Re-enter Password <input type="password" placeholder="yeti4preZ" aria-describedby="exampleHelpText2" required pattern="alpha_numeric" data-equalto="password"> <span class="form-error"> Hey, passwords are supposed to match! </span> </label> <p class="help-text" id="exampleHelpText2">This field is using the `data-equalto="password"` attribute, causing it to match the password field above.</p> </div> </div> <div class="grid-x grid-padding-x"> <div class="medium-6 cell"> <label>URL Pattern, not required, but throws error if it doesn't match the Regular Expression for a valid URL. <input type="text" placeholder="http://foundation.zurb.com" pattern="url"> </label> </div> <div class="medium-6 cell"> <label>European Cars, Choose One, it can't be the blank option. <select id="select" required> <option value=""></option> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="mercedes">Mercedes</option> <option value="audi">Audi</option> </select> </label> </div> </div> <div class="grid-x grid-padding-x"> <fieldset class="large-6 cell"> <legend>Choose Your Favorite, and this is required, so you have to pick one.</legend> <input type="radio" name="pokemon" value="Red" id="pokemonRed"><label for="pokemonRed">Red</label> <input type="radio" name="pokemon" value="Blue" id="pokemonBlue" required><label for="pokemonBlue">Blue</label> <input type="radio" name="pokemon" value="Yellow" id="pokemonYellow"><label for="pokemonYellow">Yellow</label> </fieldset> <fieldset class="large-6 cell"> <legend>Choose Your Favorite - not required, you can leave this one blank.</legend> <input type="radio" name="pockets" value="Red" id="pocketsRed"><label for="pocketsRed">Red</label> <input type="radio" name="pockets" value="Blue" id="pocketsBlue"><label for="pocketsBlue">Blue</label> <input type="radio" name="pockets" value="Yellow" id="pocketsYellow"><label for="pocketsYellow">Yellow</label> </fieldset> <fieldset class="large-6 cell"> <legend>Check these out</legend> <input id="checkbox1" type="checkbox"><label for="checkbox1">Checkbox 1</label> <input id="checkbox2" type="checkbox" required><label for="checkbox2">Checkbox 2</label> <input id="checkbox3" type="checkbox"><label for="checkbox3">Checkbox 3</label> </fieldset> </div> <div class="grid-x grid-padding-x"> <fieldset class="large-6 cell"> <button class="button" type="submit" value="Submit">Submit</button> </fieldset> <fieldset class="large-6 cell"> <button class="button" type="reset" value="Reset">Reset</button> </fieldset> </div> </form>
{ "content_hash": "f9e8b0b25f1e4ac8dc182cbf2cf54b76", "timestamp": "", "source": "github", "line_count": 279, "max_line_length": 552, "avg_line_length": 36.17204301075269, "alnum_prop": 0.6726119698771305, "repo_name": "daigofuji/jekyll-foundation-6-starter", "id": "8054405f8ccab43dc8358ab700379cd9373c06c0", "size": "10099", "binary": false, "copies": "1", "ref": "refs/heads/gh-pages", "path": "page-html-unit-test.html", "mode": "33261", "license": "mit", "language": [ { "name": "CSS", "bytes": "26617" }, { "name": "HTML", "bytes": "39124" }, { "name": "JavaScript", "bytes": "714" }, { "name": "Ruby", "bytes": "48" } ], "symlink_target": "" }
int _glfwPlatformGetJoystickParam( int joy, int param ) { // TODO: Implement this. return 0; } //======================================================================== // Get joystick axis positions //======================================================================== int _glfwPlatformGetJoystickPos( int joy, float *pos, int numaxes ) { // TODO: Implement this. return 0; } //======================================================================== // Get joystick button states //======================================================================== int _glfwPlatformGetJoystickButtons( int joy, unsigned char *buttons, int numbuttons ) { // TODO: Implement this. return 0; }
{ "content_hash": "2ccd07d3c03b46c6326fb105a6a3f9ee", "timestamp": "", "source": "github", "line_count": 26, "max_line_length": 86, "avg_line_length": 27.615384615384617, "alnum_prop": 0.4011142061281337, "repo_name": "d909b/GADEL-Snake", "id": "bd3ea640128b10d6632a0219298583505b96ac31", "size": "2448", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "Angel/Libraries/glfw-2.7.3/lib/cocoa/cocoa_joystick.m", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Ada", "bytes": "89080" }, { "name": "Assembly", "bytes": "143356" }, { "name": "C", "bytes": "15770728" }, { "name": "C#", "bytes": "55726" }, { "name": "C++", "bytes": "7152957" }, { "name": "D", "bytes": "416653" }, { "name": "Delphi", "bytes": "68422" }, { "name": "JavaScript", "bytes": "40695" }, { "name": "Lua", "bytes": "542771" }, { "name": "OCaml", "bytes": "6380" }, { "name": "Objective-C", "bytes": "1650241" }, { "name": "Perl", "bytes": "269377" }, { "name": "Python", "bytes": "202527" }, { "name": "Racket", "bytes": "19627" }, { "name": "Ruby", "bytes": "234" }, { "name": "Scheme", "bytes": "9578" }, { "name": "Shell", "bytes": "5749964" } ], "symlink_target": "" }
html { font-size: 14px; } .h1, .h2, .h3, .h4, .h5, .h6, h1, h2, h3, h4, h5, h6 { font-weight: 700; margin: 0.75rem 0; } h4 { font-size: 1.25rem; } a, a:not([href]) { color: #0088cc; text-decoration: none; } a:hover, a:not([href]):hover { color: #005580; text-decoration:underline } .btn-spark { color:#333333; background-color:#ffffff; background-image:linear-gradient(to bottom, #ffffff, #e6e6e6); background-repeat:repeat-x; border: 1px solid #ced4da; border-bottom-color: #b3b3b3; box-shadow:inset 0 1px 0 rgba(255,255,255,.2), 0 1px 2px rgba(0,0,0,.05); } .btn-spark:hover { background-color: #e6e6e6; background-position:0 -15px; transition:background-position 0.1s linear; } .form-inline label { margin-left: 0.25rem; margin-right: 0.25rem; } .navbar { background-color: #fafafa; background-image: linear-gradient(to bottom, #ffffff, #f2f2f2); background-repeat: repeat-x; box-shadow: 0 1px 10px rgba(0,0,0,.1); border-bottom-color: #d4d4d4; border-bottom-style: solid; border-bottom-width: 1px; font-size: 15px; line-height: 1; margin-bottom: 15px; padding: 0 1rem; } .navbar .navbar-brand { padding: 0; } .navbar .navbar-nav .nav-link { height: 50px; padding: 10px 15px 10px; line-height: 2; } .navbar .navbar-nav .nav-item.active .nav-link { background-color: #e5e5e5; box-shadow: inset 0 3px 8px rgba(0, 0, 0, 0.125); color: #555555; } table.sortable thead { cursor: pointer; } table.sortable td { word-wrap: break-word; max-width: 600px; } .progress { font-size: 1rem; height: 1.42rem; margin-bottom: 0px; position: relative; box-shadow: inset 1px 0 0 rgba(0,0,0,.15), inset 0 -1px 0 rgba(0,0,0,.15); } .progress.progress-started { background-color: #A0DFFF; background-image: -moz-linear-gradient(top, #A4EDFF, #94DDFF); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#A4EDFF), to(#94DDFF)); background-image: -webkit-linear-gradient(top, #A4EDFF, #94DDFF); background-image: -o-linear-gradient(top, #A4EDFF, #94DDFF); background-image: linear-gradient(to bottom, #A4EDFF, #94DDFF); background-repeat: repeat-x; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#FFA4EDFF', endColorstr='#FF94DDFF', GradientType=0); } .progress .progress-bar { background-color: #3EC0FF; background-image: -moz-linear-gradient(top, #44CBFF, #34B0EE); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#44CBFF), to(#34B0EE)); background-image: -webkit-linear-gradient(top, #44CBFF, #34B0EE); background-image: -o-linear-gradient(top, #44CBFF, #34B0EE); background-image: linear-gradient(to bottom, #64CBFF, #54B0EE); background-repeat: repeat-x; filter: progid:dximagetransform.microsoft.gradient(startColorstr='#FF44CBFF', endColorstr='#FF34B0EE', GradientType=0); } a.kill-link { margin-right: 2px; margin-left: 20px; color: gray; float: right; } a.name-link { word-wrap: break-word; } span.expand-details { font-size: 10pt; cursor: pointer; color: grey; float: right; } span.rest-uri { font-size: 10pt; font-style: italic; color: gray; } pre { background-color: rgba(0, 0, 0, .05); font-size: 12px; line-height: 18px; padding: 6px; margin: 0; word-break: break-word; border: 1px solid rgba(0, 0, 0, 0.15); border-radius: 3px; white-space: pre-wrap; } .stage-details { overflow-y: auto; margin: 0; display: block; transition: max-height 0.25s ease-out, padding 0.25s ease-out; } .stage-details.collapsed { padding-top: 0; padding-bottom: 0; border: none; display: none; } .description-input { overflow: hidden; text-overflow: ellipsis; width: 100%; white-space: nowrap; display: block; } .description-input-full { overflow: hidden; text-overflow: ellipsis; width: 100%; white-space: normal; display: block; } .stacktrace-details { max-height: 300px; overflow-y: auto; margin: 0; display: block; transition: max-height 0.25s ease-out, padding 0.25s ease-out; } .stacktrace-details.collapsed { padding-top: 0; padding-bottom: 0; border: none; display: none; } span.expand-dag-viz, .collapse-table { cursor: pointer; } .collapsible-table.collapsed { display: none; } .tooltip { font-size: 0.786rem; font-weight: normal; } .arrow-open { width: 0; height: 0; border-left: 5px solid transparent; border-right: 5px solid transparent; border-top: 5px solid #08c; display: inline-block; margin-bottom: 2px; } .arrow-closed { width: 0; height: 0; border-top: 5px solid transparent; border-bottom: 5px solid transparent; border-left: 5px solid #08c; display: inline-block; margin-left: 2px; margin-right: 3px; } .version { line-height: 2.5; vertical-align: bottom; font-size: 12px; padding: 0; margin: 0; font-weight: bold; color: #777; } .accordion-inner { background: #f5f5f5; } .accordion-inner pre { border: 0; padding: 0; background: none; } a.expandbutton { cursor: pointer; } .threaddump-td-mouseover { background-color: #49535a !important; color: white; cursor:pointer; } .table-head-clickable th a, .table-head-clickable th a:hover { /* Make the entire header clickable, not just the text label */ display: block; width: 100%; /* Suppress the default link styling */ color: #333; text-decoration: none; } .log-more-btn, .log-new-btn { width: 100% } .no-new-alert { text-align: center; margin: 0; padding: 4px 0; } .table-cell-width-limited td { max-width: 600px; } .page-link { color: #0088cc; } .page-item.active .page-link { background-color: #0088cc; border-color: #0088cc; } .title-table { clear: left; display: inline-block; } .table-dataTable { width: 100%; } .container-fluid-div { width: 200px; } .select-all-div-checkbox-div { width: 90px; } .scheduler-delay-checkbox-div { width: 130px; } .task-deserialization-time-checkbox-div { width: 190px; } .shuffle-read-blocked-time-checkbox-div { width: 200px; } .shuffle-remote-reads-checkbox-div { width: 170px; } .result-serialization-time-checkbox-div { width: 185px; } .getting-result-time-checkbox-div { width: 155px; } .peak-execution-memory-checkbox-div { width: 180px; } #active-tasks-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #active-tasks-table th:first-child { border-left: 1px solid #dddddd; } #accumulator-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #accumulator-table th:first-child { border-left: 1px solid #dddddd; } #summary-executor-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #summary-executor-table th:first-child { border-left: 1px solid #dddddd; } #summary-metrics-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #summary-metrics-table th:first-child { border-left: 1px solid #dddddd; } #summary-execs-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #summary-execs-table th:first-child { border-left: 1px solid #dddddd; } #active-executors-table th { border-top: 1px solid #dddddd; border-bottom: 1px solid #dddddd; border-right: 1px solid #dddddd; } #active-executors-table th:first-child { border-left: 1px solid #dddddd; }
{ "content_hash": "1322b5419cd9c78f906f97bac62dfd5d", "timestamp": "", "source": "github", "line_count": 399, "max_line_length": 121, "avg_line_length": 18.849624060150376, "alnum_prop": 0.679962770908124, "repo_name": "zuotingbing/spark", "id": "f7f8a0e0e9061d29c2aefa98fb729f11c96de2c1", "size": "8321", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/src/main/resources/org/apache/spark/ui/static/webui.css", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "ANTLR", "bytes": "44801" }, { "name": "Batchfile", "bytes": "31085" }, { "name": "C", "bytes": "1493" }, { "name": "CSS", "bytes": "26884" }, { "name": "Dockerfile", "bytes": "8823" }, { "name": "HTML", "bytes": "70460" }, { "name": "HiveQL", "bytes": "1823426" }, { "name": "Java", "bytes": "3993807" }, { "name": "JavaScript", "bytes": "199308" }, { "name": "Makefile", "bytes": "9397" }, { "name": "PLpgSQL", "bytes": "26241" }, { "name": "PowerShell", "bytes": "3867" }, { "name": "Python", "bytes": "2903471" }, { "name": "R", "bytes": "1185346" }, { "name": "Roff", "bytes": "15706" }, { "name": "Scala", "bytes": "29274895" }, { "name": "Shell", "bytes": "201038" }, { "name": "TSQL", "bytes": "370332" }, { "name": "Thrift", "bytes": "67610" }, { "name": "q", "bytes": "146878" } ], "symlink_target": "" }
// NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // Google+ Domains API (plusDomains/v1) // Description: // Builds on top of the Google+ platform for Google Apps Domains. // Documentation: // https://developers.google.com/+/domains/ #if GTLR_BUILT_AS_FRAMEWORK #import "GTLR/GTLRQuery.h" #else #import "GTLRQuery.h" #endif #if GTLR_RUNTIME_VERSION != 3000 #error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source. #endif @class GTLRPlusDomains_Activity; @class GTLRPlusDomains_Circle; @class GTLRPlusDomains_Comment; @class GTLRPlusDomains_Media; NS_ASSUME_NONNULL_BEGIN // ---------------------------------------------------------------------------- // Constants - For some of the query classes' properties below. // ---------------------------------------------------------------------------- // collection /** * The list of people who this user has added to one or more circles. * * Value: "circled" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionCircled; /** * Upload the media to share on Google+. * * Value: "cloud" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionCloud; /** * List all people who have +1'd this activity. * * Value: "plusoners" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionPlusoners; /** * List all people who have reshared this activity. * * Value: "resharers" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionResharers; /** * List all people who this activity was shared to. * * Value: "sharedto" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionSharedto; /** * All activities created by the specified user that the authenticated user is * authorized to view. * * Value: "user" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsCollectionUser; // ---------------------------------------------------------------------------- // orderBy /** * Order the people by their display name. * * Value: "alphabetical" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsOrderByAlphabetical; /** * Order people based on the relevence to the viewer. * * Value: "best" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsOrderByBest; // ---------------------------------------------------------------------------- // sortOrder /** * Sort oldest comments first. * * Value: "ascending" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsSortOrderAscending; /** * Sort newest comments first. * * Value: "descending" */ GTLR_EXTERN NSString * const kGTLRPlusDomainsSortOrderDescending; // ---------------------------------------------------------------------------- // Query Classes // /** * Parent class for other PlusDomains query classes. */ @interface GTLRPlusDomainsQuery : GTLRQuery /** Selector specifying which fields to include in a partial response. */ @property(copy, nullable) NSString *fields; @end /** * Get an activity. * * Method: plusDomains.activities.get * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe * @c kGTLRAuthScopePlusDomainsPlusStreamRead */ @interface GTLRPlusDomainsQuery_ActivitiesGet : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForActivitiesGetWithactivityId:] /** The ID of the activity to get. */ @property(copy, nullable) NSString *activityId; /** * Fetches a @c GTLRPlusDomains_Activity. * * Get an activity. * * @param activityId The ID of the activity to get. * * @returns GTLRPlusDomainsQuery_ActivitiesGet */ + (instancetype)queryWithActivityId:(NSString *)activityId; @end /** * Create a new activity for the authenticated user. * * Method: plusDomains.activities.insert * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe * @c kGTLRAuthScopePlusDomainsPlusStreamWrite */ @interface GTLRPlusDomainsQuery_ActivitiesInsert : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForActivitiesInsertWithObject:userId:] /** * If "true", extract the potential media attachments for a URL. The response * will include all possible attachments for a URL, including video, photos, * and articles based on the content of the page. */ @property(assign) BOOL preview; /** * The ID of the user to create the activity on behalf of. Its value should be * "me", to indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_Activity. * * Create a new activity for the authenticated user. * * @param object The @c GTLRPlusDomains_Activity to include in the query. * @param userId The ID of the user to create the activity on behalf of. Its * value should be "me", to indicate the authenticated user. * * @returns GTLRPlusDomainsQuery_ActivitiesInsert */ + (instancetype)queryWithObject:(GTLRPlusDomains_Activity *)object userId:(NSString *)userId; @end /** * List all of the activities in the specified collection for a particular * user. * * Method: plusDomains.activities.list * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe * @c kGTLRAuthScopePlusDomainsPlusStreamRead */ @interface GTLRPlusDomainsQuery_ActivitiesList : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForActivitiesListWithuserId:collection:] /** * The collection of activities to list. * * Likely values: * @arg @c kGTLRPlusDomainsCollectionUser All activities created by the * specified user that the authenticated user is authorized to view. * (Value: "user") */ @property(copy, nullable) NSString *collection; /** * The maximum number of activities to include in the response, which is used * for paging. For any response, the actual number returned might be less than * the specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * The ID of the user to get activities for. The special value "me" can be used * to indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_ActivityFeed. * * List all of the activities in the specified collection for a particular * user. * * @param userId The ID of the user to get activities for. The special value * "me" can be used to indicate the authenticated user. * @param collection The collection of activities to list. * * Likely values for @c collection: * @arg @c kGTLRPlusDomainsCollectionUser All activities created by the * specified user that the authenticated user is authorized to view. * (Value: "user") * * @returns GTLRPlusDomainsQuery_ActivitiesList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithUserId:(NSString *)userId collection:(NSString *)collection; @end /** * List all of the audiences to which a user can share. * * Method: plusDomains.audiences.list * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesRead * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe */ @interface GTLRPlusDomainsQuery_AudiencesList : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForAudiencesListWithuserId:] /** * The maximum number of circles to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * The ID of the user to get audiences for. The special value "me" can be used * to indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_AudiencesFeed. * * List all of the audiences to which a user can share. * * @param userId The ID of the user to get audiences for. The special value * "me" can be used to indicate the authenticated user. * * @returns GTLRPlusDomainsQuery_AudiencesList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithUserId:(NSString *)userId; @end /** * Add a person to a circle. Google+ limits certain circle operations, * including the number of circle adds. Learn More. * * Method: plusDomains.circles.addPeople * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesAddPeople : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesAddPeopleWithcircleId:] /** The ID of the circle to add the person to. */ @property(copy, nullable) NSString *circleId; /** Email of the people to add to the circle. Optional, can be repeated. */ @property(strong, nullable) NSArray<NSString *> *email; /** IDs of the people to add to the circle. Optional, can be repeated. */ @property(strong, nullable) NSArray<NSString *> *userId; /** * Fetches a @c GTLRPlusDomains_Circle. * * Add a person to a circle. Google+ limits certain circle operations, * including the number of circle adds. Learn More. * * @param circleId The ID of the circle to add the person to. * * @returns GTLRPlusDomainsQuery_CirclesAddPeople */ + (instancetype)queryWithCircleId:(NSString *)circleId; @end /** * Get a circle. * * Method: plusDomains.circles.get * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesRead * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesGet : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesGetWithcircleId:] /** The ID of the circle to get. */ @property(copy, nullable) NSString *circleId; /** * Fetches a @c GTLRPlusDomains_Circle. * * Get a circle. * * @param circleId The ID of the circle to get. * * @returns GTLRPlusDomainsQuery_CirclesGet */ + (instancetype)queryWithCircleId:(NSString *)circleId; @end /** * Create a new circle for the authenticated user. * * Method: plusDomains.circles.insert * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe */ @interface GTLRPlusDomainsQuery_CirclesInsert : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesInsertWithObject:userId:] /** * The ID of the user to create the circle on behalf of. The value "me" can be * used to indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_Circle. * * Create a new circle for the authenticated user. * * @param object The @c GTLRPlusDomains_Circle to include in the query. * @param userId The ID of the user to create the circle on behalf of. The * value "me" can be used to indicate the authenticated user. * * @returns GTLRPlusDomainsQuery_CirclesInsert */ + (instancetype)queryWithObject:(GTLRPlusDomains_Circle *)object userId:(NSString *)userId; @end /** * List all of the circles for a user. * * Method: plusDomains.circles.list * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesRead * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe */ @interface GTLRPlusDomainsQuery_CirclesList : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesListWithuserId:] /** * The maximum number of circles to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * The ID of the user to get circles for. The special value "me" can be used to * indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_CircleFeed. * * List all of the circles for a user. * * @param userId The ID of the user to get circles for. The special value "me" * can be used to indicate the authenticated user. * * @returns GTLRPlusDomainsQuery_CirclesList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithUserId:(NSString *)userId; @end /** * Update a circle's description. This method supports patch semantics. * * Method: plusDomains.circles.patch * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesPatch : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesPatchWithObject:circleId:] /** The ID of the circle to update. */ @property(copy, nullable) NSString *circleId; /** * Fetches a @c GTLRPlusDomains_Circle. * * Update a circle's description. This method supports patch semantics. * * @param object The @c GTLRPlusDomains_Circle to include in the query. * @param circleId The ID of the circle to update. * * @returns GTLRPlusDomainsQuery_CirclesPatch */ + (instancetype)queryWithObject:(GTLRPlusDomains_Circle *)object circleId:(NSString *)circleId; @end /** * Delete a circle. * * Method: plusDomains.circles.remove * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesRemove : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesRemoveWithcircleId:] /** The ID of the circle to delete. */ @property(copy, nullable) NSString *circleId; /** * Upon successful completion, the callback's object and error parameters will * be nil. This query does not fetch an object. * * Delete a circle. * * @param circleId The ID of the circle to delete. * * @returns GTLRPlusDomainsQuery_CirclesRemove */ + (instancetype)queryWithCircleId:(NSString *)circleId; @end /** * Remove a person from a circle. * * Method: plusDomains.circles.removePeople * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesRemovePeople : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesRemovePeopleWithcircleId:] /** The ID of the circle to remove the person from. */ @property(copy, nullable) NSString *circleId; /** Email of the people to add to the circle. Optional, can be repeated. */ @property(strong, nullable) NSArray<NSString *> *email; /** IDs of the people to remove from the circle. Optional, can be repeated. */ @property(strong, nullable) NSArray<NSString *> *userId; /** * Upon successful completion, the callback's object and error parameters will * be nil. This query does not fetch an object. * * Remove a person from a circle. * * @param circleId The ID of the circle to remove the person from. * * @returns GTLRPlusDomainsQuery_CirclesRemovePeople */ + (instancetype)queryWithCircleId:(NSString *)circleId; @end /** * Update a circle's description. * * Method: plusDomains.circles.update * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesWrite * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_CirclesUpdate : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCirclesUpdateWithObject:circleId:] /** The ID of the circle to update. */ @property(copy, nullable) NSString *circleId; /** * Fetches a @c GTLRPlusDomains_Circle. * * Update a circle's description. * * @param object The @c GTLRPlusDomains_Circle to include in the query. * @param circleId The ID of the circle to update. * * @returns GTLRPlusDomainsQuery_CirclesUpdate */ + (instancetype)queryWithObject:(GTLRPlusDomains_Circle *)object circleId:(NSString *)circleId; @end /** * Get a comment. * * Method: plusDomains.comments.get * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusStreamRead */ @interface GTLRPlusDomainsQuery_CommentsGet : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCommentsGetWithcommentId:] /** The ID of the comment to get. */ @property(copy, nullable) NSString *commentId; /** * Fetches a @c GTLRPlusDomains_Comment. * * Get a comment. * * @param commentId The ID of the comment to get. * * @returns GTLRPlusDomainsQuery_CommentsGet */ + (instancetype)queryWithCommentId:(NSString *)commentId; @end /** * Create a new comment in reply to an activity. * * Method: plusDomains.comments.insert * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusStreamWrite */ @interface GTLRPlusDomainsQuery_CommentsInsert : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCommentsInsertWithObject:activityId:] /** The ID of the activity to reply to. */ @property(copy, nullable) NSString *activityId; /** * Fetches a @c GTLRPlusDomains_Comment. * * Create a new comment in reply to an activity. * * @param object The @c GTLRPlusDomains_Comment to include in the query. * @param activityId The ID of the activity to reply to. * * @returns GTLRPlusDomainsQuery_CommentsInsert */ + (instancetype)queryWithObject:(GTLRPlusDomains_Comment *)object activityId:(NSString *)activityId; @end /** * List all of the comments for an activity. * * Method: plusDomains.comments.list * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusStreamRead */ @interface GTLRPlusDomainsQuery_CommentsList : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForCommentsListWithactivityId:] /** The ID of the activity to get comments for. */ @property(copy, nullable) NSString *activityId; /** * The maximum number of comments to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 0..500). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * The order in which to sort the list of comments. * * Likely values: * @arg @c kGTLRPlusDomainsSortOrderAscending Sort oldest comments first. * (Value: "ascending") * @arg @c kGTLRPlusDomainsSortOrderDescending Sort newest comments first. * (Value: "descending") * * @note If not set, the documented server-side default will be * kGTLRPlusDomainsSortOrderAscending. */ @property(copy, nullable) NSString *sortOrder; /** * Fetches a @c GTLRPlusDomains_CommentFeed. * * List all of the comments for an activity. * * @param activityId The ID of the activity to get comments for. * * @returns GTLRPlusDomainsQuery_CommentsList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithActivityId:(NSString *)activityId; @end /** * Add a new media item to an album. The current upload size limitations are * 36MB for a photo and 1GB for a video. Uploads do not count against quota if * photos are less than 2048 pixels on their longest side or videos are less * than 15 minutes in length. * * Method: plusDomains.media.insert * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe * @c kGTLRAuthScopePlusDomainsPlusMediaUpload */ @interface GTLRPlusDomainsQuery_MediaInsert : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForMediaInsertWithObject:userId:collection:] /** * collection * * Likely values: * @arg @c kGTLRPlusDomainsCollectionCloud Upload the media to share on * Google+. (Value: "cloud") */ @property(copy, nullable) NSString *collection; /** The ID of the user to create the activity on behalf of. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_Media. * * Add a new media item to an album. The current upload size limitations are * 36MB for a photo and 1GB for a video. Uploads do not count against quota if * photos are less than 2048 pixels on their longest side or videos are less * than 15 minutes in length. * * @param object The @c GTLRPlusDomains_Media to include in the query. * @param userId The ID of the user to create the activity on behalf of. * @param collection NSString * * Likely values for @c collection: * @arg @c kGTLRPlusDomainsCollectionCloud Upload the media to share on * Google+. (Value: "cloud") * @param uploadParameters The media to include in this query. Accepted MIME * types: image/ *, video/ * * * @returns GTLRPlusDomainsQuery_MediaInsert */ + (instancetype)queryWithObject:(GTLRPlusDomains_Media *)object userId:(NSString *)userId collection:(NSString *)collection uploadParameters:(nullable GTLRUploadParameters *)uploadParameters; @end /** * Get a person's profile. * * Method: plusDomains.people.get * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe * @c kGTLRAuthScopePlusDomainsPlusProfilesRead * @c kGTLRAuthScopePlusDomainsUserinfoEmail * @c kGTLRAuthScopePlusDomainsUserinfoProfile */ @interface GTLRPlusDomainsQuery_PeopleGet : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForPeopleGetWithuserId:] /** * The ID of the person to get the profile for. The special value "me" can be * used to indicate the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_Person. * * Get a person's profile. * * @param userId The ID of the person to get the profile for. The special value * "me" can be used to indicate the authenticated user. * * @returns GTLRPlusDomainsQuery_PeopleGet */ + (instancetype)queryWithUserId:(NSString *)userId; @end /** * List all of the people in the specified collection. * * Method: plusDomains.people.list * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesRead * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusMe */ @interface GTLRPlusDomainsQuery_PeopleList : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForPeopleListWithuserId:collection:] /** * The collection of people to list. * * Likely values: * @arg @c kGTLRPlusDomainsCollectionCircled The list of people who this user * has added to one or more circles. (Value: "circled") */ @property(copy, nullable) NSString *collection; /** * The maximum number of people to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 100 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The order to return people in. * * Likely values: * @arg @c kGTLRPlusDomainsOrderByAlphabetical Order the people by their * display name. (Value: "alphabetical") * @arg @c kGTLRPlusDomainsOrderByBest Order people based on the relevence to * the viewer. (Value: "best") */ @property(copy, nullable) NSString *orderBy; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * Get the collection of people for the person identified. Use "me" to indicate * the authenticated user. */ @property(copy, nullable) NSString *userId; /** * Fetches a @c GTLRPlusDomains_PeopleFeed. * * List all of the people in the specified collection. * * @param userId Get the collection of people for the person identified. Use * "me" to indicate the authenticated user. * @param collection The collection of people to list. * * Likely values for @c collection: * @arg @c kGTLRPlusDomainsCollectionCircled The list of people who this user * has added to one or more circles. (Value: "circled") * * @returns GTLRPlusDomainsQuery_PeopleList * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithUserId:(NSString *)userId collection:(NSString *)collection; @end /** * List all of the people in the specified collection for a particular * activity. * * Method: plusDomains.people.listByActivity * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusLogin * @c kGTLRAuthScopePlusDomainsPlusStreamRead */ @interface GTLRPlusDomainsQuery_PeopleListByActivity : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForPeopleListByActivityWithactivityId:collection:] /** The ID of the activity to get the list of people for. */ @property(copy, nullable) NSString *activityId; /** * The collection of people to list. * * Likely values: * @arg @c kGTLRPlusDomainsCollectionPlusoners List all people who have +1'd * this activity. (Value: "plusoners") * @arg @c kGTLRPlusDomainsCollectionResharers List all people who have * reshared this activity. (Value: "resharers") * @arg @c kGTLRPlusDomainsCollectionSharedto List all people who this * activity was shared to. (Value: "sharedto") */ @property(copy, nullable) NSString *collection; /** * The maximum number of people to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * Fetches a @c GTLRPlusDomains_PeopleFeed. * * List all of the people in the specified collection for a particular * activity. * * @param activityId The ID of the activity to get the list of people for. * @param collection The collection of people to list. * * Likely values for @c collection: * @arg @c kGTLRPlusDomainsCollectionPlusoners List all people who have +1'd * this activity. (Value: "plusoners") * @arg @c kGTLRPlusDomainsCollectionResharers List all people who have * reshared this activity. (Value: "resharers") * @arg @c kGTLRPlusDomainsCollectionSharedto List all people who this * activity was shared to. (Value: "sharedto") * * @returns GTLRPlusDomainsQuery_PeopleListByActivity * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithActivityId:(NSString *)activityId collection:(NSString *)collection; @end /** * List all of the people who are members of a circle. * * Method: plusDomains.people.listByCircle * * Authorization scope(s): * @c kGTLRAuthScopePlusDomainsPlusCirclesRead * @c kGTLRAuthScopePlusDomainsPlusLogin */ @interface GTLRPlusDomainsQuery_PeopleListByCircle : GTLRPlusDomainsQuery // Previous library name was // +[GTLQueryPlusDomains queryForPeopleListByCircleWithcircleId:] /** The ID of the circle to get the members of. */ @property(copy, nullable) NSString *circleId; /** * The maximum number of people to include in the response, which is used for * paging. For any response, the actual number returned might be less than the * specified maxResults. * * @note If not set, the documented server-side default will be 20 (from the * range 1..100). */ @property(assign) NSUInteger maxResults; /** * The continuation token, which is used to page through large result sets. To * get the next page of results, set this parameter to the value of * "nextPageToken" from the previous response. */ @property(copy, nullable) NSString *pageToken; /** * Fetches a @c GTLRPlusDomains_PeopleFeed. * * List all of the people who are members of a circle. * * @param circleId The ID of the circle to get the members of. * * @returns GTLRPlusDomainsQuery_PeopleListByCircle * * @note Automatic pagination will be done when @c shouldFetchNextPages is * enabled. See @c shouldFetchNextPages on @c GTLRService for more * information. */ + (instancetype)queryWithCircleId:(NSString *)circleId; @end NS_ASSUME_NONNULL_END
{ "content_hash": "ec0263ca9dbea0a0bb6a59b0e93ec9f9", "timestamp": "", "source": "github", "line_count": 1027, "max_line_length": 126, "avg_line_length": 30.41869522882181, "alnum_prop": 0.7124199743918054, "repo_name": "googlecreativelab/Sprayscape", "id": "e56a51130134efaebb42d11599691bae14bf6a27", "size": "31240", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Sprayscape/Assets/Plugins/GoogleDrivePlugin/Plugins/iOS/google-api-objectivec-client-for-rest/Source/GeneratedServices/PlusDomains/GTLRPlusDomainsQuery.h", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "C#", "bytes": "590239" }, { "name": "HLSL", "bytes": "4730" }, { "name": "Java", "bytes": "30392" }, { "name": "JavaScript", "bytes": "1554" }, { "name": "Objective-C", "bytes": "10576417" }, { "name": "Objective-C++", "bytes": "30880" }, { "name": "Ruby", "bytes": "16874" }, { "name": "ShaderLab", "bytes": "17021" }, { "name": "Shell", "bytes": "3452" } ], "symlink_target": "" }
angular.module('MapBiomas.workmap').factory('WorkspaceLayers', ['AppConfig', '$filter', "$injector", function(AppConfig, $filter, $injector) { return { imgsref: function(wgis) { var mapfilepath = AppConfig.MAPSERVER.mapfilepath; var mapfilehost = AppConfig.MAPSERVER.mapfilehost; var biomas = ['AMAZONIA', 'CAATINGA', 'CERRADO', 'PAMPA', 'PANTANAL', 'MATAATLANTICA']; var anos = []; // valores iniciais dos anos for (var i = 2000; i <= 2016; i++) { anos.push(i); } /** * COLEÇÂO 1 */ wgis.addNodeLabel($filter('translate')('COLECAO') + " 1"); wgis.addNodeLabel($filter('translate')('CONSOLIDADOCLASSIFICACAO'), $filter('translate')('COLECAO') + " 1"); /* * MapBiomas Consolidado */ wgis.addNodeLabel($filter('translate')('CLASSIFICACAONAOCONSOLIDADA'), $filter('translate')('COLECAO') + " 1"); var biomasAnos = {}; biomasAnos[$filter('translate')('AMAZONIA')] = { "collection": "AMAZONIA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('CAATINGA')] = { "collection": "CAATINGA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('CERRADO')] = { "collection": "CERRADO", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('MATAATLANTICA')] = { "collection": "MATAATLANTICA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('PAMPA')] = { "collection": "PAMPA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('PANTANAL')] = { "collection": "PANTANAL", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; biomasAnos[$filter('translate')('ZONACOSTEIRA')] = { "collection": "ZONACOSTEIRA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; angular.forEach(biomasAnos, function(bioma, biomaName) { if (bioma.anos.length > 0) { wgis.addNodeLabel(biomaName, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); console.log(biomaName, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); } if (biomaName === $filter('translate')('ZONACOSTEIRA')) { wgis.addNodeLabel($filter('translate')('AGRICULTURA'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); wgis.addNodeLabel($filter('translate')('CANADEACUCAR'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); wgis.addNodeLabel($filter('translate')('FLORESTAPLANTADA'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); wgis.addNodeLabel($filter('translate')('PASTAGEM'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); } angular.forEach(bioma.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/classification/bioma.map", layers: 'bioma', year: ano, bioma_collection: bioma.collection, classification_ids: 1, format: 'image/png', transparent: true } }, $filter('translate')('FLORESTA'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + biomaName + "+>" + ano, false, "img/legendas/floresta.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/classification/bioma.map", layers: 'bioma', bioma_collection: bioma.collection, year: ano, classification_ids: 2, format: 'image/png', transparent: true } }, $filter('translate')('NAOFLORESTA'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + biomaName + "+>" + ano, false, "img/legendas/naofloresta.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/classification/bioma.map", layers: 'bioma', year: ano, bioma_collection: bioma.collection, classification_ids: 3, format: 'image/png', transparent: true } }, $filter('translate')('AGUA'), $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + biomaName + "+>" + ano, false, "img/legendas/agua.png"); }); }); // Cana var cana_florestaplantadaClasses = {}; cana_florestaplantadaClasses[$filter('translate')('CANADEACUCAR')] = { "icon": "img/legendas/cana.png", "collection": "AMAZONIA", "anos": { "2008": "0708", "2009": "0809", "2010": "0910", "2011": "1011", "2013": "1113", "2014": "1314" } }; cana_florestaplantadaClasses[$filter('translate')('FLORESTAPLANTADA')] = { "icon": "img/legendas/florestaplantada.png", "collection": "AMAZONIA", "anos": { "2008": "0708", "2009": "0809", "2010": "0910", "2011": "1011", "2013": "1113", "2014": "1314" } }; angular.forEach(cana_florestaplantadaClasses, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/cana_florestaplantada.map", layers: 'cana', year: ano, class_cana: subclassName === $filter('translate')('CANADEACUCAR'), class_florestaplantada: subclassName === $filter('translate')('FLORESTAPLANTADA'), format: 'image/png', transparent: true } }, anoKey, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + subclassName, false, subclass.icon); }); }); // Agricultura wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '0708', format: 'image/png', transparent: true } }, "2008", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '0809', format: 'image/png', transparent: true } }, "2009", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '0910', format: 'image/png', transparent: true } }, "2010", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '1011', format: 'image/png', transparent: true } }, "2011", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '111213', format: 'image/png', transparent: true } }, "2013", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'crop', years: '1314', format: 'image/png', transparent: true } }, "2014", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('AGRICULTURA'), false, "img/legendas/agricultura.png"); // Pastagem wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '0708', format: 'image/png', transparent: true } }, "2008", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '0809', format: 'image/png', transparent: true } }, "2009", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '0910', format: 'image/png', transparent: true } }, "2010", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '1011', format: 'image/png', transparent: true } }, "2011", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '111213', format: 'image/png', transparent: true } }, "2013", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/croppasture.map", layers: 'croppasture', class: 'pasture', years: '1314', format: 'image/png', transparent: true } }, "2014", $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')('PASTAGEM'), false, "img/legendas/pastagem.png"); /* * MapBiomas Consolidado */ // wgis.addNodeLabel($filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO')); var consolidado = {}; consolidado[$filter('translate')('AMAZONIA')] = { "collection": "AMAZONIA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('CAATINGA')] = { "collection": "CAATINGA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('CERRADO')] = { "collection": "CERRADO", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('MATAATLANTICA')] = { "collection": "MATAATLANTICA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('PAMPA')] = { "collection": "PAMPA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('PANTANAL')] = { "collection": "PANTANAL", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014", "2015"] }; consolidado[$filter('translate')('ZONACOSTEIRA')] = { "collection": "ZONACOSTEIRA", "anos": [] }; var consolidadoClasses = { 1: $filter('translate')('FLORESTA'), 2: $filter('translate')('NAOFLORESTA'), 3: $filter('translate')('AGUA'), 4: "Vegetação não florestal", 5: $filter('translate')('PASTAGEM'), 6: $filter('translate')('AGRICULTURA'), 7: $filter('translate')('FLORESTAPLANTADA') //8: "Floresta da zona costeira" }; var legends_icons = { 0: "img/legendas/colecao1/nodata_0.png", 1: "img/legendas/colecao1/floresta_1.png", 2: "img/legendas/colecao1/naofloresta_2.png", 3: "img/legendas/colecao1/agua_3.png", 4: "img/legendas/colecao1/vegetacaonaoflorestal_4.png", 5: "img/legendas/colecao1/pastagem_5.png", 6: "img/legendas/colecao1/agricultura_6.png", 7: "img/legendas/colecao1/florestaplantada_7.png", 8: "img/legendas/colecao1/florestazonacosteira_8.png", }; angular.forEach(consolidado, function(bioma, biomaName) { if (bioma.anos.length > 0) { wgis.addNodeLabel(biomaName, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO')); } angular.forEach(bioma.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/classification/bioma_integrate.map", layers: 'bioma', year: ano, bioma_collection: bioma.collection, classification_ids: [1, 2, 3, 4, 5, 6, 7, 8], format: 'image/png', transparent: true } }, ano, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO') + "+>" + biomaName, false, 'img/layergroup.png'); var DtreeClasses = $injector.get('DtreeClasses').getClasses("0"); angular.forEach(DtreeClasses, function(classedtree) { var id = classedtree.id var nameclass = classedtree.classe var icon = legends_icons[id] wgis.addNodeLabel(nameclass, $filter('translate')('COLECAO') + " 1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO') + "+>" + biomaName + "+>" + ano, icon ); }); }); }); // wgis.addNodeLabel(subclassName, $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('PAMPA')+ "+>" + ano, // subclass.icon /** * COLEÇÂO 2 */ var assetServiceCol2 = new MapbiomasAssetService({ 'assets': { 'regioes': 'projects/mapbiomas-workspace/AUXILIAR/regioes', 'mosaico': 'projects/mapbiomas-workspace/MOSAICOS/workspace', 'classificacao': 'projects/mapbiomas-workspace/COLECAO2/classificacao', 'classificacaoft': 'projects/mapbiomas-workspace/COLECAO2/classificacao-ft', }, "palette": "#129912,#1f4423,#006400,#00ff00,#65c24b,#687537," + "#76a5af,#29eee4,#77a605,#935132,#ffe599,#45c2a5,#f1c232,#b8af4f,#ffffb2," + "#ffd966,#ffe599,#f6b26b,#e974ed,#d5a6bd,#c27ba0,#a64d79,#ea9999,#cc4125," + "#dd7e6b,#e6b8af,#980000,#999999,#b7b7b7,#434343,#d9d9d9,#0000ff,#d5d5e5" }); wgis.addNodeLabel($filter('translate')('COLECAO') + " 2"); wgis.addNodeLabel($filter('translate')('MOSAICOIMAGENS') + " (Beta)", $filter('translate')('COLECAO') + " 2"); wgis.addNodeLabel($filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " (Beta)", $filter('translate')('COLECAO') + " 2"); // Mosaico angular.forEach(biomas, function(assetBioma, biomaIndex) { anos.forEach(function(assetAno, anoIndex) { if (anoIndex == 0) { wgis.addNodeLabel($filter('translate')(assetBioma), $filter('translate')('COLECAO') + " 2+>" + $filter('translate')('MOSAICOIMAGENS') + " (Beta)", 'img/layergroup.png'); } var geeMosaicLayer = new L.TileLayer.GeeScript(function(callback) { var assetTileUrl = assetServiceCol2 .getMosaicByBiomaYear(assetBioma, assetAno); callback(assetTileUrl); }); wgis.addLayer(geeMosaicLayer, assetAno, $filter('translate')('COLECAO') + " 2+>" + $filter('translate')('MOSAICOIMAGENS') + " (Beta)" + "+>" + $filter('translate')(assetBioma), false); }); }); var legends_icons_col2 = { 1: "img/legendas/colecao2/formacoesflorestais_1.png", 2: "img/legendas/colecao2/formacoesflorestaisnaturais_2.png", 3: "img/legendas/colecao2/florestadensa_3.png", 4: "img/legendas/colecao2/florestaaberta_4.png", 5: "img/legendas/colecao2/florestarasa_5.png", 6: "img/legendas/colecao2/mangue_6.png", 7: "img/legendas/colecao2/florestaalagada_7.png", 8: "img/legendas/colecao2/florestadegradada_8.png", 9: "img/legendas/colecao2/florestasecundaria_9.png", 10: "img/legendas/colecao2/silvicultura_10.png", 11: "img/legendas/colecao2/formacoesnaturaisnaoflorestais_11.png", 12: "img/legendas/colecao2/formacoesnaoflorestaisemareasumidas_12.png", 13: "img/legendas/colecao2/dunasvegetadas_13.png", 14: "img/legendas/colecao2/vegetacaocampestre_14.png", 15: "img/legendas/colecao2/agropecuaria_15.png", 16: "img/legendas/colecao2/pastagem_16.png", 17: "img/legendas/colecao2/pastagemnaodegradada_17.png", 18: "img/legendas/colecao2/pastagemdegradada_18.png", 19: "img/legendas/colecao2/agricultura_19.png", 20: "img/legendas/colecao2/culturasanuais_20.png", 21: "img/legendas/colecao2/culturassemiperene_21.png", 22: "img/legendas/colecao2/culturasperenes_22.png", 23: "img/legendas/colecao2/areasnaovegetadas_23.png", 24: "img/legendas/colecao2/formacoesnaturaisnaovegetadas_24.png", 25: "img/legendas/colecao2/praiasedunas_25.png", 26: "img/legendas/colecao2/afloramentosrochosos_26.png", 27: "img/legendas/colecao2/recifesdecorais_27.png", 28: "img/legendas/colecao2/outrasareasnaovegetadas_28.png", 29: "img/legendas/colecao2/areasurbanas_29.png", 30: "img/legendas/colecao2/mineracao_30.png", 31: "img/legendas/colecao2/outrasareasnaovegetadas_31.png", 32: "img/legendas/colecao2/corposdagua_32.png", 33: "img/legendas/colecao2/naoobservado_33.png", }; // Classificação angular.forEach(biomas, function(assetBioma, biomaIndex) { angular.forEach(anos, function(assetAno, anoIndex) { if (anoIndex == 0) { wgis.addNodeLabel($filter('translate')(assetBioma), $filter('translate')('COLECAO') + " 2+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " (Beta)"); } var geeClassLayer = new L.TileLayer.GeeScript(function(callback) { var assetTileUrl = assetServiceCol2 .getClassifByBiomaYear(assetBioma, assetAno); callback(assetTileUrl); }); wgis.addLayer(geeClassLayer, String(assetAno), $filter('translate')('COLECAO') + " 2+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " (Beta)+>" + $filter('translate')(assetBioma), false); var DtreeClasses = $injector.get('DtreeClasses').getClasses("2"); angular.forEach(DtreeClasses, function(classedtree) { var id = classedtree.id var nameclass = classedtree.classe var icon = legends_icons_col2[id] wgis.addNodeLabel(nameclass, $filter('translate')('COLECAO') + " 2+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " (Beta)+>" + $filter('translate')(assetBioma) + "+>" + assetAno, icon ); }); }); }); /** * COLEÇÂO 2.1 */ var assetServiceCol21 = new MapbiomasAssetService({ 'assets': { 'regioes': 'projects/mapbiomas-workspace/AUXILIAR/regioes2_1', 'mosaico': 'projects/mapbiomas-workspace/MOSAICOS/workspace', 'classificacao': 'projects/mapbiomas-workspace/COLECAO2_1/classificacao', 'classificacaoft': 'projects/mapbiomas-workspace/COLECAO2_1/classificacao-ft', }, "palette": "FFFFFF,129912,1F4423,006400,00FF00," + "687537,76A5AF,29EEE4,77A605,935132," + "FF9966,45C2A5,B8AF4F,F1C232,FFFFB2," + "FFD966,F6B26B,A0D0DE,E974ED,D5A6BD," + "C27BA0,FFEFC3,EA9999,DD7E6B,B7B7B7," + "FF99FF,0000FF,D5D5E5" }); wgis.addNodeLabel($filter('translate')('COLECAO') + " 2.1"); wgis.addNodeLabel($filter('translate')('CLASSIFICACAONAOCONSOLIDADA'), $filter('translate')('COLECAO') + " 2.1"); var legends_icons_col21 = { 1: "img/legendas/colecao2_1/formacoesflorestais_1.png", 2: "img/legendas/colecao2_1/formacoesflorestaisnaturais_2.png", 3: "img/legendas/colecao2_1/florestadensa_3.png", 4: "img/legendas/colecao2_1/florestaaberta_4.png", 5: "img/legendas/colecao2_1/mangue_5.png", 6: "img/legendas/colecao2_1/florestaalagada_6.png", 7: "img/legendas/colecao2_1/florestadegradada_7.png", 8: "img/legendas/colecao2_1/florestasecundaria_8.png", 9: "img/legendas/colecao2_1/silvicultura_9.png", 10: "img/legendas/colecao2_1/formacoesnaturaisnaoflorestais_10.png", 11: "img/legendas/colecao2_1/areasumidasnaturaisnaoflorestais_11.png", 12: "img/legendas/colecao2_1/vegetacaocampestre_12.png", 13: "img/legendas/colecao2_1/outrasformacoesnaoflorestais_13.png", 14: "img/legendas/colecao2_1/usoagropecuario_14.png", 15: "img/legendas/colecao2_1/pastagem_15.png", 16: "img/legendas/colecao2_1/pastagememcamposnaturais_16.png", 17: "img/legendas/colecao2_1/outraspastagens_17.png", 18: "img/legendas/colecao2_1/agricultura_18.png", 19: "img/legendas/colecao2_1/culturasanuais_19.png", 20: "img/legendas/colecao2_1/culturassemiperene_20.png", 21: "img/legendas/colecao2_1/agriculturaoupastagem_21.png", 22: "img/legendas/colecao2_1/areasnaovegetadas_22.png", 23: "img/legendas/colecao2_1/praiasedunas_23.png", 24: "img/legendas/colecao2_1/areasurbanas_24.png", 25: "img/legendas/colecao2_1/outrasareasnaovegetadas_25.png", 26: "img/legendas/colecao2_1/corposdagua_26.png", 27: "img/legendas/colecao2_1/naoobservado_27.png", 28: "img/legendas/colecao2_1/mosaicodecultivos_28.png" }; // Classificação angular.forEach(biomas, function(assetBioma, biomaIndex) { angular.forEach(anos, function(assetAno, anoIndex) { if (anoIndex == 0) { wgis.addNodeLabel($filter('translate')(assetBioma), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA')); } var geeClassLayer = new L.TileLayer.GeeScript(function(callback) { var assetTileUrl = assetServiceCol21 .getClassifByBiomaYear(assetBioma, assetAno); callback(assetTileUrl); }); wgis.addLayer(geeClassLayer, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')(assetBioma), false); var DtreeClasses = $injector.get('DtreeClasses').getClasses("3"); angular.forEach(DtreeClasses, function(classedtree) { var id = classedtree.id var nameclass = classedtree.classe var icon = legends_icons_col21[id] wgis.addNodeLabel(nameclass, $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + "+>" + $filter('translate')(assetBioma) + "+>" + assetAno, icon ); }); }); }); // Classificação FT 2.1 var assetServiceCol21_ft = new MapbiomasAssetService({ 'assets': { 'regioes': 'projects/mapbiomas-workspace/AUXILIAR/regioes2_1', 'mosaico': 'projects/mapbiomas-workspace/MOSAICOS/workspace', 'classificacao': 'projects/mapbiomas-workspace/COLECAO2_1/classificacao-ft', }, "palette": "FFFFFF,129912,1F4423,006400,00FF00," + "687537,76A5AF,29EEE4,77A605,935132," + "FF9966,45C2A5,B8AF4F,F1C232,FFFFB2," + "FFD966,F6B26B,A0D0DE,E974ED,D5A6BD," + "C27BA0,FFEFC3,EA9999,DD7E6B,B7B7B7," + "FF99FF,0000FF,D5D5E5" }); wgis.addNodeLabel($filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " FT", $filter('translate')('COLECAO') + " 2.1"); angular.forEach(biomas, function(assetBioma, biomaIndex) { angular.forEach(anos, function(assetAno, anoIndex) { if (anoIndex == 0) { wgis.addNodeLabel($filter('translate')(assetBioma), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " FT"); } var geeClassLayer = new L.TileLayer.GeeScript(function(callback) { var assetTileUrl = assetServiceCol21_ft .getClassifByBiomaYear(assetBioma, assetAno); callback(assetTileUrl); }); wgis.addLayer(geeClassLayer, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " FT+>" + $filter('translate')(assetBioma), false); var DtreeClasses = $injector.get('DtreeClasses').getClasses("3"); angular.forEach(DtreeClasses, function(classedtree) { var id = classedtree.id var nameclass = classedtree.classe var icon = legends_icons_col21[id] wgis.addNodeLabel(nameclass, $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CLASSIFICACAONAOCONSOLIDADA') + " FT+>" + $filter('translate')(assetBioma) + "+>" + assetAno, icon ); }); }); }); // Classificação Consolidado 2.1 var assetServiceCol21_Consolidate = new MapbiomasAssetService({ 'assets': { 'regioes': 'projects/mapbiomas-workspace/AUXILIAR/regioes2_1', 'mosaico': 'projects/mapbiomas-workspace/MOSAICOS/workspace', 'classificacao': 'projects/mapbiomas-workspace/COLECAO2_1/integracao', }, "palette": "FFFFFF,129912,1F4423,006400,00FF00," + "687537,76A5AF,29EEE4,77A605,935132," + "FF9966,45C2A5,B8AF4F,F1C232,FFFFB2," + "FFD966,F6B26B,A0D0DE,E974ED,D5A6BD," + "C27BA0,FFEFC3,EA9999,DD7E6B,B7B7B7," + "FF99FF,0000FF,D5D5E5,CE3D3D" }); wgis.addNodeLabel($filter('translate')('CONSOLIDADOCLASSIFICACAO'), $filter('translate')('COLECAO') + " 2.1"); angular.forEach(biomas, function(assetBioma, biomaIndex) { angular.forEach(anos, function(assetAno, anoIndex) { if (anoIndex == 0) { wgis.addNodeLabel($filter('translate')(assetBioma), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO')); } var geeClassLayer = new L.TileLayer.GeeScript(function(callback) { var assetTileUrl = assetServiceCol21_Consolidate .getConsolidateByBiomaYear(assetBioma, assetAno); callback(assetTileUrl); }); wgis.addLayer(geeClassLayer, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO') + "+>" + $filter('translate')(assetBioma), false); var DtreeClassesConsol = angular.copy($injector.get('DtreeClasses').getClasses("3")); DtreeClassesConsol.push({ id: 28, cod: "3.2.3.", classe: $filter('translate')('MOSAICODECULTIVOS'), color: "#CE3D3D" }) angular.forEach(DtreeClassesConsol, function(classedtree) { var id = classedtree.id var nameclass = classedtree.classe var icon = legends_icons_col21[id] wgis.addNodeLabel(nameclass, $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('CONSOLIDADOCLASSIFICACAO') + "+>" + $filter('translate')(assetBioma) + "+>" + assetAno, icon ); }); }); }); // dados transversais em 2.1 // floresta plantada wgis.addNodeLabel($filter('translate')('FLORESTAPLANTADA'), $filter('translate')('COLECAO') + " 2.1"); var transvFloPlantadaYears = { 2000: 2001, 2001: 2001, 2002: 2001, 2003: 2001, 2004: 2001, 2005: 2006, 2006: 2006, 2007: 2006, 2008: 2006, 2009: 2006, 2010: 2011, 2011: 2011, 2012: 2011, 2013: 2011, 2014: 2015, 2015: 2015, 2016: 2015, } angular.forEach(anos, function(assetAno, anoIndex) { var geeTransvFloPlantada = new L.TileLayer.GeeScript(function(callback) { var imc = ee.ImageCollection("projects/mapbiomas-workspace/TRANSVERSAIS/FLORESTAPLANTADA"); var img = ee.Image(imc.filterMetadata("year", "equals", transvFloPlantadaYears[assetAno]).first()); var imgmask = img.mask(img.gt(0)); var mapid = imgmask.getMap({ "palette": "#05fc46" }); assetTileUrl = 'https://earthengine.googleapis.com/map/' + mapid.mapid + '/{z}/{x}/{y}?token=' + mapid.token; callback(assetTileUrl); }); wgis.addLayer(geeTransvFloPlantada, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('FLORESTAPLANTADA'), false); }); // agricultura wgis.addNodeLabel($filter('translate')('AGRICULTURA'), $filter('translate')('COLECAO') + " 2.1"); angular.forEach(anos, function(assetAno, anoIndex) { var geeTransvAgricultura = new L.TileLayer.GeeScript(function(callback) { var imc = ee.ImageCollection("projects/mapbiomas-workspace/TRANSVERSAIS/AGRICULTURA"); var img = ee.Image(imc.filterMetadata("year", "equals", assetAno).first()); var imgmask = img.mask(img.gt(0)); var mapid = imgmask.getMap({ "palette": "#e008b8" }); assetTileUrl = 'https://earthengine.googleapis.com/map/' + mapid.mapid + '/{z}/{x}/{y}?token=' + mapid.token; callback(assetTileUrl); }); wgis.addLayer(geeTransvAgricultura, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('AGRICULTURA'), false); }); // pecuaria wgis.addNodeLabel($filter('translate')('PASTAGEM'), $filter('translate')('COLECAO') + " 2.1"); angular.forEach(anos, function(assetAno, anoIndex) { var geeTransvPecuaria = new L.TileLayer.GeeScript(function(callback) { var imc = ee.ImageCollection("projects/mapbiomas-workspace/TRANSVERSAIS/PECUARIA"); var img = ee.Image(imc.filterMetadata("year", "equals", assetAno).first()); var imgmask = img.mask(img.gt(0)); var mapid = imgmask.getMap({ "palette": "#e88000" }); assetTileUrl = 'https://earthengine.googleapis.com/map/' + mapid.mapid + '/{z}/{x}/{y}?token=' + mapid.token; callback(assetTileUrl); }); wgis.addLayer(geeTransvPecuaria, String(assetAno), $filter('translate')('COLECAO') + " 2.1+>" + $filter('translate')('PASTAGEM'), false); }); /* * Base Layer */ wgis.addNodeLabel("Raster layers"); wgis.addLayerTile({ url: "https://tile-{s}.urthecast.com/v1/rgb/{z}/{x}/{y}?api_key={api_key}&api_secret={api_secret}&sensor_platform={sensor_platform}&cloud_coverage_lte={cloud_coverage_lte}&acquired_gte={acquired_gte}&acquired_lte={acquired_lte}", params: { api_key: "<INSERT API_KEY HERE>", api_secret: "<INSERT API_SECRET HERE>", sensor_platform: "theia", cloud_coverage_lte: "50", acquired_gte: "2015-01-01T03:00:00.000Z", acquired_lte: "2016-01-01T02:59:59.999Z" } }, "Urthecast - sensor Theia", "Raster layers", false); /* * Mapas de Referencia */ wgis.addNodeLabel($filter('translate')('MAPAREFERENCIA')); //CAMADAS VETORIAIS wgis.addNodeLabel("Vectors", $filter('translate')('MAPAREFERENCIA')); //biomas 1:5000000 wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/territories/bioma.map", color_id: 2, layers: 'bioma', format: 'image/png', transparent: true } }, "Biomes 1:5.000.000", $filter('translate')('MAPAREFERENCIA') + "+>Vectors", false); //biomas 1:1000000 wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/regioes_1_1000000.map", color_id: 2, layers: 'regioes_1_1000000', format: 'image/png', transparent: true } }, "Biomes 1:1.000.000", $filter('translate')('MAPAREFERENCIA') + "+>Vectors", false); //areas protegidas wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/areas_protegidas.map", color_id: 2, layers: 'areasprotegidas', format: 'image/png', transparent: true } }, $filter('translate')('AREASPROTEGIDAS'), $filter('translate')('MAPAREFERENCIA') + "+>Vectors", false); /** * GLOBAL SURFACE WATER */ var geeSurfaceWaterLayer = new L.TileLayer.GeeScript(function(callback) { // var boundary = ee.FeatureCollection('ft:1-yEW8F5gVnjWwcKJ_-iWIFZoPaW0YXmxf4gScDVw'); var gsw = ee.Image('JRC/GSW1_0/GlobalSurfaceWater'); var occurrence = gsw.select('occurrence'); var vis = { min:0, max:100, palette: ['red', 'blue'] }; // occurrence = occurrence.updateMask(occurrence.divide(100)).clip(boundary) var mapid = occurrence.getMap(vis); assetTileUrl = 'https://earthengine.googleapis.com/map/' + mapid.mapid + '/{z}/{x}/{y}?token=' + mapid.token; callback(assetTileUrl); }); wgis.addLayer(geeSurfaceWaterLayer, "Global Surface Water", $filter('translate')("MAPAREFERENCIA"), false); // Amazônia > TerraClass wgis.addNodeLabel($filter('translate')('AMAZONIA'), $filter('translate')('MAPAREFERENCIA')); var prodesClasses = {}; prodesClasses[$filter('translate')('FLORESTA')] = { "icon": "img/legendas/forest.png", "collection": "FLORESTA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014"] }; prodesClasses[$filter('translate')('NAOFLORESTA')] = { "icon": "img/legendas/nonforest_pink.png", "collection": "NAOFLORESTA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014"] }; prodesClasses[$filter('translate')('AGUA')] = { "icon": "img/legendas/water.png", "collection": "AGUA", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014"] }; prodesClasses[$filter('translate')('NUVEM')] = { "icon": "img/legendas/cloud.png", "collection": "NUVEM", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014"] }; prodesClasses[$filter('translate')('DESMATAMENTO')] = { "icon": "img/legendas/deforestation.png", "collection": "DESMATAMENTO", "anos": ["2008", "2009", "2010", "2011", "2012", "2013", "2014"] }; angular.forEach(prodesClasses, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/prodes.map", layers: 'prodes', year: ano, class_forest: subclassName === $filter('translate')('FLORESTA'), class_nonforest: subclassName === $filter('translate')('NAOFLORESTA'), class_water: subclassName === $filter('translate')('AGUA'), class_cloud: subclassName === $filter('translate')('NUVEM'), class_deforestation: subclassName === $filter('translate')('DESMATAMENTO'), format: 'image/png', transparent: true } }, subclassName, $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('AMAZONIA') + "+>Prodes+>" + ano, false, subclass.icon); }); }); var terraclasseClasses = {}; terraclasseClasses[$filter('translate')('FLORESTA')] = { "icon": "img/legendas/forest.png", "collection": "FLORESTA", "anos": ["2008"] }; terraclasseClasses[$filter('translate')('NAOFLORESTA')] = { "icon": "img/legendas/nonforest_pink.png", "collection": "NAOFLORESTA", "anos": ["2008"] }; terraclasseClasses[$filter('translate')('AGUA')] = { "icon": "img/legendas/water.png", "collection": "AGUA", "anos": ["2008"] }; terraclasseClasses[$filter('translate')('NUVEM')] = { "icon": "img/legendas/cloud.png", "collection": "NUVEM", "anos": ["2008"] }; terraclasseClasses[$filter('translate')('DESMATAMENTO')] = { "icon": "img/legendas/deforestation.png", "collection": "DESMATAMENTO", "anos": ["2008"] }; angular.forEach(terraclasseClasses, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/terraclass.map", layers: 'terraclass', class_forest: subclassName === $filter('translate')('FLORESTA'), class_nonforest: subclassName === $filter('translate')('NAOFLORESTA'), class_water: subclassName === $filter('translate')('AGUA'), class_cloud: subclassName === $filter('translate')('NUVEM'), class_deforestation: subclassName === $filter('translate')('DESMATAMENTO'), format: 'image/png', transparent: true } }, subclassName, $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('AMAZONIA') + "+>Terraclass", false, subclass.icon); }); }); //CERRADO wgis.addNodeLabel($filter('translate')('CERRADO'), $filter('translate')('MAPAREFERENCIA')); var cerradoClasses = {}; cerradoClasses[$filter('translate')('FLORESTADENSA')] = { "icon": "img/legendas/tccerrado_floresta_densa.png", "collection": "FLORESTADENSA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('FLORESTAABERTA')] = { "icon": "img/legendas/tccerrado_floresta_aberta.png", "collection": "FLORESTAABERTA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('CORPOSDAGUA')] = { "icon": "img/legendas/tccerrado_corposdagua.png", "collection": "CORPOSDAGUA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('FORMACOESNATURAISNAOFLORESTAIS')] = { "icon": "img/legendas/tccerrado_natural_naoflorestal.png", "collection": "FORMACOESNATURAISNAOFLORESTAIS", "anos": ["2013"] }; cerradoClasses[$filter('translate')('AREASNAOVEGETADASNATURAIS')] = { "icon": "img/legendas/tccerrado_natural_naovegetado.png", "collection": "AREASNAOVEGETADASNATURAIS", "anos": ["2013"] }; cerradoClasses[$filter('translate')('SILVICULTURA')] = { "icon": "img/legendas/tccerrado_silvicultura.png", "collection": "SILVICULTURA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('AGRICULTURA')] = { "icon": "img/legendas/tccerrado_agricultura.png", "collection": "AGRICULTURA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('PASTAGEM')] = { "icon": "img/legendas/tccerrado_pastagem.png", "collection": "PASTAGEM", "anos": ["2013"] }; cerradoClasses[$filter('translate')('MOSAICOOCUPACOES')] = { "icon": "img/legendas/tccerrado_mosaico_ocupacoes.png", "collection": "MOSAICOOCUPACOES", "anos": ["2013"] }; cerradoClasses[$filter('translate')('AREASNAOVEGETADAS')] = { "icon": "img/legendas/tccerrado_area_naovegetada.png", "collection": "AREASNAOVEGETADAS", "anos": ["2013"] }; cerradoClasses[$filter('translate')('AREAURBANA')] = { "icon": "img/legendas/tccerrado_area_urbana.png", "collection": "AREAURBANA", "anos": ["2013"] }; cerradoClasses[$filter('translate')('OUTROS')] = { "icon": "img/legendas/tccerrado_outros.png", "collection": "OUTROS", "anos": ["2013"] }; cerradoClasses[$filter('translate')('NAOOBSERVADO')] = { "icon": "img/legendas/tccerrado_naoobservado.png", "collection": "NAOOBSERVADO", "anos": ["2013"] }; angular.forEach(cerradoClasses, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/cerrado.map", layers: 'cerrado', year: ano, florestadensa: subclassName === $filter('translate')('FLORESTADENSA'), florestaaberta: subclassName === $filter('translate')('FLORESTAABERTA'), corposdagua: subclassName === $filter('translate')('CORPOSDAGUA'), naturalnaoflorestal: subclassName === $filter('translate')('FORMACOESNATURAISNAOFLORESTAIS'), naturalnaovegetado: subclassName === $filter('translate')('AREASNAOVEGETADASNATURAIS'), silvicultura: subclassName === $filter('translate')('SILVICULTURA'), agricultura: subclassName === $filter('translate')('AGRICULTURA'), pastagem: subclassName === $filter('translate')('PASTAGEM'), mosaicoocupacoes: subclassName === $filter('translate')('MOSAICOOCUPACOES'), areanaovegetada: subclassName === $filter('translate')('AREASNAOVEGETADAS'), areaurbana: subclassName === $filter('translate')('AREAURBANA'), outros: subclassName === $filter('translate')('OUTROS'), naoobservado: subclassName === $filter('translate')('NAOOBSERVADO'), format: 'image/png', transparent: true } }, subclassName, $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('CERRADO') + "+>TerraClass+>" + ano, false, subclass.icon); }); }); //PAMPA wgis.addNodeLabel($filter('translate')('PAMPA'), $filter('translate')('MAPAREFERENCIA')); var pampaClasses = {}; pampaClasses[$filter('translate')('FLORESTA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_floresta.png", "collection": "FLORESTA", "anos": ["2002", "2009"], "class_id": 1 }; pampaClasses[$filter('translate')('FORMACOESFLORESTAISNATURAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_formacoesflorestaisnaturais.png", "collection": "FORMACOESFLORESTAISNATURAIS", "anos": ["2002", "2009"], "class_id": 2 }; pampaClasses[$filter('translate')('FLORESTADENSA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_florestadensa.png", "collection": "FLORESTADENSA", "anos": ["2002", "2009"], "class_id": 3 }; pampaClasses[$filter('translate')('FLORESTAABERTA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_florestaaberta.png", "collection": "FLORESTAABERTA", "anos": ["2002", "2009"], "class_id": 4 }; pampaClasses[$filter('translate')('MANGUE')] = { "icon": "img/legendas/mapbiomas/mapbiomas_mangue.png", "collection": "MANGUE", "anos": ["2002", "2009"], "class_id": 5 }; pampaClasses[$filter('translate')('FLORESTAALAGADA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_florestaalagada.png", "collection": "FLORESTAALAGADA", "anos": ["2002", "2009"], "class_id": 6 }; pampaClasses[$filter('translate')('FLORESTADEGRADADA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_florestadegradada.png", "collection": "FLORESTADEGRADADA", "anos": ["2002", "2009"], "class_id": 7 }; pampaClasses[$filter('translate')('FLORESTASECUNDARIA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_florestasecundaria.png", "collection": "FLORESTASECUNDARIA", "anos": ["2002", "2009"], "class_id": 8 }; pampaClasses[$filter('translate')('SILVICULTURA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_silvicutura.png", "collection": "SILVICULTURA", "anos": ["2002", "2009"], "class_id": 9 }; pampaClasses[$filter('translate')('FORMACOESNATURAISNAOFLORESTAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_formacoesnaturaisnaoflorestais.png", "collection": "FORMACOESNATURAISNAOFLORESTAIS", "anos": ["2002", "2009"], "class_id": 10 }; pampaClasses[$filter('translate')('AREASUMIDASNATURAISNAOFLORESTAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_areasumidasnaturaisnaoflorestais.png", "collection": "AREASUMIDASNATURAISNAOFLORESTAIS", "anos": ["2002", "2009"], "class_id": 11 }; pampaClasses[$filter('translate')('VEGETACAOCAMPESTRE')] = { "icon": "img/legendas/mapbiomas/mapbiomas_vegetacaocampestre.png", "collection": "VEGETACAOCAMPESTRE", "anos": ["2002", "2009"], "class_id": 12 }; pampaClasses[$filter('translate')('OUTRASFORMACOESNAOFLORESTAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_outrasformacoesnaoflorestais.png", "collection": "OUTRASFORMACOESNAOFLORESTAIS", "anos": ["2002", "2009"], "class_id": 13 }; pampaClasses[$filter('translate')('USOAGROPECUARIO')] = { "icon": "img/legendas/mapbiomas/mapbiomas_usoagropecuario.png", "collection": "USOAGROPECUARIO", "anos": ["2002", "2009"], "class_id": 14 }; pampaClasses[$filter('translate')('PASTAGEM')] = { "icon": "img/legendas/mapbiomas/mapbiomas_pastagem.png", "collection": "PASTAGEM", "anos": ["2002", "2009"], "class_id": 15 }; pampaClasses[$filter('translate')('PASTAGEMEMCAMPOSNATURAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_pastagememcamposnaturais.png", "collection": "PASTAGEMEMCAMPOSNATURAIS", "anos": ["2002", "2009"], "class_id": 16 }; pampaClasses[$filter('translate')('OUTRASPASTAGENS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_outraspastagens.png", "collection": "OUTRASPASTAGENS", "anos": ["2002", "2009"], "class_id": 17 }; pampaClasses[$filter('translate')('AGRICULTURA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_agricultura.png", "collection": "AGRICULTURA", "anos": ["2002", "2009"], "class_id": 18 }; pampaClasses[$filter('translate')('CULTURASANUAIS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_culturasanuais.png", "collection": "CULTURASANUAIS", "anos": ["2002", "2009"], "class_id": 19 }; pampaClasses[$filter('translate')('CULTURASSEMIPERENE')] = { "icon": "img/legendas/mapbiomas/mapbiomas_culturassemiperenes.png", "collection": "CULTURASSEMIPERENE", "anos": ["2002", "2009"], "class_id": 20 }; pampaClasses[$filter('translate')('AGRICULTURAOUPASTAGEM')] = { "icon": "img/legendas/mapbiomas/mapbiomas_agriculturaoupastagem.png", "collection": "AGRICULTURAOUPASTAGEM", "anos": ["2002", "2009"], "class_id": 21 }; pampaClasses[$filter('translate')('AREASNAOVEGETADAS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_areasnaovegetadas.png", "collection": "AREASNAOVEGETADAS", "anos": ["2002", "2009"], "class_id": 22 }; pampaClasses[$filter('translate')('PRAIASEDUNAS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_praiasedunas.png", "collection": "PRAIASEDUNAS", "anos": ["2002", "2009"], "class_id": 23 }; pampaClasses[$filter('translate')('AREASURBANAS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_infraestruturasurbana.png", "collection": "AREASURBANAS", "anos": ["2002", "2009"], "class_id": 24 }; pampaClasses[$filter('translate')('OUTRASAREASNAOVEGETADAS')] = { "icon": "img/legendas/mapbiomas/mapbiomas_outrasareasnaovegetadas.png", "collection": "OUTRASAREASNAOVEGETADAS", "anos": ["2002", "2009"], "class_id": 25 }; pampaClasses[$filter('translate')('CORPOSDAGUA')] = { "icon": "img/legendas/mapbiomas/mapbiomas_corposdagua.png", "collection": "CORPOSDAGUA", "anos": ["2002", "2009"], "class_id": 26 }; pampaClasses[$filter('translate')('NAOOBSERVADO')] = { "icon": "img/legendas/mapbiomas/mapbiomas_naoobservado.png", "collection": "NAOOBSERVADO", "anos": ["2002", "2009"], "class_id": 27 }; wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/pampa.map", classes_ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27], layers: 'pampa', year: "2002", format: 'image/png', transparent: true } }, "2002", $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('PAMPA'), false); wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/pampa.map", classes_ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27], layers: 'pampa', year: "2009", format: 'image/png', transparent: true } }, "2009", $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('PAMPA'), false); angular.forEach(pampaClasses, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addNodeLabel(subclassName, $filter('translate')('MAPAREFERENCIA') + "+>" + $filter('translate')('PAMPA') + "+>" + ano, subclass.icon ); }) }); var mapreferenceClass = {}; mapreferenceClass[$filter('translate')('CAATINGA')] = { "collection": "CAATINGA", "layer": "caatinga", "anos": ["2008"] }; mapreferenceClass[$filter('translate')('MATAATLANTICA')] = { "collection": "MATAATLANTICA", "layer": "mataatlantica", "anos": ["2008"] }; mapreferenceClass[$filter('translate')('PANTANAL')] = { "collection": "PANTANAL", "layer": "pantanal", "anos": ["2008"] }; mapreferenceClass[$filter('translate')('ZONACOSTEIRA')] = { "collection": "ZONACOSTEIRA", "layer": "zonacosteira", "anos": ["2008"] }; angular.forEach(mapreferenceClass, function(subclass, subclassName) { angular.forEach(subclass.anos, function(ano, anoKey) { wgis.addLayerWMS({ url: mapfilehost, params: { map: mapfilepath + "/imgsref/" + subclass.layer + ".map", layers: subclass.layer, format: 'image/png', transparent: true } }, subclassName, $filter('translate')('MAPAREFERENCIA'), false, null); }); }); }, cartasInfo: function(wgis) { L.geoJson(cartas, { style: function(feature) { return { color: feature.properties.color }; }, onEachFeature: function(feature, layer) { layer.bindPopup(feature.properties.description); } }).addTo(wgis._wgis.lmap); } }; } ]);
{ "content_hash": "c6e4911e2260610fb3cdc29e0a974916", "timestamp": "", "source": "github", "line_count": 1510, "max_line_length": 249, "avg_line_length": 47.274172185430466, "alnum_prop": 0.43789924913145806, "repo_name": "TerrasAppSolutions/seeg-mapbiomas-workspace", "id": "0516e2adc0322e20a5df14d572429e2f706581cf", "size": "71402", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "app/webroot/js/app/modules/workmap/layers/workmap.layers.brasil.js", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "2980" }, { "name": "CSS", "bytes": "67586" }, { "name": "Dockerfile", "bytes": "2507" }, { "name": "HTML", "bytes": "238878" }, { "name": "JavaScript", "bytes": "2182379" }, { "name": "PHP", "bytes": "8418950" }, { "name": "Python", "bytes": "3165" }, { "name": "Shell", "bytes": "8648" }, { "name": "TSQL", "bytes": "42857" } ], "symlink_target": "" }
/* * $Id$ */ // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include <xercesc/util/BinMemInputStream.hpp> #include <xercesc/framework/MemoryManager.hpp> #include <string.h> XERCES_CPP_NAMESPACE_BEGIN // --------------------------------------------------------------------------- // BinMemInputStream: Constructors and Destructor // --------------------------------------------------------------------------- BinMemInputStream::BinMemInputStream( const XMLByte* const initData , const XMLSize_t capacity , const BufOpts bufOpt , MemoryManager* const manager) : fBuffer(0) , fBufOpt(bufOpt) , fCapacity(capacity) , fCurIndex(0) , fMemoryManager(manager) { // According to the buffer option, do the right thing if (fBufOpt == BufOpt_Copy) { XMLByte* tmpBuf = (XMLByte*) fMemoryManager->allocate ( fCapacity * sizeof(XMLByte) );//new XMLByte[fCapacity]; memcpy(tmpBuf, initData, capacity); fBuffer = tmpBuf; } else { fBuffer = initData; } } BinMemInputStream::~BinMemInputStream() { // // If we adopted or copied the buffer, then clean it up. We have to // cast off the const'ness in that case in order to delete it. // if ((fBufOpt == BufOpt_Adopt) || (fBufOpt == BufOpt_Copy)) fMemoryManager->deallocate(const_cast<XMLByte*>(fBuffer));//delete [] (XMLByte*)fBuffer; } // --------------------------------------------------------------------------- // MemBinInputStream: Implementation of the input stream interface // --------------------------------------------------------------------------- XMLSize_t BinMemInputStream::readBytes( XMLByte* const toFill , const XMLSize_t maxToRead) { // // Figure out how much we can really read. Its the smaller of the // amount available and the amount asked for. // const XMLSize_t available = (fCapacity - fCurIndex); if (!available) return 0; const XMLSize_t actualToRead = available < maxToRead ? available : maxToRead; memcpy(toFill, &fBuffer[fCurIndex], actualToRead); fCurIndex += actualToRead; return actualToRead; } const XMLCh* BinMemInputStream::getContentType() const { return 0; } XERCES_CPP_NAMESPACE_END
{ "content_hash": "bef2fe27a86377427648d7c277143899", "timestamp": "", "source": "github", "line_count": 83, "max_line_length": 96, "avg_line_length": 31.120481927710845, "alnum_prop": 0.49554781262098335, "repo_name": "ctapmex/xerces-c", "id": "5ebdf9936ead343590b242466f5a99f8ea1bb28c", "size": "3385", "binary": false, "copies": "2", "ref": "refs/heads/colorer-xerces", "path": "src/xercesc/util/BinMemInputStream.cpp", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "701" }, { "name": "C", "bytes": "205856" }, { "name": "C++", "bytes": "10883660" }, { "name": "CMake", "bytes": "75166" }, { "name": "Makefile", "bytes": "192161" }, { "name": "Perl", "bytes": "19946" }, { "name": "Shell", "bytes": "1854" } ], "symlink_target": "" }
'use strict'; define(['app'], function(app) { app.config(['$stateProvider', function($stateProvider) { $stateProvider .state("products", { url: "/:locale/products/", templateUrl: '/app/Aisel/Product/views/product.html', controller: 'ProductCtrl' }) .state("productView", { url: "/:locale/product/view/:productId/", templateUrl: '/app/Aisel/Product/views/product-detail.html', controller: 'ProductDetailCtrl' }) .state("productCategories", { url: "/:locale/product/categories/", templateUrl: '/app/Aisel/Product/views/category.html', controller: 'ProductCategoryCtrl' }) .state("productCategoryView", { url: "/:locale/product/category/:categoryId/", templateUrl: '/app/Aisel/Product/views/category-detail.html', controller: 'ProductCategoryDetailCtrl' }); }]); });
{ "content_hash": "bb43a2c891a62fbd5da13a43e3969050", "timestamp": "", "source": "github", "line_count": 29, "max_line_length": 77, "avg_line_length": 36.93103448275862, "alnum_prop": 0.5228758169934641, "repo_name": "kamilkisiela/Aisel", "id": "1af3ddfde8c86220a8525d83beac8fba8a60abe2", "size": "1350", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "frontend/web/app/Aisel/Product/config/product.js", "mode": "33188", "license": "mit", "language": [ { "name": "ApacheConf", "bytes": "600" }, { "name": "CSS", "bytes": "16382" }, { "name": "HTML", "bytes": "139777" }, { "name": "JavaScript", "bytes": "192240" }, { "name": "PHP", "bytes": "491082" }, { "name": "Shell", "bytes": "225" } ], "symlink_target": "" }
#ifndef __ATOMIC_H__ #define __ATOMIC_H__ /* * Warning: These are not really atomic at all. They are wrappers around the * kernel atomic variable interface. If we do need these variables to be atomic * (due to multithreading of the code that uses them) we need to add some * pthreads magic here. */ typedef int32_t atomic_t; typedef int64_t atomic64_t; #define atomic_inc_return(x) (++(*(x))) #define atomic_dec_return(x) (--(*(x))) #define atomic64_read(x) *(x) #define atomic64_set(x, v) (*(x) = v) #endif /* __ATOMIC_H__ */
{ "content_hash": "90854878069d97c184f613450dce5dd6", "timestamp": "", "source": "github", "line_count": 21, "max_line_length": 79, "avg_line_length": 25.61904761904762, "alnum_prop": 0.671003717472119, "repo_name": "calee0219/Course", "id": "151c5bf71c3d2236acace0b83aadb9cc9da37ab7", "size": "1244", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "SAP/hw2/partclone-0.2.89/src/xfs/atomic.h", "mode": "33188", "license": "mit", "language": [ { "name": "Assembly", "bytes": "2289" }, { "name": "Batchfile", "bytes": "15462" }, { "name": "C", "bytes": "3743223" }, { "name": "C++", "bytes": "5215847" }, { "name": "CMake", "bytes": "58587" }, { "name": "CSS", "bytes": "3594" }, { "name": "Coq", "bytes": "17175" }, { "name": "Forth", "bytes": "476" }, { "name": "HTML", "bytes": "1179412" }, { "name": "Jupyter Notebook", "bytes": "3982275" }, { "name": "Lex", "bytes": "13550" }, { "name": "M4", "bytes": "91072" }, { "name": "Makefile", "bytes": "502535" }, { "name": "OpenEdge ABL", "bytes": "8142" }, { "name": "Perl", "bytes": "4976" }, { "name": "Python", "bytes": "40779" }, { "name": "Roff", "bytes": "48176" }, { "name": "Shell", "bytes": "117131" }, { "name": "Tcl", "bytes": "49089" }, { "name": "TeX", "bytes": "1847" }, { "name": "TypeScript", "bytes": "8296" }, { "name": "Verilog", "bytes": "1306446" }, { "name": "XSLT", "bytes": "1477" } ], "symlink_target": "" }
@class JavaUtilHashMap; @protocol AMLocaleProvider < NSObject, JavaObject > - (JavaUtilHashMap *)loadLocale; - (jboolean)is24Hours; @end J2OBJC_EMPTY_STATIC_INIT(AMLocaleProvider) J2OBJC_TYPE_LITERAL_HEADER(AMLocaleProvider) #define ImActorModelLocaleProvider AMLocaleProvider #endif // _AMLocaleProvider_H_
{ "content_hash": "444e47cd77c53080969c6f6be8feac74", "timestamp": "", "source": "github", "line_count": 17, "max_line_length": 51, "avg_line_length": 18.58823529411765, "alnum_prop": 0.8006329113924051, "repo_name": "TimurTarasenko/actor-platform", "id": "b05e525c3e4b6e05f4ad07631d240c01d8de3a45", "size": "578", "binary": false, "copies": "13", "ref": "refs/heads/master", "path": "actor-apps/core-async-cocoa/src/im/actor/model/LocaleProvider.h", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "48086" }, { "name": "HTML", "bytes": "2084" }, { "name": "Java", "bytes": "4085955" }, { "name": "JavaScript", "bytes": "141061" }, { "name": "Objective-C", "bytes": "6115908" }, { "name": "Ruby", "bytes": "2670" }, { "name": "Scala", "bytes": "902029" }, { "name": "Shell", "bytes": "9522" }, { "name": "Swift", "bytes": "503432" } ], "symlink_target": "" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Xamarin.Forms; namespace IconEntrySample { public partial class App : Application { public App() { InitializeComponent(); MainPage = new IconEntrySample.MainPage(); } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
{ "content_hash": "dd7b7f015c2625c8d7770c13f6448bdd", "timestamp": "", "source": "github", "line_count": 34, "max_line_length": 54, "avg_line_length": 19.029411764705884, "alnum_prop": 0.5564142194744977, "repo_name": "Li-Yanzhi/IconEntry", "id": "c700aaa196ba7ce376d7e47523a1da6860f2fda0", "size": "649", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "samples/IconEntrySample/App.xaml.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "205" }, { "name": "C#", "bytes": "12138" } ], "symlink_target": "" }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>statsmodels.genmod.generalized_estimating_equations.GEEResults.resid &#8212; statsmodels v0.10.1 documentation</title> <link rel="stylesheet" href="../_static/nature.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" /> <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <script type="text/javascript" src="../_static/language_data.js"></script> <script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-AMS-MML_HTMLorMML"></script> <link rel="shortcut icon" href="../_static/statsmodels_hybi_favico.ico"/> <link rel="author" title="About these documents" href="../about.html" /> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="next" title="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered" href="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered.html" /> <link rel="prev" title="statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data" href="statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data.html" /> <link rel="stylesheet" href="../_static/examples.css" type="text/css" /> <link rel="stylesheet" href="../_static/facebox.css" type="text/css" /> <script type="text/javascript" src="../_static/scripts.js"> </script> <script type="text/javascript" src="../_static/facebox.js"> </script> <script type="text/javascript"> $.facebox.settings.closeImage = "../_static/closelabel.png" $.facebox.settings.loadingImage = "../_static/loading.gif" </script> <script> $(document).ready(function() { $.getJSON("../../versions.json", function(versions) { var dropdown = document.createElement("div"); dropdown.className = "dropdown"; var button = document.createElement("button"); button.className = "dropbtn"; button.innerHTML = "Other Versions"; var content = document.createElement("div"); content.className = "dropdown-content"; dropdown.appendChild(button); dropdown.appendChild(content); $(".header").prepend(dropdown); for (var i = 0; i < versions.length; i++) { if (versions[i].substring(0, 1) == "v") { versions[i] = [versions[i], versions[i].substring(1)]; } else { versions[i] = [versions[i], versions[i]]; }; }; for (var i = 0; i < versions.length; i++) { var a = document.createElement("a"); a.innerHTML = versions[i][1]; a.href = "../../" + versions[i][0] + "/index.html"; a.title = versions[i][1]; $(".dropdown-content").append(a); }; }); }); </script> </head><body> <div class="headerwrap"> <div class = "header"> <a href = "../index.html"> <img src="../_static/statsmodels_hybi_banner.png" alt="Logo" style="padding-left: 15px"/></a> </div> </div> <div class="related" role="navigation" aria-label="related navigation"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li class="right" > <a href="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered.html" title="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered" accesskey="N">next</a> |</li> <li class="right" > <a href="statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data.html" title="statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data" accesskey="P">previous</a> |</li> <li><a href ="../install.html">Install</a></li> &nbsp;|&nbsp; <li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> &nbsp;|&nbsp; <li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> &nbsp;|&nbsp; <li><a href="../dev/index.html">Develop</a></li> &nbsp;|&nbsp; <li><a href="../examples/index.html">Examples</a></li> &nbsp;|&nbsp; <li><a href="../faq.html">FAQ</a></li> &nbsp;|&nbsp; <li class="nav-item nav-item-1"><a href="../gee.html" >Generalized Estimating Equations</a> |</li> <li class="nav-item nav-item-2"><a href="statsmodels.genmod.generalized_estimating_equations.GEEResults.html" accesskey="U">statsmodels.genmod.generalized_estimating_equations.GEEResults</a> |</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body" role="main"> <div class="section" id="statsmodels-genmod-generalized-estimating-equations-geeresults-resid"> <h1>statsmodels.genmod.generalized_estimating_equations.GEEResults.resid<a class="headerlink" href="#statsmodels-genmod-generalized-estimating-equations-geeresults-resid" title="Permalink to this headline">¶</a></h1> <p>method</p> <dl class="method"> <dt id="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid"> <code class="sig-prename descclassname">GEEResults.</code><code class="sig-name descname">resid</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/genmod/generalized_estimating_equations.html#GEEResults.resid"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#statsmodels.genmod.generalized_estimating_equations.GEEResults.resid" title="Permalink to this definition">¶</a></dt> <dd><p>Returns the residuals, the endogeneous data minus the fitted values from the model.</p> </dd></dl> </div> </div> </div> </div> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h4>Previous topic</h4> <p class="topless"><a href="statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data.html" title="previous chapter">statsmodels.genmod.generalized_estimating_equations.GEEResults.remove_data</a></p> <h4>Next topic</h4> <p class="topless"><a href="statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered.html" title="next chapter">statsmodels.genmod.generalized_estimating_equations.GEEResults.resid_centered</a></p> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/generated/statsmodels.genmod.generalized_estimating_equations.GEEResults.resid.rst.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3 id="searchlabel">Quick search</h3> <div class="searchformwrapper"> <form class="search" action="../search.html" method="get"> <input type="text" name="q" aria-labelledby="searchlabel" /> <input type="submit" value="Go" /> </form> </div> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="footer" role="contentinfo"> &#169; Copyright 2009-2018, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers. Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2. </div> </body> </html>
{ "content_hash": "02ab7c522361468c27c90207d49519aa", "timestamp": "", "source": "github", "line_count": 165, "max_line_length": 482, "avg_line_length": 48.78787878787879, "alnum_prop": 0.6611180124223602, "repo_name": "statsmodels/statsmodels.github.io", "id": "bbea6220f7c715f710564209ebb76d29127ae84d", "size": "8054", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "v0.10.1/generated/statsmodels.genmod.generalized_estimating_equations.GEEResults.resid.html", "mode": "33188", "license": "bsd-3-clause", "language": [], "symlink_target": "" }
package cn.lhfei.airqa.service; import java.util.List; import cn.lhfei.airqa.entity.Region; public interface IRegionService { List<Region> findRegion(int level,int pid); }
{ "content_hash": "b32926bde0e1422e33e62b0a3b691ff6", "timestamp": "", "source": "github", "line_count": 10, "max_line_length": 44, "avg_line_length": 18.7, "alnum_prop": 0.732620320855615, "repo_name": "lhfei/air-qa-back-end", "id": "8259170ea9eb5c5c32b629ed867440df4f1fbe45", "size": "187", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/cn/lhfei/airqa/service/IRegionService.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "433459" }, { "name": "Java", "bytes": "83511" }, { "name": "JavaScript", "bytes": "348712" } ], "symlink_target": "" }
package org.apache.hadoop.hbase.master; import org.apache.hadoop.hbase.HBaseClassTestRule; import org.apache.hadoop.hbase.testclassification.MasterTests; import org.apache.hadoop.hbase.testclassification.MediumTests; import org.junit.ClassRule; import org.junit.experimental.categories.Category; @Category({ MasterTests.class, MediumTests.class }) public class TestRoundRobinAssignmentOnRestartSplitWithoutZk extends TestRoundRobinAssignmentOnRestart { @ClassRule public static final HBaseClassTestRule CLASS_RULE = HBaseClassTestRule.forClass(TestRoundRobinAssignmentOnRestartSplitWithoutZk.class); @Override protected boolean splitWALCoordinatedByZk() { return false; } }
{ "content_hash": "bfac3ee9b20c76fc301d3f5367516181", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 31.772727272727273, "alnum_prop": 0.8311874105865522, "repo_name": "HubSpot/hbase", "id": "8ea7aa3bcb49552d212f45013161a27a8f5e4e73", "size": "1504", "binary": false, "copies": "6", "ref": "refs/heads/hubspot-2.5", "path": "hbase-server/src/test/java/org/apache/hadoop/hbase/master/TestRoundRobinAssignmentOnRestartSplitWithoutZk.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "26366" }, { "name": "C", "bytes": "4041" }, { "name": "C++", "bytes": "19726" }, { "name": "CMake", "bytes": "1437" }, { "name": "CSS", "bytes": "8033" }, { "name": "Dockerfile", "bytes": "13729" }, { "name": "HTML", "bytes": "18151" }, { "name": "Java", "bytes": "40683660" }, { "name": "JavaScript", "bytes": "9455" }, { "name": "Makefile", "bytes": "1359" }, { "name": "PHP", "bytes": "8385" }, { "name": "Perl", "bytes": "383739" }, { "name": "Python", "bytes": "102210" }, { "name": "Roff", "bytes": "2896" }, { "name": "Ruby", "bytes": "766684" }, { "name": "Shell", "bytes": "312013" }, { "name": "Thrift", "bytes": "55594" }, { "name": "XSLT", "bytes": "3924" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ChangeListManager"> <list default="true" id="81e28fcf-1ca2-4a17-a68b-588ca64dc21f" name="Default" comment=""> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/README.md" afterPath="$PROJECT_DIR$/README.md" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/index.js" afterPath="$PROJECT_DIR$/index.js" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/package.json" afterPath="$PROJECT_DIR$/package.json" /> <change type="MODIFICATION" beforePath="$PROJECT_DIR$/test/test.js" afterPath="$PROJECT_DIR$/test/test.js" /> </list> <ignored path="json-schema-filter.iws" /> <ignored path=".idea/workspace.xml" /> <option name="TRACKING_ENABLED" value="true" /> <option name="SHOW_DIALOG" value="false" /> <option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" /> <option name="LAST_RESOLUTION" value="IGNORE" /> </component> <component name="ChangesViewManager" flattened_view="true" show_ignored="false" /> <component name="CreatePatchCommitExecutor"> <option name="PATCH_PATH" value="" /> </component> <component name="DaemonCodeAnalyzer"> <disable_hints /> </component> <component name="ExecutionTargetManager" SELECTED_TARGET="default_target" /> <component name="FavoritesManager"> <favorites_list name="json-schema-filter" /> </component> <component name="FileEditorManager"> <leaf> <file leaf-file-name="index.js" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/index.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="915"> <caret line="45" column="10" selection-start-line="45" selection-start-column="10" selection-end-line="45" selection-end-column="10" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="package.json" pinned="false" current="false" current-in-tab="false"> <entry file="file://$PROJECT_DIR$/package.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-6.25" vertical-offset="0" max-vertical-offset="510"> <caret line="10" column="18" selection-start-line="10" selection-start-column="18" selection-end-line="10" selection-end-column="18" /> <folding /> </state> </provider> </entry> </file> <file leaf-file-name="test.js" pinned="false" current="true" current-in-tab="true"> <entry file="file://$PROJECT_DIR$/test/test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.8380682" vertical-offset="1050" max-vertical-offset="2175"> <caret line="129" column="0" selection-start-line="129" selection-start-column="0" selection-end-line="129" selection-end-column="0" /> <folding /> </state> </provider> </entry> </file> </leaf> </component> <component name="FindManager"> <FindUsagesManager> <setting name="OPEN_NEW_TAB" value="true" /> </FindUsagesManager> </component> <component name="Git.Settings"> <option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$" /> </component> <component name="IdeDocumentHistory"> <option name="changedFiles"> <list> <option value="$PROJECT_DIR$/index.js" /> <option value="$PROJECT_DIR$/package.json" /> <option value="$PROJECT_DIR$/README.md" /> <option value="$PROJECT_DIR$/test/test.js" /> </list> </option> </component> <component name="ProjectFrameBounds"> <option name="x" value="-262" /> <option name="y" value="-1529" /> <option name="width" value="1531" /> <option name="height" value="1174" /> </component> <component name="ProjectLevelVcsManager" settingsEditedManually="false"> <OptionsSetting value="true" id="Add" /> <OptionsSetting value="true" id="Remove" /> <OptionsSetting value="true" id="Checkout" /> <OptionsSetting value="true" id="Update" /> <OptionsSetting value="true" id="Status" /> <OptionsSetting value="true" id="Edit" /> <ConfirmationsSetting value="0" id="Add" /> <ConfirmationsSetting value="0" id="Remove" /> </component> <component name="ProjectReloadState"> <option name="STATE" value="0" /> </component> <component name="ProjectView"> <navigator currentView="ProjectPane" proportions="" version="1"> <flattenPackages /> <showMembers /> <showModules /> <showLibraryContents /> <hideEmptyPackages /> <abbreviatePackageNames /> <autoscrollToSource /> <autoscrollFromSource /> <sortByType /> </navigator> <panes> <pane id="ProjectPane"> <subPane> <PATH> <PATH_ELEMENT> <option name="myItemId" value="json-schema-filter" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="json-schema-filter" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="json-schema-filter" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> <PATH> <PATH_ELEMENT> <option name="myItemId" value="json-schema-filter" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.ProjectViewProjectNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="json-schema-filter" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> <PATH_ELEMENT> <option name="myItemId" value="test" /> <option name="myItemType" value="com.intellij.ide.projectView.impl.nodes.PsiDirectoryNode" /> </PATH_ELEMENT> </PATH> </subPane> </pane> <pane id="Scope" /> </panes> </component> <component name="PropertiesComponent"> <property name="options.lastSelected" value="preferences.sourceCode.General" /> <property name="options.splitter.main.proportions" value="0.3" /> <property name="options.splitter.details.proportions" value="0.2" /> <property name="options.searchVisible" value="true" /> <property name="last_opened_file_path" value="$PROJECT_DIR$" /> <property name="WebServerToolWindowFactoryState" value="true" /> </component> <component name="RunManager"> <configuration default="true" type="DartUnitRunConfigurationType" factoryName="DartUnit"> <option name="VMOptions" /> <option name="arguments" /> <option name="filePath" /> <option name="scope" value="ALL" /> <option name="testName" /> <method /> </configuration> <configuration default="true" type="DartCommandLineRunConfigurationType" factoryName="Dart Command Line Application"> <option name="VMOptions" /> <option name="arguments" /> <option name="filePath" /> <option name="name" value="Dart" /> <option name="saveOutputToFile" value="false" /> <option name="showConsoleOnStdErr" value="false" /> <option name="showConsoleOnStdOut" value="false" /> <method /> </configuration> <configuration default="true" type="CucumberJavaScriptRunConfigurationType" factoryName="Cucumber.js"> <option name="cucumberJsArguments" /> <option name="executablePath" /> <option name="filePath" /> <method /> </configuration> <configuration default="true" type="JavaScriptTestRunnerKarma" factoryName="Karma" config-file=""> <envs /> <method /> </configuration> <configuration default="true" type="JSTestDriver:ConfigurationType" factoryName="JsTestDriver"> <setting name="configLocationType" value="CONFIG_FILE" /> <setting name="settingsFile" value="" /> <setting name="serverType" value="INTERNAL" /> <setting name="preferredDebugBrowser" value="Chrome" /> <method /> </configuration> <configuration default="true" type="JavascriptDebugType" factoryName="JavaScript Debug"> <method /> </configuration> <configuration default="true" type="NodeJSConfigurationType" factoryName="Node.js" working-dir=""> <method /> </configuration> <list size="0" /> </component> <component name="ShelveChangesManager" show_recycled="false" /> <component name="TaskManager"> <task active="true" id="Default" summary="Default task"> <changelist id="81e28fcf-1ca2-4a17-a68b-588ca64dc21f" name="Default" comment="" /> <created>1409064644038</created> <updated>1409064644038</updated> </task> <servers /> </component> <component name="ToolWindowManager"> <frame x="-262" y="-1529" width="1531" height="1174" extended-state="0" /> <editor active="true" /> <layout> <window_info id="Changes" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" /> <window_info id="Terminal" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" /> <window_info id="TODO" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="6" side_tool="false" content_ui="tabs" /> <window_info id="Structure" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Remote Host" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" /> <window_info id="Project" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="true" weight="0.24983211" sideWeight="0.5" order="0" side_tool="false" content_ui="combo" /> <window_info id="Debug" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="3" side_tool="false" content_ui="tabs" /> <window_info id="Favorites" active="false" anchor="left" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" /> <window_info id="Event Log" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="true" content_ui="tabs" /> <window_info id="Run" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="2" side_tool="false" content_ui="tabs" /> <window_info id="Version Control" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="-1" side_tool="false" content_ui="tabs" /> <window_info id="Cvs" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="4" side_tool="false" content_ui="tabs" /> <window_info id="Message" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Ant Build" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Find" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.33" sideWeight="0.5" order="1" side_tool="false" content_ui="tabs" /> <window_info id="Commander" active="false" anchor="right" auto_hide="false" internal_type="SLIDING" type="SLIDING" visible="false" weight="0.4" sideWeight="0.5" order="0" side_tool="false" content_ui="tabs" /> <window_info id="Hierarchy" active="false" anchor="right" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.25" sideWeight="0.5" order="2" side_tool="false" content_ui="combo" /> <window_info id="Inspection" active="false" anchor="bottom" auto_hide="false" internal_type="DOCKED" type="DOCKED" visible="false" weight="0.4" sideWeight="0.5" order="5" side_tool="false" content_ui="tabs" /> </layout> </component> <component name="Vcs.Log.UiProperties"> <option name="RECENTLY_FILTERED_USER_GROUPS"> <collection /> </option> <option name="RECENTLY_FILTERED_BRANCH_GROUPS"> <collection /> </option> </component> <component name="VcsContentAnnotationSettings"> <option name="myLimit" value="2678400000" /> </component> <component name="VcsManagerConfiguration"> <option name="myTodoPanelSettings"> <TodoPanelSettings /> </option> </component> <component name="XDebuggerManager"> <breakpoint-manager /> </component> <component name="editorHistoryManager"> <entry file="file://$PROJECT_DIR$/README.md"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.08840864" vertical-offset="0" max-vertical-offset="1515"> <caret line="6" column="253" selection-start-line="6" selection-start-column="253" selection-end-line="6" selection-end-column="253" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/package.json"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="-6.25" vertical-offset="0" max-vertical-offset="510"> <caret line="10" column="18" selection-start-line="10" selection-start-column="18" selection-end-line="10" selection-end-column="18" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/index.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.0" vertical-offset="0" max-vertical-offset="915"> <caret line="45" column="10" selection-start-line="45" selection-start-column="10" selection-end-line="45" selection-end-column="10" /> <folding /> </state> </provider> </entry> <entry file="file://$PROJECT_DIR$/test/test.js"> <provider selected="true" editor-type-id="text-editor"> <state vertical-scroll-proportion="0.8380682" vertical-offset="1050" max-vertical-offset="2175"> <caret line="129" column="0" selection-start-line="129" selection-start-column="0" selection-end-line="129" selection-end-column="0" /> <folding /> </state> </provider> </entry> </component> </project>
{ "content_hash": "195a3e08989805d8c03c181a9c095b68", "timestamp": "", "source": "github", "line_count": 289, "max_line_length": 222, "avg_line_length": 54.68512110726643, "alnum_prop": 0.6473677549987344, "repo_name": "alank64/json-schema-filter", "id": "18a7c8d8bf933f03ff6f116a07744c99d94e9eda", "size": "15804", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": ".idea/workspace.xml", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "7307" } ], "symlink_target": "" }
(function(){ UEDITOR_CONFIG = window.UEDITOR_CONFIG || {}; var baidu = window.baidu || {}; window.baidu = baidu; window.UE = baidu.editor = {}; UE.plugins = {}; UE.commands = {}; UE.instants = {}; UE.I18N = {}; UE.version = "1.2.6.1"; var dom = UE.dom = {};/** * @file * @name UE.browser * @short Browser * @desc UEditor中采用的浏览器判断模块 */ var browser = UE.browser = function(){ var agent = navigator.userAgent.toLowerCase(), opera = window.opera, browser = { /** * 检测浏览器是否为IE * @name ie * @grammar UE.browser.ie => true|false */ ie : !!window.ActiveXObject, /** * 检测浏览器是否为Opera * @name opera * @grammar UE.browser.opera => true|false */ opera : ( !!opera && opera.version ), /** * 检测浏览器是否为webkit内核 * @name webkit * @grammar UE.browser.webkit => true|false */ webkit : ( agent.indexOf( ' applewebkit/' ) > -1 ), /** * 检测浏览器是否为mac系统下的浏览器 * @name mac * @grammar UE.browser.mac => true|false */ mac : ( agent.indexOf( 'macintosh' ) > -1 ), /** * 检测浏览器是否处于怪异模式 * @name quirks * @grammar UE.browser.quirks => true|false */ quirks : ( document.compatMode == 'BackCompat' ) }; /** * 检测浏览器是否处为gecko内核 * @name gecko * @grammar UE.browser.gecko => true|false */ browser.gecko =( navigator.product == 'Gecko' && !browser.webkit && !browser.opera ); var version = 0; // Internet Explorer 6.0+ if ( browser.ie ){ version = parseFloat( agent.match( /msie (\d+)/ )[1] ); /** * 检测浏览器是否为 IE9 模式 * @name ie9Compat * @grammar UE.browser.ie9Compat => true|false */ browser.ie9Compat = document.documentMode == 9; /** * 检测浏览器是否为 IE8 浏览器 * @name ie8 * @grammar UE.browser.ie8 => true|false */ browser.ie8 = !!document.documentMode; /** * 检测浏览器是否为 IE8 模式 * @name ie8Compat * @grammar UE.browser.ie8Compat => true|false */ browser.ie8Compat = document.documentMode == 8; /** * 检测浏览器是否运行在 兼容IE7模式 * @name ie7Compat * @grammar UE.browser.ie7Compat => true|false */ browser.ie7Compat = ( ( version == 7 && !document.documentMode ) || document.documentMode == 7 ); /** * 检测浏览器是否IE6模式或怪异模式 * @name ie6Compat * @grammar UE.browser.ie6Compat => true|false */ browser.ie6Compat = ( version < 7 || browser.quirks ); } // Gecko. if ( browser.gecko ){ var geckoRelease = agent.match( /rv:([\d\.]+)/ ); if ( geckoRelease ) { geckoRelease = geckoRelease[1].split( '.' ); version = geckoRelease[0] * 10000 + ( geckoRelease[1] || 0 ) * 100 + ( geckoRelease[2] || 0 ) * 1; } } /** * 检测浏览器是否为chrome * @name chrome * @grammar UE.browser.chrome => true|false */ if (/chrome\/(\d+\.\d)/i.test(agent)) { browser.chrome = + RegExp['\x241']; } /** * 检测浏览器是否为safari * @name safari * @grammar UE.browser.safari => true|false */ if(/(\d+\.\d)?(?:\.\d)?\s+safari\/?(\d+\.\d+)?/i.test(agent) && !/chrome/i.test(agent)){ browser.safari = + (RegExp['\x241'] || RegExp['\x242']); } // Opera 9.50+ if ( browser.opera ) version = parseFloat( opera.version() ); // WebKit 522+ (Safari 3+) if ( browser.webkit ) version = parseFloat( agent.match( / applewebkit\/(\d+)/ )[1] ); /** * 浏览器版本判断 * IE系列返回值为5,6,7,8,9,10等 * gecko系列会返回10900,158900等. * webkit系列会返回其build号 (如 522等). * @name version * @grammar UE.browser.version => number * @example * if ( UE.browser.ie && UE.browser.version == 6 ){ * alert( "Ouch!居然是万恶的IE6!" ); * } */ browser.version = version; /** * 是否是兼容模式的浏览器 * @name isCompatible * @grammar UE.browser.isCompatible => true|false * @example * if ( UE.browser.isCompatible ){ * alert( "你的浏览器相当不错哦!" ); * } */ browser.isCompatible = !browser.mobile && ( ( browser.ie && version >= 6 ) || ( browser.gecko && version >= 10801 ) || ( browser.opera && version >= 9.5 ) || ( browser.air && version >= 1 ) || ( browser.webkit && version >= 522 ) || false ); return browser; }(); //快捷方式 var ie = browser.ie, webkit = browser.webkit, gecko = browser.gecko, opera = browser.opera;/** * @file * @name UE.Utils * @short Utils * @desc UEditor封装使用的静态工具函数 * @import editor.js */ var utils = UE.utils = { /** * 遍历数组,对象,nodeList * @name each * @grammar UE.utils.each(obj,iterator,[context]) * @since 1.2.4+ * @desc * * obj 要遍历的对象 * * iterator 遍历的方法,方法的第一个是遍历的值,第二个是索引,第三个是obj * * context iterator的上下文 * @example * UE.utils.each([1,2],function(v,i){ * console.log(v)//值 * console.log(i)//索引 * }) * UE.utils.each(document.getElementsByTagName('*'),function(n){ * console.log(n.tagName) * }) */ each : function(obj, iterator, context) { if (obj == null) return; if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if(iterator.call(context, obj[i], i, obj) === false) return false; } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { if(iterator.call(context, obj[key], key, obj) === false) return false; } } } }, makeInstance:function (obj) { var noop = new Function(); noop.prototype = obj; obj = new noop; noop.prototype = null; return obj; }, /** * 将source对象中的属性扩展到target对象上 * @name extend * @grammar UE.utils.extend(target,source) => Object //覆盖扩展 * @grammar UE.utils.extend(target,source,true) ==> Object //保留扩展 */ extend:function (t, s, b) { if (s) { for (var k in s) { if (!b || !t.hasOwnProperty(k)) { t[k] = s[k]; } } } return t; }, extend2:function (t) { var a = arguments; for (var i = 1; i < a.length; i++) { var x = a[i]; for (var k in x) { if (!t.hasOwnProperty(k)) { t[k] = x[k]; } } } return t; }, /** * 模拟继承机制,subClass继承superClass * @name inherits * @grammar UE.utils.inherits(subClass,superClass) => subClass * @example * function SuperClass(){ * this.name = "小李"; * } * SuperClass.prototype = { * hello:function(str){ * console.log(this.name + str); * } * } * function SubClass(){ * this.name = "小张"; * } * UE.utils.inherits(SubClass,SuperClass); * var sub = new SubClass(); * sub.hello("早上好!"); ==> "小张早上好!" */ inherits:function (subClass, superClass) { var oldP = subClass.prototype, newP = utils.makeInstance(superClass.prototype); utils.extend(newP, oldP, true); subClass.prototype = newP; return (newP.constructor = subClass); }, /** * 用指定的context作为fn上下文,也就是this * @name bind * @grammar UE.utils.bind(fn,context) => fn */ bind:function (fn, context) { return function () { return fn.apply(context, arguments); }; }, /** * 创建延迟delay执行的函数fn * @name defer * @grammar UE.utils.defer(fn,delay) =>fn //延迟delay毫秒执行fn,返回fn * @grammar UE.utils.defer(fn,delay,exclusion) =>fn //延迟delay毫秒执行fn,若exclusion为真,则互斥执行fn * @example * function test(){ * console.log("延迟输出!"); * } * //非互斥延迟执行 * var testDefer = UE.utils.defer(test,1000); * testDefer(); => "延迟输出!"; * testDefer(); => "延迟输出!"; * //互斥延迟执行 * var testDefer1 = UE.utils.defer(test,1000,true); * testDefer1(); => //本次不执行 * testDefer1(); => "延迟输出!"; */ defer:function (fn, delay, exclusion) { var timerID; return function () { if (exclusion) { clearTimeout(timerID); } timerID = setTimeout(fn, delay); }; }, /** * 查找元素item在数组array中的索引, 若找不到返回-1 * @name indexOf * @grammar UE.utils.indexOf(array,item) => index|-1 //默认从数组开头部开始搜索 * @grammar UE.utils.indexOf(array,item,start) => index|-1 //start指定开始查找的位置 */ indexOf:function (array, item, start) { var index = -1; start = this.isNumber(start) ? start : 0; this.each(array, function (v, i) { if (i >= start && v === item) { index = i; return false; } }); return index; }, /** * 移除数组array中的元素item * @name removeItem * @grammar UE.utils.removeItem(array,item) */ removeItem:function (array, item) { for (var i = 0, l = array.length; i < l; i++) { if (array[i] === item) { array.splice(i, 1); i--; } } }, /** * 删除字符串str的首尾空格 * @name trim * @grammar UE.utils.trim(str) => String */ trim:function (str) { return str.replace(/(^[ \t\n\r]+)|([ \t\n\r]+$)/g, ''); }, /** * 将字符串list(以','分隔)或者数组list转成哈希对象 * @name listToMap * @grammar UE.utils.listToMap(list) => Object //Object形如{test:1,br:1,textarea:1} */ listToMap:function (list) { if (!list)return {}; list = utils.isArray(list) ? list : list.split(','); for (var i = 0, ci, obj = {}; ci = list[i++];) { obj[ci.toUpperCase()] = obj[ci] = 1; } return obj; }, /** * 将str中的html符号转义,默认将转义''&<">''四个字符,可自定义reg来确定需要转义的字符 * @name unhtml * @grammar UE.utils.unhtml(str); => String * @grammar UE.utils.unhtml(str,reg) => String * @example * var html = '<body>You say:"你好!Baidu & UEditor!"</body>'; * UE.utils.unhtml(html); ==> &lt;body&gt;You say:&quot;你好!Baidu &amp; UEditor!&quot;&lt;/body&gt; * UE.utils.unhtml(html,/[<>]/g) ==> &lt;body&gt;You say:"你好!Baidu & UEditor!"&lt;/body&gt; */ unhtml:function (str, reg) { return str ? str.replace(reg || /[&<">'](?:(amp|lt|quot|gt|#39|nbsp);)?/g, function (a, b) { if (b) { return a; } else { return { '<':'&lt;', '&':'&amp;', '"':'&quot;', '>':'&gt;', "'":'&#39;' }[a] } }) : ''; }, /** * 将str中的转义字符还原成html字符 * @name html * @grammar UE.utils.html(str) => String //详细参见<code><a href = '#unhtml'>unhtml</a></code> */ html:function (str) { return str ? str.replace(/&((g|l|quo)t|amp|#39);/g, function (m) { return { '&lt;':'<', '&amp;':'&', '&quot;':'"', '&gt;':'>', '&#39;':"'" }[m] }) : ''; }, /** * 将css样式转换为驼峰的形式。如font-size => fontSize * @name cssStyleToDomStyle * @grammar UE.utils.cssStyleToDomStyle(cssName) => String */ cssStyleToDomStyle:function () { var test = document.createElement('div').style, cache = { 'float':test.cssFloat != undefined ? 'cssFloat' : test.styleFloat != undefined ? 'styleFloat' : 'float' }; return function (cssName) { return cache[cssName] || (cache[cssName] = cssName.toLowerCase().replace(/-./g, function (match) { return match.charAt(1).toUpperCase(); })); }; }(), /** * 动态加载文件到doc中,并依据obj来设置属性,加载成功后执行回调函数fn * @name loadFile * @grammar UE.utils.loadFile(doc,obj) * @grammar UE.utils.loadFile(doc,obj,fn) * @example * //指定加载到当前document中一个script文件,加载成功后执行function * utils.loadFile( document, { * src:"test.js", * tag:"script", * type:"text/javascript", * defer:"defer" * }, function () { * console.log('加载成功!') * }); */ loadFile:function () { var tmpList = []; function getItem(doc, obj) { try { for (var i = 0, ci; ci = tmpList[i++];) { if (ci.doc === doc && ci.url == (obj.src || obj.href)) { return ci; } } } catch (e) { return null; } } return function (doc, obj, fn) { var item = getItem(doc, obj); if (item) { if (item.ready) { fn && fn(); } else { item.funs.push(fn) } return; } tmpList.push({ doc:doc, url:obj.src || obj.href, funs:[fn] }); if (!doc.body) { var html = []; for (var p in obj) { if (p == 'tag')continue; html.push(p + '="' + obj[p] + '"') } doc.write('<' + obj.tag + ' ' + html.join(' ') + ' ></' + obj.tag + '>'); return; } if (obj.id && doc.getElementById(obj.id)) { return; } var element = doc.createElement(obj.tag); delete obj.tag; for (var p in obj) { element.setAttribute(p, obj[p]); } element.onload = element.onreadystatechange = function () { if (!this.readyState || /loaded|complete/.test(this.readyState)) { item = getItem(doc, obj); if (item.funs.length > 0) { item.ready = 1; for (var fi; fi = item.funs.pop();) { fi(); } } element.onload = element.onreadystatechange = null; } }; element.onerror = function () { throw Error('The load ' + (obj.href || obj.src) + ' fails,check the url settings of file ueditor.config.js ') }; doc.getElementsByTagName("head")[0].appendChild(element); } }(), /** * 判断obj对象是否为空 * @name isEmptyObject * @grammar UE.utils.isEmptyObject(obj) => true|false * @example * UE.utils.isEmptyObject({}) ==>true * UE.utils.isEmptyObject([]) ==>true * UE.utils.isEmptyObject("") ==>true */ isEmptyObject:function (obj) { if (obj == null) return true; if (this.isArray(obj) || this.isString(obj)) return obj.length === 0; for (var key in obj) if (obj.hasOwnProperty(key)) return false; return true; }, /** * 统一将颜色值使用16进制形式表示 * @name fixColor * @grammar UE.utils.fixColor(name,value) => value * @example * rgb(255,255,255) => "#ffffff" */ fixColor:function (name, value) { if (/color/i.test(name) && /rgba?/.test(value)) { var array = value.split(","); if (array.length > 3) return ""; value = "#"; for (var i = 0, color; color = array[i++];) { color = parseInt(color.replace(/[^\d]/gi, ''), 10).toString(16); value += color.length == 1 ? "0" + color : color; } value = value.toUpperCase(); } return value; }, /** * 只针对border,padding,margin做了处理,因为性能问题 * @public * @function * @param {String} val style字符串 */ optCss:function (val) { var padding, margin, border; val = val.replace(/(padding|margin|border)\-([^:]+):([^;]+);?/gi, function (str, key, name, val) { if (val.split(' ').length == 1) { switch (key) { case 'padding': !padding && (padding = {}); padding[name] = val; return ''; case 'margin': !margin && (margin = {}); margin[name] = val; return ''; case 'border': return val == 'initial' ? '' : str; } } return str; }); function opt(obj, name) { if (!obj) { return ''; } var t = obj.top , b = obj.bottom, l = obj.left, r = obj.right, val = ''; if (!t || !l || !b || !r) { for (var p in obj) { val += ';' + name + '-' + p + ':' + obj[p] + ';'; } } else { val += ';' + name + ':' + (t == b && b == l && l == r ? t : t == b && l == r ? (t + ' ' + l) : l == r ? (t + ' ' + l + ' ' + b) : (t + ' ' + r + ' ' + b + ' ' + l)) + ';' } return val; } val += opt(padding, 'padding') + opt(margin, 'margin'); return val.replace(/^[ \n\r\t;]*|[ \n\r\t]*$/, '').replace(/;([ \n\r\t]+)|\1;/g, ';') .replace(/(&((l|g)t|quot|#39))?;{2,}/g, function (a, b) { return b ? b + ";;" : ';' }); }, /** * 深度克隆对象,从source到target * @name clone * @grammar UE.utils.clone(source) => anthorObj 新的对象是完整的source的副本 * @grammar UE.utils.clone(source,target) => target包含了source的所有内容,重名会覆盖 */ clone:function (source, target) { var tmp; target = target || {}; for (var i in source) { if (source.hasOwnProperty(i)) { tmp = source[i]; if (typeof tmp == 'object') { target[i] = utils.isArray(tmp) ? [] : {}; utils.clone(source[i], target[i]) } else { target[i] = tmp; } } } return target; }, /** * 转换cm/pt到px * @name transUnitToPx * @grammar UE.utils.transUnitToPx('20pt') => '27px' * @grammar UE.utils.transUnitToPx('0pt') => '0' */ transUnitToPx:function (val) { if (!/(pt|cm)/.test(val)) { return val } var unit; val.replace(/([\d.]+)(\w+)/, function (str, v, u) { val = v; unit = u; }); switch (unit) { case 'cm': val = parseFloat(val) * 25; break; case 'pt': val = Math.round(parseFloat(val) * 96 / 72); } return val + (val ? 'px' : ''); }, /** * DomReady方法,回调函数将在dom树ready完成后执行 * @name domReady * @grammar UE.utils.domReady(fn) => fn //返回一个延迟执行的方法 */ domReady:function () { var fnArr = []; function doReady(doc) { //确保onready只执行一次 doc.isReady = true; for (var ci; ci = fnArr.pop(); ci()) { } } return function (onready, win) { win = win || window; var doc = win.document; onready && fnArr.push(onready); if (doc.readyState === "complete") { doReady(doc); } else { doc.isReady && doReady(doc); if (browser.ie) { (function () { if (doc.isReady) return; try { doc.documentElement.doScroll("left"); } catch (error) { setTimeout(arguments.callee, 0); return; } doReady(doc); })(); win.attachEvent('onload', function () { doReady(doc) }); } else { doc.addEventListener("DOMContentLoaded", function () { doc.removeEventListener("DOMContentLoaded", arguments.callee, false); doReady(doc); }, false); win.addEventListener('load', function () { doReady(doc) }, false); } } } }(), /** * 动态添加css样式 * @name cssRule * @grammar UE.utils.cssRule('添加的样式的节点名称',['样式','放到哪个document上']) * @grammar UE.utils.cssRule('body','body{background:#ccc}') => null //给body添加背景颜色 * @grammar UE.utils.cssRule('body') =>样式的字符串 //取得key值为body的样式的内容,如果没有找到key值先关的样式将返回空,例如刚才那个背景颜色,将返回 body{background:#ccc} * @grammar UE.utils.cssRule('body','') =>null //清空给定的key值的背景颜色 */ cssRule:browser.ie ? function (key, style, doc) { var indexList, index; doc = doc || document; if (doc.indexList) { indexList = doc.indexList; } else { indexList = doc.indexList = {}; } var sheetStyle; if (!indexList[key]) { if (style === undefined) { return '' } sheetStyle = doc.createStyleSheet('', index = doc.styleSheets.length); indexList[key] = index; } else { sheetStyle = doc.styleSheets[indexList[key]]; } if (style === undefined) { return sheetStyle.cssText } sheetStyle.cssText = style || '' } : function (key, style, doc) { doc = doc || document; var head = doc.getElementsByTagName('head')[0], node; if (!(node = doc.getElementById(key))) { if (style === undefined) { return '' } node = doc.createElement('style'); node.id = key; head.appendChild(node) } if (style === undefined) { return node.innerHTML } if (style !== '') { node.innerHTML = style; } else { head.removeChild(node) } }, sort:function(array,compareFn){ compareFn = compareFn || function(item1, item2){ return item1.localeCompare(item2);}; for(var i= 0,len = array.length; i<len; i++){ for(var j = i,length = array.length; j<length; j++){ if(compareFn(array[i], array[j]) > 0){ var t = array[i]; array[i] = array[j]; array[j] = t; } } } return array; } }; /** * 判断str是否为字符串 * @name isString * @grammar UE.utils.isString(str) => true|false */ /** * 判断array是否为数组 * @name isArray * @grammar UE.utils.isArray(obj) => true|false */ /** * 判断obj对象是否为方法 * @name isFunction * @grammar UE.utils.isFunction(obj) => true|false */ /** * 判断obj对象是否为数字 * @name isNumber * @grammar UE.utils.isNumber(obj) => true|false */ utils.each(['String', 'Function', 'Array', 'Number', 'RegExp', 'Object'], function (v) { UE.utils['is' + v] = function (obj) { return Object.prototype.toString.apply(obj) == '[object ' + v + ']'; } });/** * @file * @name UE.EventBase * @short EventBase * @import editor.js,core/utils.js * @desc UE采用的事件基类,继承此类的对应类将获取addListener,removeListener,fireEvent方法。 * 在UE中,Editor以及所有ui实例都继承了该类,故可以在对应的ui对象以及editor对象上使用上述方法。 */ var EventBase = UE.EventBase = function () {}; EventBase.prototype = { /** * 注册事件监听器 * @name addListener * @grammar editor.addListener(types,fn) //types为事件名称,多个可用空格分隔 * @example * editor.addListener('selectionchange',function(){ * console.log("选区已经变化!"); * }) * editor.addListener('beforegetcontent aftergetcontent',function(type){ * if(type == 'beforegetcontent'){ * //do something * }else{ * //do something * } * console.log(this.getContent) // this是注册的事件的编辑器实例 * }) */ addListener:function (types, listener) { types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { getListener(this, ti, true).push(listener); } }, /** * 移除事件监听器 * @name removeListener * @grammar editor.removeListener(types,fn) //types为事件名称,多个可用空格分隔 * @example * //changeCallback为方法体 * editor.removeListener("selectionchange",changeCallback); */ removeListener:function (types, listener) { types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { utils.removeItem(getListener(this, ti) || [], listener); } }, /** * 触发事件 * @name fireEvent * @grammar editor.fireEvent(types) //types为事件名称,多个可用空格分隔 * @example * editor.fireEvent("selectionchange"); */ fireEvent:function () { var types = arguments[0]; types = utils.trim(types).split(' '); for (var i = 0, ti; ti = types[i++];) { var listeners = getListener(this, ti), r, t, k; if (listeners) { k = listeners.length; while (k--) { if(!listeners[k])continue; t = listeners[k].apply(this, arguments); if(t === true){ return t; } if (t !== undefined) { r = t; } } } if (t = this['on' + ti.toLowerCase()]) { r = t.apply(this, arguments); } } return r; } }; /** * 获得对象所拥有监听类型的所有监听器 * @public * @function * @param {Object} obj 查询监听器的对象 * @param {String} type 事件类型 * @param {Boolean} force 为true且当前所有type类型的侦听器不存在时,创建一个空监听器数组 * @returns {Array} 监听器数组 */ function getListener(obj, type, force) { var allListeners; type = type.toLowerCase(); return ( ( allListeners = ( obj.__allListeners || force && ( obj.__allListeners = {} ) ) ) && ( allListeners[type] || force && ( allListeners[type] = [] ) ) ); } ///import editor.js ///import core/dom/dom.js ///import core/utils.js /** * dtd html语义化的体现类 * @constructor * @namespace dtd */ var dtd = dom.dtd = (function() { function _( s ) { for (var k in s) { s[k.toUpperCase()] = s[k]; } return s; } var X = utils.extend2; var A = _({isindex:1,fieldset:1}), B = _({input:1,button:1,select:1,textarea:1,label:1}), C = X( _({a:1}), B ), D = X( {iframe:1}, C ), E = _({hr:1,ul:1,menu:1,div:1,blockquote:1,noscript:1,table:1,center:1,address:1,dir:1,pre:1,h5:1,dl:1,h4:1,noframes:1,h6:1,ol:1,h1:1,h3:1,h2:1}), F = _({ins:1,del:1,script:1,style:1}), G = X( _({b:1,acronym:1,bdo:1,'var':1,'#':1,abbr:1,code:1,br:1,i:1,cite:1,kbd:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,dfn:1,span:1}), F ), H = X( _({sub:1,img:1,embed:1,object:1,sup:1,basefont:1,map:1,applet:1,font:1,big:1,small:1}), G ), I = X( _({p:1}), H ), J = X( _({iframe:1}), H, B ), K = _({img:1,embed:1,noscript:1,br:1,kbd:1,center:1,button:1,basefont:1,h5:1,h4:1,samp:1,h6:1,ol:1,h1:1,h3:1,h2:1,form:1,font:1,'#':1,select:1,menu:1,ins:1,abbr:1,label:1,code:1,table:1,script:1,cite:1,input:1,iframe:1,strong:1,textarea:1,noframes:1,big:1,small:1,span:1,hr:1,sub:1,bdo:1,'var':1,div:1,object:1,sup:1,strike:1,dir:1,map:1,dl:1,applet:1,del:1,isindex:1,fieldset:1,ul:1,b:1,acronym:1,a:1,blockquote:1,i:1,u:1,s:1,tt:1,address:1,q:1,pre:1,p:1,em:1,dfn:1}), L = X( _({a:0}), J ),//a不能被切开,所以把他 M = _({tr:1}), N = _({'#':1}), O = X( _({param:1}), K ), P = X( _({form:1}), A, D, E, I ), Q = _({li:1,ol:1,ul:1}), R = _({style:1,script:1}), S = _({base:1,link:1,meta:1,title:1}), T = X( S, R ), U = _({head:1,body:1}), V = _({html:1}); var block = _({address:1,blockquote:1,center:1,dir:1,div:1,dl:1,fieldset:1,form:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1,hr:1,isindex:1,menu:1,noframes:1,ol:1,p:1,pre:1,table:1,ul:1}), empty = _({area:1,base:1,basefont:1,br:1,col:1,command:1,dialog:1,embed:1,hr:1,img:1,input:1,isindex:1,keygen:1,link:1,meta:1,param:1,source:1,track:1,wbr:1}); return _({ // $ 表示自定的属性 // body外的元素列表. $nonBodyContent: X( V, U, S ), //块结构元素列表 $block : block, //内联元素列表 $inline : L, $inlineWithA : X(_({a:1}),L), $body : X( _({script:1,style:1}), block ), $cdata : _({script:1,style:1}), //自闭和元素 $empty : empty, //不是自闭合,但不能让range选中里边 $nonChild : _({iframe:1,textarea:1}), //列表元素列表 $listItem : _({dd:1,dt:1,li:1}), //列表根元素列表 $list: _({ul:1,ol:1,dl:1}), //不能认为是空的元素 $isNotEmpty : _({table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1,h1:1,h2:1,h3:1,h4:1,h5:1,h6:1}), //如果没有子节点就可以删除的元素列表,像span,a $removeEmpty : _({a:1,abbr:1,acronym:1,address:1,b:1,bdo:1,big:1,cite:1,code:1,del:1,dfn:1,em:1,font:1,i:1,ins:1,label:1,kbd:1,q:1,s:1,samp:1,small:1,span:1,strike:1,strong:1,sub:1,sup:1,tt:1,u:1,'var':1}), $removeEmptyBlock : _({'p':1,'div':1}), //在table元素里的元素列表 $tableContent : _({caption:1,col:1,colgroup:1,tbody:1,td:1,tfoot:1,th:1,thead:1,tr:1,table:1}), //不转换的标签 $notTransContent : _({pre:1,script:1,style:1,textarea:1}), html: U, head: T, style: N, script: N, body: P, base: {}, link: {}, meta: {}, title: N, col : {}, tr : _({td:1,th:1}), img : {}, embed: {}, colgroup : _({thead:1,col:1,tbody:1,tr:1,tfoot:1}), noscript : P, td : P, br : {}, th : P, center : P, kbd : L, button : X( I, E ), basefont : {}, h5 : L, h4 : L, samp : L, h6 : L, ol : Q, h1 : L, h3 : L, option : N, h2 : L, form : X( A, D, E, I ), select : _({optgroup:1,option:1}), font : L, ins : L, menu : Q, abbr : L, label : L, table : _({thead:1,col:1,tbody:1,tr:1,colgroup:1,caption:1,tfoot:1}), code : L, tfoot : M, cite : L, li : P, input : {}, iframe : P, strong : L, textarea : N, noframes : P, big : L, small : L, //trace: span :_({'#':1,br:1,b:1,strong:1,u:1,i:1,em:1,sub:1,sup:1,strike:1,span:1}), hr : L, dt : L, sub : L, optgroup : _({option:1}), param : {}, bdo : L, 'var' : L, div : P, object : O, sup : L, dd : P, strike : L, area : {}, dir : Q, map : X( _({area:1,form:1,p:1}), A, F, E ), applet : O, dl : _({dt:1,dd:1}), del : L, isindex : {}, fieldset : X( _({legend:1}), K ), thead : M, ul : Q, acronym : L, b : L, a : X( _({a:1}), J ), blockquote :X(_({td:1,tr:1,tbody:1,li:1}),P), caption : L, i : L, u : L, tbody : M, s : L, address : X( D, I ), tt : L, legend : L, q : L, pre : X( G, C ), p : X(_({'a':1}),L), em :L, dfn : L }); })(); /** * @file * @name UE.dom.domUtils * @short DomUtils * @import editor.js, core/utils.js,core/browser.js,core/dom/dtd.js * @desc UEditor封装的底层dom操作库 */ function getDomNode(node, start, ltr, startFromChild, fn, guard) { var tmpNode = startFromChild && node[start], parent; !tmpNode && (tmpNode = node[ltr]); while (!tmpNode && (parent = (parent || node).parentNode)) { if (parent.tagName == 'BODY' || guard && !guard(parent)) { return null; } tmpNode = parent[ltr]; } if (tmpNode && fn && !fn(tmpNode)) { return getDomNode(tmpNode, start, ltr, false, fn); } return tmpNode; } var attrFix = ie && browser.version < 9 ? { tabindex:"tabIndex", readonly:"readOnly", "for":"htmlFor", "class":"className", maxlength:"maxLength", cellspacing:"cellSpacing", cellpadding:"cellPadding", rowspan:"rowSpan", colspan:"colSpan", usemap:"useMap", frameborder:"frameBorder" } : { tabindex:"tabIndex", readonly:"readOnly" }, styleBlock = utils.listToMap([ '-webkit-box', '-moz-box', 'block' , 'list-item' , 'table' , 'table-row-group' , 'table-header-group', 'table-footer-group' , 'table-row' , 'table-column-group' , 'table-column' , 'table-cell' , 'table-caption' ]); var domUtils = dom.domUtils = { //节点常量 NODE_ELEMENT:1, NODE_DOCUMENT:9, NODE_TEXT:3, NODE_COMMENT:8, NODE_DOCUMENT_FRAGMENT:11, //位置关系 POSITION_IDENTICAL:0, POSITION_DISCONNECTED:1, POSITION_FOLLOWING:2, POSITION_PRECEDING:4, POSITION_IS_CONTAINED:8, POSITION_CONTAINS:16, //ie6使用其他的会有一段空白出现 fillChar:ie && browser.version == '6' ? '\ufeff' : '\u200B', //-------------------------Node部分-------------------------------- keys:{ /*Backspace*/ 8:1, /*Delete*/ 46:1, /*Shift*/ 16:1, /*Ctrl*/ 17:1, /*Alt*/ 18:1, 37:1, 38:1, 39:1, 40:1, 13:1 /*enter*/ }, /** * 获取节点A相对于节点B的位置关系 * @name getPosition * @grammar UE.dom.domUtils.getPosition(nodeA,nodeB) => Number * @example * switch (returnValue) { * case 0: //相等,同一节点 * case 1: //无关,节点不相连 * case 2: //跟随,即节点A头部位于节点B头部的后面 * case 4: //前置,即节点A头部位于节点B头部的前面 * case 8: //被包含,即节点A被节点B包含 * case 10://组合类型,即节点A满足跟随节点B且被节点B包含。实际上,如果被包含,必定跟随,所以returnValue事实上不会存在8的情况。 * case 16://包含,即节点A包含节点B * case 20://组合类型,即节点A满足前置节点A且包含节点B。同样,如果包含,必定前置,所以returnValue事实上也不会存在16的情况 * } */ getPosition:function (nodeA, nodeB) { // 如果两个节点是同一个节点 if (nodeA === nodeB) { // domUtils.POSITION_IDENTICAL return 0; } var node, parentsA = [nodeA], parentsB = [nodeB]; node = nodeA; while (node = node.parentNode) { // 如果nodeB是nodeA的祖先节点 if (node === nodeB) { // domUtils.POSITION_IS_CONTAINED + domUtils.POSITION_FOLLOWING return 10; } parentsA.push(node); } node = nodeB; while (node = node.parentNode) { // 如果nodeA是nodeB的祖先节点 if (node === nodeA) { // domUtils.POSITION_CONTAINS + domUtils.POSITION_PRECEDING return 20; } parentsB.push(node); } parentsA.reverse(); parentsB.reverse(); if (parentsA[0] !== parentsB[0]) { // domUtils.POSITION_DISCONNECTED return 1; } var i = -1; while (i++, parentsA[i] === parentsB[i]) { } nodeA = parentsA[i]; nodeB = parentsB[i]; while (nodeA = nodeA.nextSibling) { if (nodeA === nodeB) { // domUtils.POSITION_PRECEDING return 4 } } // domUtils.POSITION_FOLLOWING return 2; }, /** * 返回节点node在父节点中的索引位置 * @name getNodeIndex * @grammar UE.dom.domUtils.getNodeIndex(node) => Number //索引值从0开始 */ getNodeIndex:function (node, ignoreTextNode) { var preNode = node, i = 0; while (preNode = preNode.previousSibling) { if (ignoreTextNode && preNode.nodeType == 3) { if(preNode.nodeType != preNode.nextSibling.nodeType ){ i++; } continue; } i++; } return i; }, /** * 检测节点node是否在节点doc的树上,实质上是检测是否被doc包含 * @name inDoc * @grammar UE.dom.domUtils.inDoc(node,doc) => true|false */ inDoc:function (node, doc) { return domUtils.getPosition(node, doc) == 10; }, /** * 查找node节点的祖先节点 * @name findParent * @grammar UE.dom.domUtils.findParent(node) => Element // 直接返回node节点的父节点 * @grammar UE.dom.domUtils.findParent(node,filterFn) => Element //filterFn为过滤函数,node作为参数,返回true时才会将node作为符合要求的节点返回 * @grammar UE.dom.domUtils.findParent(node,filterFn,includeSelf) => Element //includeSelf指定是否包含自身 */ findParent:function (node, filterFn, includeSelf) { if (node && !domUtils.isBody(node)) { node = includeSelf ? node : node.parentNode; while (node) { if (!filterFn || filterFn(node) || domUtils.isBody(node)) { return filterFn && !filterFn(node) && domUtils.isBody(node) ? null : node; } node = node.parentNode; } } return null; }, /** * 通过tagName查找node节点的祖先节点 * @name findParentByTagName * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames) => Element //tagNames支持数组,区分大小写 * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf) => Element //includeSelf指定是否包含自身 * @grammar UE.dom.domUtils.findParentByTagName(node,tagNames,includeSelf,excludeFn) => Element //excludeFn指定例外过滤条件,返回true时忽略该节点 */ findParentByTagName:function (node, tagNames, includeSelf, excludeFn) { tagNames = utils.listToMap(utils.isArray(tagNames) ? tagNames : [tagNames]); return domUtils.findParent(node, function (node) { return tagNames[node.tagName] && !(excludeFn && excludeFn(node)); }, includeSelf); }, /** * 查找节点node的祖先节点集合 * @name findParents * @grammar UE.dom.domUtils.findParents(node) => Array //返回一个祖先节点数组集合,不包含自身 * @grammar UE.dom.domUtils.findParents(node,includeSelf) => Array //返回一个祖先节点数组集合,includeSelf指定是否包含自身 * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn) => Array //返回一个祖先节点数组集合,filterFn指定过滤条件,返回true的node将被选取 * @grammar UE.dom.domUtils.findParents(node,includeSelf,filterFn,closerFirst) => Array //返回一个祖先节点数组集合,closerFirst为true的话,node的直接父亲节点是数组的第0个 */ findParents:function (node, includeSelf, filterFn, closerFirst) { var parents = includeSelf && ( filterFn && filterFn(node) || !filterFn ) ? [node] : []; while (node = domUtils.findParent(node, filterFn)) { parents.push(node); } return closerFirst ? parents : parents.reverse(); }, /** * 在节点node后面插入新节点newNode * @name insertAfter * @grammar UE.dom.domUtils.insertAfter(node,newNode) => newNode */ insertAfter:function (node, newNode) { return node.parentNode.insertBefore(newNode, node.nextSibling); }, /** * 删除节点node,并根据keepChildren指定是否保留子节点 * @name remove * @grammar UE.dom.domUtils.remove(node) => node * @grammar UE.dom.domUtils.remove(node,keepChildren) => node */ remove:function (node, keepChildren) { var parent = node.parentNode, child; if (parent) { if (keepChildren && node.hasChildNodes()) { while (child = node.firstChild) { parent.insertBefore(child, node); } } parent.removeChild(node); } return node; }, /** * 取得node节点在dom树上的下一个节点,即多叉树遍历 * @name getNextDomNode * @grammar UE.dom.domUtils.getNextDomNode(node) => Element * @example */ getNextDomNode:function (node, startFromChild, filterFn, guard) { return getDomNode(node, 'firstChild', 'nextSibling', startFromChild, filterFn, guard); }, /** * 检测节点node是否属于bookmark节点 * @name isBookmarkNode * @grammar UE.dom.domUtils.isBookmarkNode(node) => true|false */ isBookmarkNode:function (node) { return node.nodeType == 1 && node.id && /^_baidu_bookmark_/i.test(node.id); }, /** * 获取节点node所在的window对象 * @name getWindow * @grammar UE.dom.domUtils.getWindow(node) => window对象 */ getWindow:function (node) { var doc = node.ownerDocument || node; return doc.defaultView || doc.parentWindow; }, /** * 得到nodeA与nodeB公共的祖先节点 * @name getCommonAncestor * @grammar UE.dom.domUtils.getCommonAncestor(nodeA,nodeB) => Element */ getCommonAncestor:function (nodeA, nodeB) { if (nodeA === nodeB) return nodeA; var parentsA = [nodeA] , parentsB = [nodeB], parent = nodeA, i = -1; while (parent = parent.parentNode) { if (parent === nodeB) { return parent; } parentsA.push(parent); } parent = nodeB; while (parent = parent.parentNode) { if (parent === nodeA) return parent; parentsB.push(parent); } parentsA.reverse(); parentsB.reverse(); while (i++, parentsA[i] === parentsB[i]) { } return i == 0 ? null : parentsA[i - 1]; }, /** * 清除node节点左右兄弟为空的inline节点 * @name clearEmptySibling * @grammar UE.dom.domUtils.clearEmptySibling(node) * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext) //ignoreNext指定是否忽略右边空节点 * @grammar UE.dom.domUtils.clearEmptySibling(node,ignoreNext,ignorePre) //ignorePre指定是否忽略左边空节点 * @example * <b></b><i></i>xxxx<b>bb</b> --> xxxx<b>bb</b> */ clearEmptySibling:function (node, ignoreNext, ignorePre) { function clear(next, dir) { var tmpNode; while (next && !domUtils.isBookmarkNode(next) && (domUtils.isEmptyInlineElement(next) //这里不能把空格算进来会吧空格干掉,出现文字间的空格丢掉了 || !new RegExp('[^\t\n\r' + domUtils.fillChar + ']').test(next.nodeValue) )) { tmpNode = next[dir]; domUtils.remove(next); next = tmpNode; } } !ignoreNext && clear(node.nextSibling, 'nextSibling'); !ignorePre && clear(node.previousSibling, 'previousSibling'); }, /** * 将一个文本节点node拆分成两个文本节点,offset指定拆分位置 * @name split * @grammar UE.dom.domUtils.split(node,offset) => TextNode //返回从切分位置开始的后一个文本节点 */ split:function (node, offset) { var doc = node.ownerDocument; if (browser.ie && offset == node.nodeValue.length) { var next = doc.createTextNode(''); return domUtils.insertAfter(node, next); } var retval = node.splitText(offset); //ie8下splitText不会跟新childNodes,我们手动触发他的更新 if (browser.ie8) { var tmpNode = doc.createTextNode(''); domUtils.insertAfter(retval, tmpNode); domUtils.remove(tmpNode); } return retval; }, /** * 检测节点node是否为空节点(包括空格、换行、占位符等字符) * @name isWhitespace * @grammar UE.dom.domUtils.isWhitespace(node) => true|false */ isWhitespace:function (node) { return !new RegExp('[^ \t\n\r' + domUtils.fillChar + ']').test(node.nodeValue); }, /** * 获取元素element相对于viewport的位置坐标 * @name getXY * @grammar UE.dom.domUtils.getXY(element) => Object //返回坐标对象{x:left,y:top} */ getXY:function (element) { var x = 0, y = 0; while (element.offsetParent) { y += element.offsetTop; x += element.offsetLeft; element = element.offsetParent; } return { 'x':x, 'y':y}; }, /** * 为元素element绑定原生DOM事件,type为事件类型,handler为处理函数 * @name on * @grammar UE.dom.domUtils.on(element,type,handler) //type支持数组传入 * @example * UE.dom.domUtils.on(document.body,"click",function(e){ * //e为事件对象,this为被点击元素对戏那个 * }) * @example * UE.dom.domUtils.on(document.body,["click","mousedown"],function(evt){ * //evt为事件对象,this为被点击元素对象 * }) */ on:function (element, type, handler) { var types = utils.isArray(type) ? type : [type], k = types.length; if (k) while (k--) { type = types[k]; if (element.addEventListener) { element.addEventListener(type, handler, false); } else { if (!handler._d) { handler._d = { els : [] }; } var key = type + handler.toString(),index = utils.indexOf(handler._d.els,element); if (!handler._d[key] || index == -1) { if(index == -1){ handler._d.els.push(element); } if(!handler._d[key]){ handler._d[key] = function (evt) { return handler.call(evt.srcElement, evt || window.event); }; } element.attachEvent('on' + type, handler._d[key]); } } } element = null; }, /** * 解除原生DOM事件绑定 * @name un * @grammar UE.dom.donUtils.un(element,type,handler) //参见<code><a href="#on">on</a></code> */ un:function (element, type, handler) { var types = utils.isArray(type) ? type : [type], k = types.length; if (k) while (k--) { type = types[k]; if (element.removeEventListener) { element.removeEventListener(type, handler, false); } else { var key = type + handler.toString(); try{ element.detachEvent('on' + type, handler._d ? handler._d[key] : handler); }catch(e){} if (handler._d && handler._d[key]) { var index = utils.indexOf(handler._d.els,element); if(index!=-1){ handler._d.els.splice(index,1); } handler._d.els.length == 0 && delete handler._d[key]; } } } }, /** * 比较节点nodeA与节点nodeB是否具有相同的标签名、属性名以及属性值 * @name isSameElement * @grammar UE.dom.domUtils.isSameElement(nodeA,nodeB) => true|false * @example * <span style="font-size:12px">ssss</span> and <span style="font-size:12px">bbbbb</span> => true * <span style="font-size:13px">ssss</span> and <span style="font-size:12px">bbbbb</span> => false */ isSameElement:function (nodeA, nodeB) { if (nodeA.tagName != nodeB.tagName) { return false; } var thisAttrs = nodeA.attributes, otherAttrs = nodeB.attributes; if (!ie && thisAttrs.length != otherAttrs.length) { return false; } var attrA, attrB, al = 0, bl = 0; for (var i = 0; attrA = thisAttrs[i++];) { if (attrA.nodeName == 'style') { if (attrA.specified) { al++; } if (domUtils.isSameStyle(nodeA, nodeB)) { continue; } else { return false; } } if (ie) { if (attrA.specified) { al++; attrB = otherAttrs.getNamedItem(attrA.nodeName); } else { continue; } } else { attrB = nodeB.attributes[attrA.nodeName]; } if (!attrB.specified || attrA.nodeValue != attrB.nodeValue) { return false; } } // 有可能attrB的属性包含了attrA的属性之外还有自己的属性 if (ie) { for (i = 0; attrB = otherAttrs[i++];) { if (attrB.specified) { bl++; } } if (al != bl) { return false; } } return true; }, /** * 判断节点nodeA与节点nodeB的元素属性是否一致 * @name isSameStyle * @grammar UE.dom.domUtils.isSameStyle(nodeA,nodeB) => true|false */ isSameStyle:function (nodeA, nodeB) { var styleA = nodeA.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'), styleB = nodeB.style.cssText.replace(/( ?; ?)/g, ';').replace(/( ?: ?)/g, ':'); if (browser.opera) { styleA = nodeA.style; styleB = nodeB.style; if (styleA.length != styleB.length) return false; for (var p in styleA) { if (/^(\d+|csstext)$/i.test(p)) { continue; } if (styleA[p] != styleB[p]) { return false; } } return true; } if (!styleA || !styleB) { return styleA == styleB; } styleA = styleA.split(';'); styleB = styleB.split(';'); if (styleA.length != styleB.length) { return false; } for (var i = 0, ci; ci = styleA[i++];) { if (utils.indexOf(styleB, ci) == -1) { return false; } } return true; }, /** * 检查节点node是否为块元素 * @name isBlockElm * @grammar UE.dom.domUtils.isBlockElm(node) => true|false */ isBlockElm:function (node) { return node.nodeType == 1 && (dtd.$block[node.tagName] || styleBlock[domUtils.getComputedStyle(node, 'display')]) && !dtd.$nonChild[node.tagName]; }, /** * 检测node节点是否为body节点 * @name isBody * @grammar UE.dom.domUtils.isBody(node) => true|false */ isBody:function (node) { return node && node.nodeType == 1 && node.tagName.toLowerCase() == 'body'; }, /** * 以node节点为中心,将该节点的指定祖先节点parent拆分成2块 * @name breakParent * @grammar UE.dom.domUtils.breakParent(node,parent) => node * @desc * <code type="html"><b>ooo</b>是node节点 * <p>xxxx<b>ooo</b>xxx</p> ==> <p>xxx</p><b>ooo</b><p>xxx</p> * <p>xxxxx<span>xxxx<b>ooo</b>xxxxxx</span></p> => <p>xxxxx<span>xxxx</span></p><b>ooo</b><p><span>xxxxxx</span></p></code> */ breakParent:function (node, parent) { var tmpNode, parentClone = node, clone = node, leftNodes, rightNodes; do { parentClone = parentClone.parentNode; if (leftNodes) { tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(leftNodes); leftNodes = tmpNode; tmpNode = parentClone.cloneNode(false); tmpNode.appendChild(rightNodes); rightNodes = tmpNode; } else { leftNodes = parentClone.cloneNode(false); rightNodes = leftNodes.cloneNode(false); } while (tmpNode = clone.previousSibling) { leftNodes.insertBefore(tmpNode, leftNodes.firstChild); } while (tmpNode = clone.nextSibling) { rightNodes.appendChild(tmpNode); } clone = parentClone; } while (parent !== parentClone); tmpNode = parent.parentNode; tmpNode.insertBefore(leftNodes, parent); tmpNode.insertBefore(rightNodes, parent); tmpNode.insertBefore(node, rightNodes); domUtils.remove(parent); return node; }, /** * 检查节点node是否是空inline节点 * @name isEmptyInlineElement * @grammar UE.dom.domUtils.isEmptyInlineElement(node) => 1|0 * @example * <b><i></i></b> => 1 * <b><i></i><u></u></b> => 1 * <b></b> => 1 * <b>xx<i></i></b> => 0 */ isEmptyInlineElement:function (node) { if (node.nodeType != 1 || !dtd.$removeEmpty[ node.tagName ]) { return 0; } node = node.firstChild; while (node) { //如果是创建的bookmark就跳过 if (domUtils.isBookmarkNode(node)) { return 0; } if (node.nodeType == 1 && !domUtils.isEmptyInlineElement(node) || node.nodeType == 3 && !domUtils.isWhitespace(node) ) { return 0; } node = node.nextSibling; } return 1; }, /** * 删除node节点下的左右空白文本子节点 * @name trimWhiteTextNode * @grammar UE.dom.domUtils.trimWhiteTextNode(node) */ trimWhiteTextNode:function (node) { function remove(dir) { var child; while ((child = node[dir]) && child.nodeType == 3 && domUtils.isWhitespace(child)) { node.removeChild(child); } } remove('firstChild'); remove('lastChild'); }, /** * 合并node节点下相同的子节点 * @name mergeChild * @desc * UE.dom.domUtils.mergeChild(node,tagName) //tagName要合并的子节点的标签 * @example * <p><span style="font-size:12px;">xx<span style="font-size:12px;">aa</span>xx</span></p> * ==> UE.dom.domUtils.mergeChild(node,'span') * <p><span style="font-size:12px;">xxaaxx</span></p> */ mergeChild:function (node, tagName, attrs) { var list = domUtils.getElementsByTagName(node, node.tagName.toLowerCase()); for (var i = 0, ci; ci = list[i++];) { if (!ci.parentNode || domUtils.isBookmarkNode(ci)) { continue; } //span单独处理 if (ci.tagName.toLowerCase() == 'span') { if (node === ci.parentNode) { domUtils.trimWhiteTextNode(node); if (node.childNodes.length == 1) { node.style.cssText = ci.style.cssText + ";" + node.style.cssText; domUtils.remove(ci, true); continue; } } ci.style.cssText = node.style.cssText + ';' + ci.style.cssText; if (attrs) { var style = attrs.style; if (style) { style = style.split(';'); for (var j = 0, s; s = style[j++];) { ci.style[utils.cssStyleToDomStyle(s.split(':')[0])] = s.split(':')[1]; } } } if (domUtils.isSameStyle(ci, node)) { domUtils.remove(ci, true); } continue; } if (domUtils.isSameElement(node, ci)) { domUtils.remove(ci, true); } } }, /** * 原生方法getElementsByTagName的封装 * @name getElementsByTagName * @grammar UE.dom.domUtils.getElementsByTagName(node,tagName) => Array //节点集合数组 */ getElementsByTagName:function (node, name,filter) { if(filter && utils.isString(filter)){ var className = filter; filter = function(node){return domUtils.hasClass(node,className)} } name = utils.trim(name).replace(/[ ]{2,}/g,' ').split(' '); var arr = []; for(var n = 0,ni;ni=name[n++];){ var list = node.getElementsByTagName(ni); for (var i = 0, ci; ci = list[i++];) { if(!filter || filter(ci)) arr.push(ci); } } return arr; }, /** * 将节点node合并到父节点上 * @name mergeToParent * @grammar UE.dom.domUtils.mergeToParent(node) * @example * <span style="color:#fff"><span style="font-size:12px">xxx</span></span> ==> <span style="color:#fff;font-size:12px">xxx</span> */ mergeToParent:function (node) { var parent = node.parentNode; while (parent && dtd.$removeEmpty[parent.tagName]) { if (parent.tagName == node.tagName || parent.tagName == 'A') {//针对a标签单独处理 domUtils.trimWhiteTextNode(parent); //span需要特殊处理 不处理这样的情况 <span stlye="color:#fff">xxx<span style="color:#ccc">xxx</span>xxx</span> if (parent.tagName == 'SPAN' && !domUtils.isSameStyle(parent, node) || (parent.tagName == 'A' && node.tagName == 'SPAN')) { if (parent.childNodes.length > 1 || parent !== node.parentNode) { node.style.cssText = parent.style.cssText + ";" + node.style.cssText; parent = parent.parentNode; continue; } else { parent.style.cssText += ";" + node.style.cssText; //trace:952 a标签要保持下划线 if (parent.tagName == 'A') { parent.style.textDecoration = 'underline'; } } } if (parent.tagName != 'A') { parent === node.parentNode && domUtils.remove(node, true); break; } } parent = parent.parentNode; } }, /** * 合并节点node的左右兄弟节点 * @name mergeSibling * @grammar UE.dom.domUtils.mergeSibling(node) * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre) //ignorePre指定是否忽略左兄弟 * @grammar UE.dom.domUtils.mergeSibling(node,ignorePre,ignoreNext) //ignoreNext指定是否忽略右兄弟 * @example * <b>xxxx</b><b>ooo</b><b>xxxx</b> ==> <b>xxxxoooxxxx</b> */ mergeSibling:function (node, ignorePre, ignoreNext) { function merge(rtl, start, node) { var next; if ((next = node[rtl]) && !domUtils.isBookmarkNode(next) && next.nodeType == 1 && domUtils.isSameElement(node, next)) { while (next.firstChild) { if (start == 'firstChild') { node.insertBefore(next.lastChild, node.firstChild); } else { node.appendChild(next.firstChild); } } domUtils.remove(next); } } !ignorePre && merge('previousSibling', 'firstChild', node); !ignoreNext && merge('nextSibling', 'lastChild', node); }, /** * 设置节点node及其子节点不会被选中 * @name unSelectable * @grammar UE.dom.domUtils.unSelectable(node) */ unSelectable:ie || browser.opera ? function (node) { //for ie9 node.onselectstart = function () { return false; }; node.onclick = node.onkeyup = node.onkeydown = function () { return false; }; node.unselectable = 'on'; node.setAttribute("unselectable", "on"); for (var i = 0, ci; ci = node.all[i++];) { switch (ci.tagName.toLowerCase()) { case 'iframe' : case 'textarea' : case 'input' : case 'select' : break; default : ci.unselectable = 'on'; node.setAttribute("unselectable", "on"); } } } : function (node) { node.style.MozUserSelect = node.style.webkitUserSelect = node.style.KhtmlUserSelect = 'none'; }, /** * 删除节点node上的属性attrNames,attrNames为属性名称数组 * @name removeAttributes * @grammar UE.dom.domUtils.removeAttributes(node,attrNames) * @example * //Before remove * <span style="font-size:14px;" id="test" name="followMe">xxxxx</span> * //Remove * UE.dom.domUtils.removeAttributes(node,["id","name"]); * //After remove * <span style="font-size:14px;">xxxxx</span> */ removeAttributes:function (node, attrNames) { attrNames = utils.isArray(attrNames) ? attrNames : utils.trim(attrNames).replace(/[ ]{2,}/g,' ').split(' '); for (var i = 0, ci; ci = attrNames[i++];) { ci = attrFix[ci] || ci; switch (ci) { case 'className': node[ci] = ''; break; case 'style': node.style.cssText = ''; !browser.ie && node.removeAttributeNode(node.getAttributeNode('style')) } node.removeAttribute(ci); } }, /** * 在doc下创建一个标签名为tag,属性为attrs的元素 * @name createElement * @grammar UE.dom.domUtils.createElement(doc,tag,attrs) => Node //返回创建的节点 */ createElement:function (doc, tag, attrs) { return domUtils.setAttributes(doc.createElement(tag), attrs) }, /** * 为节点node添加属性attrs,attrs为属性键值对 * @name setAttributes * @grammar UE.dom.domUtils.setAttributes(node,attrs) => node */ setAttributes:function (node, attrs) { for (var attr in attrs) { if(attrs.hasOwnProperty(attr)){ var value = attrs[attr]; switch (attr) { case 'class': //ie下要这样赋值,setAttribute不起作用 node.className = value; break; case 'style' : node.style.cssText = node.style.cssText + ";" + value; break; case 'innerHTML': node[attr] = value; break; case 'value': node.value = value; break; default: node.setAttribute(attrFix[attr] || attr, value); } } } return node; }, /** * 获取元素element的计算样式 * @name getComputedStyle * @grammar UE.dom.domUtils.getComputedStyle(element,styleName) => String //返回对应样式名称的样式值 * @example * getComputedStyle(document.body,"font-size") => "15px" * getComputedStyle(form,"color") => "#ffccdd" */ getComputedStyle:function (element, styleName) { //一下的属性单独处理 var pros = 'width height top left'; if(pros.indexOf(styleName) > -1){ return element['offset' + styleName.replace(/^\w/,function(s){return s.toUpperCase()})] + 'px'; } //忽略文本节点 if (element.nodeType == 3) { element = element.parentNode; } //ie下font-size若body下定义了font-size,则从currentStyle里会取到这个font-size. 取不到实际值,故此修改. if (browser.ie && browser.version < 9 && styleName == 'font-size' && !element.style.fontSize && !dtd.$empty[element.tagName] && !dtd.$nonChild[element.tagName]) { var span = element.ownerDocument.createElement('span'); span.style.cssText = 'padding:0;border:0;font-family:simsun;'; span.innerHTML = '.'; element.appendChild(span); var result = span.offsetHeight; element.removeChild(span); span = null; return result + 'px'; } try { var value = domUtils.getStyle(element, styleName) || (window.getComputedStyle ? domUtils.getWindow(element).getComputedStyle(element, '').getPropertyValue(styleName) : ( element.currentStyle || element.style )[utils.cssStyleToDomStyle(styleName)]); } catch (e) { return ""; } return utils.transUnitToPx(utils.fixColor(styleName, value)); }, /** * 在元素element上删除classNames,支持同时删除多个 * @name removeClasses * @grammar UE.dom.domUtils.removeClasses(element,classNames) * @example * //执行方法前的dom结构 * <span class="test1 test2 test3">xxx</span> * //执行方法 * UE.dom.domUtils.removeClasses(element,["test1","test3"]) * //执行方法后的dom结构 * <span class="test2">xxx</span> */ removeClasses:function (elm, classNames) { classNames = utils.isArray(classNames) ? classNames : utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){ cls = cls.replace(new RegExp('\\b' + ci + '\\b'),'') } cls = utils.trim(cls).replace(/[ ]{2,}/g,' '); if(cls){ elm.className = cls; }else{ domUtils.removeAttributes(elm,['class']); } }, /** * 在元素element上增加一个样式类className,支持以空格分开的多个类名 * 如果相同的类名将不会添加 * @name addClass * @grammar UE.dom.domUtils.addClass(element,classNames) */ addClass:function (elm, classNames) { if(!elm)return; classNames = utils.trim(classNames).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = elm.className;ci=classNames[i++];){ if(!new RegExp('\\b' + ci + '\\b').test(cls)){ elm.className += ' ' + ci; } } }, /** * 判断元素element是否包含样式类名className,支持以空格分开的多个类名,多个类名顺序不同也可以比较 * @name hasClass * @grammar UE.dom.domUtils.hasClass(element,className) =>true|false */ hasClass:function (element, className) { if(utils.isRegExp(className)){ return className.test(element.className) } className = utils.trim(className).replace(/[ ]{2,}/g,' ').split(' '); for(var i = 0,ci,cls = element.className;ci=className[i++];){ if(!new RegExp('\\b' + ci + '\\b','i').test(cls)){ return false; } } return i - 1 == className.length; }, /** * 阻止事件默认行为 * @param {Event} evt 需要组织的事件对象 */ preventDefault:function (evt) { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); }, /** * 删除元素element的样式 * @grammar UE.dom.domUtils.removeStyle(element,name) 删除的样式名称 */ removeStyle:function (element, name) { if(browser.ie ){ //针对color先单独处理一下 if(name == 'color'){ name = '(^|;)' + name; } element.style.cssText = element.style.cssText.replace(new RegExp(name + '[^:]*:[^;]+;?','ig'),'') }else{ if (element.style.removeProperty) { element.style.removeProperty (name); }else { element.style.removeAttribute (utils.cssStyleToDomStyle(name)); } } if (!element.style.cssText) { domUtils.removeAttributes(element, ['style']); } }, /** * 获取元素element的某个样式值 * @name getStyle * @grammar UE.dom.domUtils.getStyle(element,name) => String */ getStyle:function (element, name) { var value = element.style[ utils.cssStyleToDomStyle(name) ]; return utils.fixColor(name, value); }, /** * 为元素element设置样式属性值 * @name setStyle * @grammar UE.dom.domUtils.setStyle(element,name,value) */ setStyle:function (element, name, value) { element.style[utils.cssStyleToDomStyle(name)] = value; if(!utils.trim(element.style.cssText)){ this.removeAttributes(element,'style') } }, /** * 为元素element设置样式属性值 * @name setStyles * @grammar UE.dom.domUtils.setStyle(element,styles) //styles为样式键值对 */ setStyles:function (element, styles) { for (var name in styles) { if (styles.hasOwnProperty(name)) { domUtils.setStyle(element, name, styles[name]); } } }, /** * 删除_moz_dirty属性 * @function */ removeDirtyAttr:function (node) { for (var i = 0, ci, nodes = node.getElementsByTagName('*'); ci = nodes[i++];) { ci.removeAttribute('_moz_dirty'); } node.removeAttribute('_moz_dirty'); }, /** * 返回子节点的数量 * @function * @param {Node} node 父节点 * @param {Function} fn 过滤子节点的规则,若为空,则得到所有子节点的数量 * @return {Number} 符合条件子节点的数量 */ getChildCount:function (node, fn) { var count = 0, first = node.firstChild; fn = fn || function () { return 1; }; while (first) { if (fn(first)) { count++; } first = first.nextSibling; } return count; }, /** * 判断是否为空节点 * @function * @param {Node} node 节点 * @return {Boolean} 是否为空节点 */ isEmptyNode:function (node) { return !node.firstChild || domUtils.getChildCount(node, function (node) { return !domUtils.isBr(node) && !domUtils.isBookmarkNode(node) && !domUtils.isWhitespace(node) }) == 0 }, /** * 清空节点所有的className * @function * @param {Array} nodes 节点数组 */ clearSelectedArr:function (nodes) { var node; while (node = nodes.pop()) { domUtils.removeAttributes(node, ['class']); } }, /** * 将显示区域滚动到显示节点的位置 * @function * @param {Node} node 节点 * @param {window} win window对象 * @param {Number} offsetTop 距离上方的偏移量 */ scrollToView:function (node, win, offsetTop) { var getViewPaneSize = function () { var doc = win.document, mode = doc.compatMode == 'CSS1Compat'; return { width:( mode ? doc.documentElement.clientWidth : doc.body.clientWidth ) || 0, height:( mode ? doc.documentElement.clientHeight : doc.body.clientHeight ) || 0 }; }, getScrollPosition = function (win) { if ('pageXOffset' in win) { return { x:win.pageXOffset || 0, y:win.pageYOffset || 0 }; } else { var doc = win.document; return { x:doc.documentElement.scrollLeft || doc.body.scrollLeft || 0, y:doc.documentElement.scrollTop || doc.body.scrollTop || 0 }; } }; var winHeight = getViewPaneSize().height, offset = winHeight * -1 + offsetTop; offset += (node.offsetHeight || 0); var elementPosition = domUtils.getXY(node); offset += elementPosition.y; var currentScroll = getScrollPosition(win).y; // offset += 50; if (offset > currentScroll || offset < currentScroll - winHeight) { win.scrollTo(0, offset + (offset < 0 ? -20 : 20)); } }, /** * 判断节点是否为br * @function * @param {Node} node 节点 */ isBr:function (node) { return node.nodeType == 1 && node.tagName == 'BR'; }, isFillChar:function (node,isInStart) { return node.nodeType == 3 && !node.nodeValue.replace(new RegExp((isInStart ? '^' : '' ) + domUtils.fillChar), '').length }, isStartInblock:function (range) { var tmpRange = range.cloneRange(), flag = 0, start = tmpRange.startContainer, tmp; if(start.nodeType == 1 && start.childNodes[tmpRange.startOffset]){ start = start.childNodes[tmpRange.startOffset]; var pre = start.previousSibling; while(pre && domUtils.isFillChar(pre)){ start = pre; pre = pre.previousSibling; } } if(this.isFillChar(start,true) && tmpRange.startOffset == 1){ tmpRange.setStartBefore(start); start = tmpRange.startContainer; } while (start && domUtils.isFillChar(start)) { tmp = start; start = start.previousSibling } if (tmp) { tmpRange.setStartBefore(tmp); start = tmpRange.startContainer; } if (start.nodeType == 1 && domUtils.isEmptyNode(start) && tmpRange.startOffset == 1) { tmpRange.setStart(start, 0).collapse(true); } while (!tmpRange.startOffset) { start = tmpRange.startContainer; if (domUtils.isBlockElm(start) || domUtils.isBody(start)) { flag = 1; break; } var pre = tmpRange.startContainer.previousSibling, tmpNode; if (!pre) { tmpRange.setStartBefore(tmpRange.startContainer); } else { while (pre && domUtils.isFillChar(pre)) { tmpNode = pre; pre = pre.previousSibling; } if (tmpNode) { tmpRange.setStartBefore(tmpNode); } else { tmpRange.setStartBefore(tmpRange.startContainer); } } } return flag && !domUtils.isBody(tmpRange.startContainer) ? 1 : 0; }, isEmptyBlock:function (node,reg) { if(node.nodeType != 1) return 0; reg = reg || new RegExp('[ \t\r\n' + domUtils.fillChar + ']', 'g'); if (node[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').length > 0) { return 0; } for (var n in dtd.$isNotEmpty) { if (node.getElementsByTagName(n).length) { return 0; } } return 1; }, setViewportOffset:function (element, offset) { var left = parseInt(element.style.left) | 0; var top = parseInt(element.style.top) | 0; var rect = element.getBoundingClientRect(); var offsetLeft = offset.left - rect.left; var offsetTop = offset.top - rect.top; if (offsetLeft) { element.style.left = left + offsetLeft + 'px'; } if (offsetTop) { element.style.top = top + offsetTop + 'px'; } }, fillNode:function (doc, node) { var tmpNode = browser.ie ? doc.createTextNode(domUtils.fillChar) : doc.createElement('br'); node.innerHTML = ''; node.appendChild(tmpNode); }, moveChild:function (src, tag, dir) { while (src.firstChild) { if (dir && tag.firstChild) { tag.insertBefore(src.lastChild, tag.firstChild); } else { tag.appendChild(src.firstChild); } } }, //判断是否有额外属性 hasNoAttributes:function (node) { return browser.ie ? /^<\w+\s*?>/.test(node.outerHTML) : node.attributes.length == 0; }, //判断是否是编辑器自定义的参数 isCustomeNode:function (node) { return node.nodeType == 1 && node.getAttribute('_ue_custom_node_'); }, isTagNode:function (node, tagName) { return node.nodeType == 1 && new RegExp('^' + node.tagName + '$','i').test(tagName) }, /** * 对于nodelist用filter进行过滤 * @name filterNodeList * @since 1.2.4+ * @grammar UE.dom.domUtils.filterNodeList(nodelist,filter,onlyFirst) => 节点 * @example * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'div p') //返回第一个是div或者p的节点 * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),function(n){return n.getAttribute('src')}) * //返回第一个带src属性的节点 * UE.dom.domUtils.filterNodeList(document.getElementsByTagName('*'),'i',true) //返回数组,里边都是i节点 */ filterNodeList : function(nodelist,filter,forAll){ var results = []; if(!utils .isFunction(filter)){ var str = filter; filter = function(n){ return utils.indexOf(utils.isArray(str) ? str:str.split(' '), n.tagName.toLowerCase()) != -1 }; } utils.each(nodelist,function(n){ filter(n) && results.push(n) }); return results.length == 0 ? null : results.length == 1 || !forAll ? results[0] : results }, isInNodeEndBoundary : function (rng,node){ var start = rng.startContainer; if(start.nodeType == 3 && rng.startOffset != start.nodeValue.length){ return 0; } if(start.nodeType == 1 && rng.startOffset != start.childNodes.length){ return 0; } while(start !== node){ if(start.nextSibling){ return 0 }; start = start.parentNode; } return 1; }, isBoundaryNode : function (node,dir){ var tmp; while(!domUtils.isBody(node)){ tmp = node; node = node.parentNode; if(tmp !== node[dir]){ return false; } } return true; } }; var fillCharReg = new RegExp(domUtils.fillChar, 'g');///import editor.js ///import core/utils.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js /** * @file * @name UE.dom.Range * @anthor zhanyi * @short Range * @import editor.js,core/utils.js,core/browser.js,core/dom/domUtils.js,core/dom/dtd.js * @desc Range范围实现类,本类是UEditor底层核心类,统一w3cRange和ieRange之间的差异,包括接口和属性 */ (function () { var guid = 0, fillChar = domUtils.fillChar, fillData; /** * 更新range的collapse状态 * @param {Range} range range对象 */ function updateCollapse(range) { range.collapsed = range.startContainer && range.endContainer && range.startContainer === range.endContainer && range.startOffset == range.endOffset; } function selectOneNode(rng){ return !rng.collapsed && rng.startContainer.nodeType == 1 && rng.startContainer === rng.endContainer && rng.endOffset - rng.startOffset == 1 } function setEndPoint(toStart, node, offset, range) { //如果node是自闭合标签要处理 if (node.nodeType == 1 && (dtd.$empty[node.tagName] || dtd.$nonChild[node.tagName])) { offset = domUtils.getNodeIndex(node) + (toStart ? 0 : 1); node = node.parentNode; } if (toStart) { range.startContainer = node; range.startOffset = offset; if (!range.endContainer) { range.collapse(true); } } else { range.endContainer = node; range.endOffset = offset; if (!range.startContainer) { range.collapse(false); } } updateCollapse(range); return range; } function execContentsAction(range, action) { //调整边界 //range.includeBookmark(); var start = range.startContainer, end = range.endContainer, startOffset = range.startOffset, endOffset = range.endOffset, doc = range.document, frag = doc.createDocumentFragment(), tmpStart, tmpEnd; if (start.nodeType == 1) { start = start.childNodes[startOffset] || (tmpStart = start.appendChild(doc.createTextNode(''))); } if (end.nodeType == 1) { end = end.childNodes[endOffset] || (tmpEnd = end.appendChild(doc.createTextNode(''))); } if (start === end && start.nodeType == 3) { frag.appendChild(doc.createTextNode(start.substringData(startOffset, endOffset - startOffset))); //is not clone if (action) { start.deleteData(startOffset, endOffset - startOffset); range.collapse(true); } return frag; } var current, currentLevel, clone = frag, startParents = domUtils.findParents(start, true), endParents = domUtils.findParents(end, true); for (var i = 0; startParents[i] == endParents[i];) { i++; } for (var j = i, si; si = startParents[j]; j++) { current = si.nextSibling; if (si == start) { if (!tmpStart) { if (range.startContainer.nodeType == 3) { clone.appendChild(doc.createTextNode(start.nodeValue.slice(startOffset))); //is not clone if (action) { start.deleteData(startOffset, start.nodeValue.length - startOffset); } } else { clone.appendChild(!action ? start.cloneNode(true) : start); } } } else { currentLevel = si.cloneNode(false); clone.appendChild(currentLevel); } while (current) { if (current === end || current === endParents[j]) { break; } si = current.nextSibling; clone.appendChild(!action ? current.cloneNode(true) : current); current = si; } clone = currentLevel; } clone = frag; if (!startParents[i]) { clone.appendChild(startParents[i - 1].cloneNode(false)); clone = clone.firstChild; } for (var j = i, ei; ei = endParents[j]; j++) { current = ei.previousSibling; if (ei == end) { if (!tmpEnd && range.endContainer.nodeType == 3) { clone.appendChild(doc.createTextNode(end.substringData(0, endOffset))); //is not clone if (action) { end.deleteData(0, endOffset); } } } else { currentLevel = ei.cloneNode(false); clone.appendChild(currentLevel); } //如果两端同级,右边第一次已经被开始做了 if (j != i || !startParents[i]) { while (current) { if (current === start) { break; } ei = current.previousSibling; clone.insertBefore(!action ? current.cloneNode(true) : current, clone.firstChild); current = ei; } } clone = currentLevel; } if (action) { range.setStartBefore(!endParents[i] ? endParents[i - 1] : !startParents[i] ? startParents[i - 1] : endParents[i]).collapse(true); } tmpStart && domUtils.remove(tmpStart); tmpEnd && domUtils.remove(tmpEnd); return frag; } /** * @name Range * @grammar new UE.dom.Range(document) => Range 实例 * @desc 创建一个跟document绑定的空的Range实例 * - ***startContainer*** 开始边界的容器节点,可以是elementNode或者是textNode * - ***startOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符 * - ***endContainer*** 结束边界的容器节点,可以是elementNode或者是textNode * - ***endOffset*** 容器节点中的偏移量,如果是elementNode就是childNodes中的第几个,如果是textNode就是nodeValue的第几个字符 * - ***document*** 跟range关联的document对象 * - ***collapsed*** 是否是闭合状态 */ var Range = dom.Range = function (document) { var me = this; me.startContainer = me.startOffset = me.endContainer = me.endOffset = null; me.document = document; me.collapsed = true; }; /** * 删除fillData * @param doc * @param excludeNode */ function removeFillData(doc, excludeNode) { try { if (fillData && domUtils.inDoc(fillData, doc)) { if (!fillData.nodeValue.replace(fillCharReg, '').length) { var tmpNode = fillData.parentNode; domUtils.remove(fillData); while (tmpNode && domUtils.isEmptyInlineElement(tmpNode) && //safari的contains有bug (browser.safari ? !(domUtils.getPosition(tmpNode,excludeNode) & domUtils.POSITION_CONTAINS) : !tmpNode.contains(excludeNode)) ) { fillData = tmpNode.parentNode; domUtils.remove(tmpNode); tmpNode = fillData; } } else { fillData.nodeValue = fillData.nodeValue.replace(fillCharReg, ''); } } } catch (e) { } } /** * * @param node * @param dir */ function mergeSibling(node, dir) { var tmpNode; node = node[dir]; while (node && domUtils.isFillChar(node)) { tmpNode = node[dir]; domUtils.remove(node); node = tmpNode; } } Range.prototype = { /** * @name cloneContents * @grammar range.cloneContents() => DocumentFragment * @desc 克隆选中的内容到一个fragment里,如果选区是空的将返回null */ cloneContents:function () { return this.collapsed ? null : execContentsAction(this, 0); }, /** * @name deleteContents * @grammar range.deleteContents() => Range * @desc 删除当前选区范围中的所有内容并返回range实例,这时的range已经变成了闭合状态 * @example * DOM Element : * <b>x<i>x[x<i>xx]x</b> * //执行方法后 * <b>x<i>x<i>|x</b> * 注意range改变了 * range.startContainer => b * range.startOffset => 2 * range.endContainer => b * range.endOffset => 2 * range.collapsed => true */ deleteContents:function () { var txt; if (!this.collapsed) { execContentsAction(this, 1); } if (browser.webkit) { txt = this.startContainer; if (txt.nodeType == 3 && !txt.nodeValue.length) { this.setStartBefore(txt).collapse(true); domUtils.remove(txt); } } return this; }, /** * @name extractContents * @grammar range.extractContents() => DocumentFragment * @desc 将当前的内容放到一个fragment里并返回这个fragment,这时的range已经变成了闭合状态 * @example * DOM Element : * <b>x<i>x[x<i>xx]x</b> * //执行方法后 * 返回的fragment里的 dom结构是 * <i>x<i>xx * dom树上的结构是 * <b>x<i>x<i>|x</b> * 注意range改变了 * range.startContainer => b * range.startOffset => 2 * range.endContainer => b * range.endOffset => 2 * range.collapsed => true */ extractContents:function () { return this.collapsed ? null : execContentsAction(this, 2); }, /** * @name setStart * @grammar range.setStart(node,offset) => Range * @desc 设置range的开始位置位于node节点内,偏移量为offset * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符 */ setStart:function (node, offset) { return setEndPoint(true, node, offset, this); }, /** * 设置range的结束位置位于node节点,偏移量为offset * 如果node是elementNode那offset指的是childNodes中的第几个,如果是textNode那offset指的是nodeValue的第几个字符 * @name setEnd * @grammar range.setEnd(node,offset) => Range */ setEnd:function (node, offset) { return setEndPoint(false, node, offset, this); }, /** * 将Range开始位置设置到node节点之后 * @name setStartAfter * @grammar range.setStartAfter(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setStartAfter(i)后 * range.startContainer =>b * range.startOffset =>2 */ setStartAfter:function (node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node) + 1); }, /** * 将Range开始位置设置到node节点之前 * @name setStartBefore * @grammar range.setStartBefore(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setStartBefore(i)后 * range.startContainer =>b * range.startOffset =>1 */ setStartBefore:function (node) { return this.setStart(node.parentNode, domUtils.getNodeIndex(node)); }, /** * 将Range结束位置设置到node节点之后 * @name setEndAfter * @grammar range.setEndAfter(node) => Range * @example * <b>xx<i>x|x</i>x</b> * setEndAfter(i)后 * range.endContainer =>b * range.endtOffset =>2 */ setEndAfter:function (node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node) + 1); }, /** * 将Range结束位置设置到node节点之前 * @name setEndBefore * @grammar range.setEndBefore(node) => Range * @example * <b>xx<i>x|x</i>x</b> * 执行setEndBefore(i)后 * range.endContainer =>b * range.endtOffset =>1 */ setEndBefore:function (node) { return this.setEnd(node.parentNode, domUtils.getNodeIndex(node)); }, /** * 将Range开始位置设置到node节点内的开始位置 * @name setStartAtFirst * @grammar range.setStartAtFirst(node) => Range */ setStartAtFirst:function (node) { return this.setStart(node, 0); }, /** * 将Range开始位置设置到node节点内的结束位置 * @name setStartAtLast * @grammar range.setStartAtLast(node) => Range */ setStartAtLast:function (node) { return this.setStart(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length); }, /** * 将Range结束位置设置到node节点内的开始位置 * @name setEndAtFirst * @grammar range.setEndAtFirst(node) => Range */ setEndAtFirst:function (node) { return this.setEnd(node, 0); }, /** * 将Range结束位置设置到node节点内的结束位置 * @name setEndAtLast * @grammar range.setEndAtLast(node) => Range */ setEndAtLast:function (node) { return this.setEnd(node, node.nodeType == 3 ? node.nodeValue.length : node.childNodes.length); }, /** * 选中完整的指定节点,并返回包含该节点的range * @name selectNode * @grammar range.selectNode(node) => Range */ selectNode:function (node) { return this.setStartBefore(node).setEndAfter(node); }, /** * 选中node内部的所有节点,并返回对应的range * @name selectNodeContents * @grammar range.selectNodeContents(node) => Range * @example * <b>xx[x<i>xxx</i>]xxx</b> * 执行后 * <b>[xxx<i>xxx</i>xxx]</b> * range.startContainer =>b * range.startOffset =>0 * range.endContainer =>b * range.endOffset =>3 */ selectNodeContents:function (node) { return this.setStart(node, 0).setEndAtLast(node); }, /** * 克隆一个新的range对象 * @name cloneRange * @grammar range.cloneRange() => Range */ cloneRange:function () { var me = this; return new Range(me.document).setStart(me.startContainer, me.startOffset).setEnd(me.endContainer, me.endOffset); }, /** * 让选区闭合到尾部,若toStart为真,则闭合到头部 * @name collapse * @grammar range.collapse() => Range * @grammar range.collapse(true) => Range //闭合选区到头部 */ collapse:function (toStart) { var me = this; if (toStart) { me.endContainer = me.startContainer; me.endOffset = me.startOffset; } else { me.startContainer = me.endContainer; me.startOffset = me.endOffset; } me.collapsed = true; return me; }, /** * 调整range的边界,使其"收缩"到最小的位置 * @name shrinkBoundary * @grammar range.shrinkBoundary() => Range //range开始位置和结束位置都调整,参见<code><a href="#adjustmentboundary">adjustmentBoundary</a></code> * @grammar range.shrinkBoundary(true) => Range //仅调整开始位置,忽略结束位置 * @example * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx] * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx]</b><i>xxx</i> * [<b><i>xxxx</i>xxxxxxx</b>] ==> <b><i>[xxxx</i>xxxxxxx]</b> */ shrinkBoundary:function (ignoreEnd) { var me = this, child, collapsed = me.collapsed; function check(node){ return node.nodeType == 1 && !domUtils.isBookmarkNode(node) && !dtd.$empty[node.tagName] && !dtd.$nonChild[node.tagName] } while (me.startContainer.nodeType == 1 //是element && (child = me.startContainer.childNodes[me.startOffset]) //子节点也是element && check(child)) { me.setStart(child, 0); } if (collapsed) { return me.collapse(true); } if (!ignoreEnd) { while (me.endContainer.nodeType == 1//是element && me.endOffset > 0 //如果是空元素就退出 endOffset=0那么endOffst-1为负值,childNodes[endOffset]报错 && (child = me.endContainer.childNodes[me.endOffset - 1]) //子节点也是element && check(child)) { me.setEnd(child, child.childNodes.length); } } return me; }, /** * 获取当前range所在位置的公共祖先节点,当前range位置可以位于文本节点内,也可以包含整个元素节点,也可以位于两个节点之间 * @name getCommonAncestor * @grammar range.getCommonAncestor([includeSelf, ignoreTextNode]) => Element * @example * <b>xx[xx<i>xx]x</i>xxx</b> ==>getCommonAncestor() ==> b * <b>[<img/>]</b> * range.startContainer ==> b * range.startOffset ==> 0 * range.endContainer ==> b * range.endOffset ==> 1 * range.getCommonAncestor() ==> b * range.getCommonAncestor(true) ==> img * <b>xxx|xx</b> * range.startContainer ==> textNode * range.startOffset ==> 3 * range.endContainer ==> textNode * range.endOffset ==> 3 * range.getCommonAncestor() ==> textNode * range.getCommonAncestor(null,true) ==> b */ getCommonAncestor:function (includeSelf, ignoreTextNode) { var me = this, start = me.startContainer, end = me.endContainer; if (start === end) { if (includeSelf && selectOneNode(this)) { start = start.childNodes[me.startOffset]; if(start.nodeType == 1) return start; } //只有在上来就相等的情况下才会出现是文本的情况 return ignoreTextNode && start.nodeType == 3 ? start.parentNode : start; } return domUtils.getCommonAncestor(start, end); }, /** * 调整边界容器,如果是textNode,就调整到elementNode上 * @name trimBoundary * @grammar range.trimBoundary([ignoreEnd]) => Range //true忽略结束边界 * @example * DOM Element : * <b>|xxx</b> * startContainer = xxx; startOffset = 0 * //执行后本方法后 * startContainer = <b>; startOffset = 0 * @example * Dom Element : * <b>xx|x</b> * startContainer = xxx; startOffset = 2 * //执行本方法后,xxx被实实在在地切分成两个TextNode * startContainer = <b>; startOffset = 1 */ trimBoundary:function (ignoreEnd) { this.txtToElmBoundary(); var start = this.startContainer, offset = this.startOffset, collapsed = this.collapsed, end = this.endContainer; if (start.nodeType == 3) { if (offset == 0) { this.setStartBefore(start); } else { if (offset >= start.nodeValue.length) { this.setStartAfter(start); } else { var textNode = domUtils.split(start, offset); //跟新结束边界 if (start === end) { this.setEnd(textNode, this.endOffset - offset); } else if (start.parentNode === end) { this.endOffset += 1; } this.setStartBefore(textNode); } } if (collapsed) { return this.collapse(true); } } if (!ignoreEnd) { offset = this.endOffset; end = this.endContainer; if (end.nodeType == 3) { if (offset == 0) { this.setEndBefore(end); } else { offset < end.nodeValue.length && domUtils.split(end, offset); this.setEndAfter(end); } } } return this; }, /** * 如果选区在文本的边界上,就扩展选区到文本的父节点上 * @name txtToElmBoundary * @example * Dom Element : * <b> |xxx</b> * startContainer = xxx; startOffset = 0 * //本方法执行后 * startContainer = <b>; startOffset = 0 * @example * Dom Element : * <b> xxx| </b> * startContainer = xxx; startOffset = 3 * //本方法执行后 * startContainer = <b>; startOffset = 1 */ txtToElmBoundary:function (ignoreCollapsed) { function adjust(r, c) { var container = r[c + 'Container'], offset = r[c + 'Offset']; if (container.nodeType == 3) { if (!offset) { r['set' + c.replace(/(\w)/, function (a) { return a.toUpperCase(); }) + 'Before'](container); } else if (offset >= container.nodeValue.length) { r['set' + c.replace(/(\w)/, function (a) { return a.toUpperCase(); }) + 'After' ](container); } } } if (ignoreCollapsed || !this.collapsed) { adjust(this, 'start'); adjust(this, 'end'); } return this; }, /** * 在当前选区的开始位置前插入一个节点或者fragment,range的开始位置会在插入节点的前边 * @name insertNode * @grammar range.insertNode(node) => Range //node可以是textNode,elementNode,fragment * @example * Range : * xxx[x<p>xxxx</p>xxxx]x<p>sdfsdf</p> * 待插入Node : * <p>ssss</p> * 执行本方法后的Range : * xxx[<p>ssss</p>x<p>xxxx</p>xxxx]x<p>sdfsdf</p> */ insertNode:function (node) { var first = node, length = 1; if (node.nodeType == 11) { first = node.firstChild; length = node.childNodes.length; } this.trimBoundary(true); var start = this.startContainer, offset = this.startOffset; var nextNode = start.childNodes[ offset ]; if (nextNode) { start.insertBefore(node, nextNode); } else { start.appendChild(node); } if (first.parentNode === this.endContainer) { this.endOffset = this.endOffset + length; } return this.setStartBefore(first); }, /** * 设置光标闭合位置,toEnd设置为true时光标将闭合到选区的结尾 * @name setCursor * @grammar range.setCursor([toEnd]) => Range //toEnd为true时,光标闭合到选区的末尾 */ setCursor:function (toEnd, noFillData) { return this.collapse(!toEnd).select(noFillData); }, /** * 创建当前range的一个书签,记录下当前range的位置,方便当dom树改变时,还能找回原来的选区位置 * @name createBookmark * @grammar range.createBookmark([serialize]) => Object //{start:开始标记,end:结束标记,id:serialize} serialize为真时,开始结束标记是插入节点的id,否则是插入节点的引用 */ createBookmark:function (serialize, same) { var endNode, startNode = this.document.createElement('span'); startNode.style.cssText = 'display:none;line-height:0px;'; startNode.appendChild(this.document.createTextNode('\u200D')); startNode.id = '_baidu_bookmark_start_' + (same ? '' : guid++); if (!this.collapsed) { endNode = startNode.cloneNode(true); endNode.id = '_baidu_bookmark_end_' + (same ? '' : guid++); } this.insertNode(startNode); if (endNode) { this.collapse().insertNode(endNode).setEndBefore(endNode); } this.setStartAfter(startNode); return { start:serialize ? startNode.id : startNode, end:endNode ? serialize ? endNode.id : endNode : null, id:serialize } }, /** * 移动边界到书签位置,并删除插入的书签节点 * @name moveToBookmark * @grammar range.moveToBookmark(bookmark) => Range //让当前的range选到给定bookmark的位置,bookmark对象是由range.createBookmark创建的 */ moveToBookmark:function (bookmark) { var start = bookmark.id ? this.document.getElementById(bookmark.start) : bookmark.start, end = bookmark.end && bookmark.id ? this.document.getElementById(bookmark.end) : bookmark.end; this.setStartBefore(start); domUtils.remove(start); if (end) { this.setEndBefore(end); domUtils.remove(end); } else { this.collapse(true); } return this; }, /** * 调整range的边界,使其"放大"到最近的父block节点 * @name enlarge * @grammar range.enlarge() => Range * @example * <p><span>xxx</span><b>x[x</b>xxxxx]</p><p>xxx</p> ==> [<p><span>xxx</span><b>xx</b>xxxxx</p>]<p>xxx</p> */ enlarge:function (toBlock, stopFn) { var isBody = domUtils.isBody, pre, node, tmp = this.document.createTextNode(''); if (toBlock) { node = this.startContainer; if (node.nodeType == 1) { if (node.childNodes[this.startOffset]) { pre = node = node.childNodes[this.startOffset] } else { node.appendChild(tmp); pre = node = tmp; } } else { pre = node; } while (1) { if (domUtils.isBlockElm(node)) { node = pre; while ((pre = node.previousSibling) && !domUtils.isBlockElm(pre)) { node = pre; } this.setStartBefore(node); break; } pre = node; node = node.parentNode; } node = this.endContainer; if (node.nodeType == 1) { if (pre = node.childNodes[this.endOffset]) { node.insertBefore(tmp, pre); } else { node.appendChild(tmp); } pre = node = tmp; } else { pre = node; } while (1) { if (domUtils.isBlockElm(node)) { node = pre; while ((pre = node.nextSibling) && !domUtils.isBlockElm(pre)) { node = pre; } this.setEndAfter(node); break; } pre = node; node = node.parentNode; } if (tmp.parentNode === this.endContainer) { this.endOffset--; } domUtils.remove(tmp); } // 扩展边界到最大 if (!this.collapsed) { while (this.startOffset == 0) { if (stopFn && stopFn(this.startContainer)) { break; } if (isBody(this.startContainer)) { break; } this.setStartBefore(this.startContainer); } while (this.endOffset == (this.endContainer.nodeType == 1 ? this.endContainer.childNodes.length : this.endContainer.nodeValue.length)) { if (stopFn && stopFn(this.endContainer)) { break; } if (isBody(this.endContainer)) { break; } this.setEndAfter(this.endContainer); } } return this; }, /** * 调整Range的边界,使其"缩小"到最合适的位置 * @name adjustmentBoundary * @grammar range.adjustmentBoundary() => Range //参见<code><a href="#shrinkboundary">shrinkBoundary</a></code> * @example * <b>xx[</b>xxxxx] ==> <b>xx</b>[xxxxx] * <b>x[xx</b><i>]xxx</i> ==> <b>x[xx</b>]<i>xxx</i> */ adjustmentBoundary:function () { if (!this.collapsed) { while (!domUtils.isBody(this.startContainer) && this.startOffset == this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length && this.startContainer[this.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { this.setStartAfter(this.startContainer); } while (!domUtils.isBody(this.endContainer) && !this.endOffset && this.endContainer[this.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { this.setEndBefore(this.endContainer); } } return this; }, /** * 给range选区中的内容添加给定的标签,主要用于inline标签 * @name applyInlineStyle * @grammar range.applyInlineStyle(tagName) => Range //tagName为需要添加的样式标签名 * @grammar range.applyInlineStyle(tagName,attrs) => Range //attrs为属性json对象 * @desc * <code type="html"><p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong") ==> <p>xxxx[<strong>xxxx</strong>]x</p> * <p>xx[dd<strong>yyyy</strong>]x</p> ==> range.applyInlineStyle("strong") ==> <p>xx[<strong>ddyyyy</strong>]x</p> * <p>xxxx[xxxx]x</p> ==> range.applyInlineStyle("strong",{"style":"font-size:12px"}) ==> <p>xxxx[<strong style="font-size:12px">xxxx</strong>]x</p></code> */ applyInlineStyle:function (tagName, attrs, list) { if (this.collapsed)return this; this.trimBoundary().enlarge(false, function (node) { return node.nodeType == 1 && domUtils.isBlockElm(node) }).adjustmentBoundary(); var bookmark = this.createBookmark(), end = bookmark.end, filterFn = function (node) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node); }, current = domUtils.getNextDomNode(bookmark.start, false, filterFn), node, pre, range = this.cloneRange(); while (current && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) { if (current.nodeType == 3 || dtd[tagName][current.tagName]) { range.setStartBefore(current); node = current; while (node && (node.nodeType == 3 || dtd[tagName][node.tagName]) && node !== end) { pre = node; node = domUtils.getNextDomNode(node, node.nodeType == 1, null, function (parent) { return dtd[tagName][parent.tagName]; }); } var frag = range.setEndAfter(pre).extractContents(), elm; if (list && list.length > 0) { var level, top; top = level = list[0].cloneNode(false); for (var i = 1, ci; ci = list[i++];) { level.appendChild(ci.cloneNode(false)); level = level.firstChild; } elm = level; } else { elm = range.document.createElement(tagName); } if (attrs) { domUtils.setAttributes(elm, attrs); } elm.appendChild(frag); range.insertNode(list ? top : elm); //处理下滑线在a上的情况 var aNode; if (tagName == 'span' && attrs.style && /text\-decoration/.test(attrs.style) && (aNode = domUtils.findParentByTagName(elm, 'a', true))) { domUtils.setAttributes(aNode, attrs); domUtils.remove(elm, true); elm = aNode; } else { domUtils.mergeSibling(elm); domUtils.clearEmptySibling(elm); } //去除子节点相同的 domUtils.mergeChild(elm, attrs); current = domUtils.getNextDomNode(elm, false, filterFn); domUtils.mergeToParent(elm); if (node === end) { break; } } else { current = domUtils.getNextDomNode(current, true, filterFn); } } return this.moveToBookmark(bookmark); }, /** * 对当前range选中的节点,去掉给定的标签节点,但标签中的内容保留,主要用于处理inline元素 * @name removeInlineStyle * @grammar range.removeInlineStyle(tagNames) => Range //tagNames 为需要去掉的样式标签名,支持"b"或者["b","i","u"] * @desc * <code type="html">xx[x<span>xxx<em>yyy</em>zz]z</span> => range.removeInlineStyle(["em"]) => xx[x<span>xxxyyyzz]z</span></code> */ removeInlineStyle:function (tagNames) { if (this.collapsed)return this; tagNames = utils.isArray(tagNames) ? tagNames : [tagNames]; this.shrinkBoundary().adjustmentBoundary(); var start = this.startContainer, end = this.endContainer; while (1) { if (start.nodeType == 1) { if (utils.indexOf(tagNames, start.tagName.toLowerCase()) > -1) { break; } if (start.tagName.toLowerCase() == 'body') { start = null; break; } } start = start.parentNode; } while (1) { if (end.nodeType == 1) { if (utils.indexOf(tagNames, end.tagName.toLowerCase()) > -1) { break; } if (end.tagName.toLowerCase() == 'body') { end = null; break; } } end = end.parentNode; } var bookmark = this.createBookmark(), frag, tmpRange; if (start) { tmpRange = this.cloneRange().setEndBefore(bookmark.start).setStartBefore(start); frag = tmpRange.extractContents(); tmpRange.insertNode(frag); domUtils.clearEmptySibling(start, true); start.parentNode.insertBefore(bookmark.start, start); } if (end) { tmpRange = this.cloneRange().setStartAfter(bookmark.end).setEndAfter(end); frag = tmpRange.extractContents(); tmpRange.insertNode(frag); domUtils.clearEmptySibling(end, false, true); end.parentNode.insertBefore(bookmark.end, end.nextSibling); } var current = domUtils.getNextDomNode(bookmark.start, false, function (node) { return node.nodeType == 1; }), next; while (current && current !== bookmark.end) { next = domUtils.getNextDomNode(current, true, function (node) { return node.nodeType == 1; }); if (utils.indexOf(tagNames, current.tagName.toLowerCase()) > -1) { domUtils.remove(current, true); } current = next; } return this.moveToBookmark(bookmark); }, /** * 得到一个自闭合的节点,常用于获取自闭和的节点,例如图片节点 * @name getClosedNode * @grammar range.getClosedNode() => node|null * @example * <b>xxxx[<img />]xxx</b> */ getClosedNode:function () { var node; if (!this.collapsed) { var range = this.cloneRange().adjustmentBoundary().shrinkBoundary(); if (selectOneNode(range)) { var child = range.startContainer.childNodes[range.startOffset]; if (child && child.nodeType == 1 && (dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName])) { node = child; } } } return node; }, /** * 根据当前range选中内容节点(在页面上表现为反白显示) * @name select * @grammar range.select(); => Range */ select:browser.ie ? function (noFillData, textRange) { var nativeRange; if (!this.collapsed) this.shrinkBoundary(); var node = this.getClosedNode(); if (node && !textRange) { try { nativeRange = this.document.body.createControlRange(); nativeRange.addElement(node); nativeRange.select(); } catch (e) {} return this; } var bookmark = this.createBookmark(), start = bookmark.start, end; nativeRange = this.document.body.createTextRange(); nativeRange.moveToElementText(start); nativeRange.moveStart('character', 1); if (!this.collapsed) { var nativeRangeEnd = this.document.body.createTextRange(); end = bookmark.end; nativeRangeEnd.moveToElementText(end); nativeRange.setEndPoint('EndToEnd', nativeRangeEnd); } else { if (!noFillData && this.startContainer.nodeType != 3) { //使用<span>|x<span>固定住光标 var tmpText = this.document.createTextNode(fillChar), tmp = this.document.createElement('span'); tmp.appendChild(this.document.createTextNode(fillChar)); start.parentNode.insertBefore(tmp, start); start.parentNode.insertBefore(tmpText, start); //当点b,i,u时,不能清除i上边的b removeFillData(this.document, tmpText); fillData = tmpText; mergeSibling(tmp, 'previousSibling'); mergeSibling(start, 'nextSibling'); nativeRange.moveStart('character', -1); nativeRange.collapse(true); } } this.moveToBookmark(bookmark); tmp && domUtils.remove(tmp); //IE在隐藏状态下不支持range操作,catch一下 try { nativeRange.select(); } catch (e) { } return this; } : function (notInsertFillData) { function checkOffset(rng){ function check(node,offset,dir){ if(node.nodeType == 3 && node.nodeValue.length < offset){ rng[dir + 'Offset'] = node.nodeValue.length } } check(rng.startContainer,rng.startOffset,'start'); check(rng.endContainer,rng.endOffset,'end'); } var win = domUtils.getWindow(this.document), sel = win.getSelection(), txtNode; //FF下关闭自动长高时滚动条在关闭dialog时会跳 //ff下如果不body.focus将不能定位闭合光标到编辑器内 browser.gecko ? this.document.body.focus() : win.focus(); if (sel) { sel.removeAllRanges(); // trace:870 chrome/safari后边是br对于闭合得range不能定位 所以去掉了判断 // this.startContainer.nodeType != 3 &&! ((child = this.startContainer.childNodes[this.startOffset]) && child.nodeType == 1 && child.tagName == 'BR' if (this.collapsed && !notInsertFillData) { // //opear如果没有节点接着,原生的不能够定位,不能在body的第一级插入空白节点 // if (notInsertFillData && browser.opera && !domUtils.isBody(this.startContainer) && this.startContainer.nodeType == 1) { // var tmp = this.document.createTextNode(''); // this.insertNode(tmp).setStart(tmp, 0).collapse(true); // } // //处理光标落在文本节点的情况 //处理以下的情况 //<b>|xxxx</b> //<b>xxxx</b>|xxxx //xxxx<b>|</b> var start = this.startContainer,child = start; if(start.nodeType == 1){ child = start.childNodes[this.startOffset]; } if( !(start.nodeType == 3 && this.startOffset) && (child ? (!child.previousSibling || child.previousSibling.nodeType != 3) : (!start.lastChild || start.lastChild.nodeType != 3) ) ){ txtNode = this.document.createTextNode(fillChar); //跟着前边走 this.insertNode(txtNode); removeFillData(this.document, txtNode); mergeSibling(txtNode, 'previousSibling'); mergeSibling(txtNode, 'nextSibling'); fillData = txtNode; this.setStart(txtNode, browser.webkit ? 1 : 0).collapse(true); } } var nativeRange = this.document.createRange(); if(this.collapsed && browser.opera && this.startContainer.nodeType == 1){ var child = this.startContainer.childNodes[this.startOffset]; if(!child){ //往前靠拢 child = this.startContainer.lastChild; if( child && domUtils.isBr(child)){ this.setStartBefore(child).collapse(true); } }else{ //向后靠拢 while(child && domUtils.isBlockElm(child)){ if(child.nodeType == 1 && child.childNodes[0]){ child = child.childNodes[0] }else{ break; } } child && this.setStartBefore(child).collapse(true) } } //是createAddress最后一位算的不准,现在这里进行微调 checkOffset(this); nativeRange.setStart(this.startContainer, this.startOffset); nativeRange.setEnd(this.endContainer, this.endOffset); sel.addRange(nativeRange); } return this; }, /** * 滚动条跳到当然range开始的位置 * @name scrollToView * @grammar range.scrollToView([win,offset]) => Range //针对window对象,若不指定,将以编辑区域的窗口为准,offset偏移量 */ scrollToView:function (win, offset) { win = win ? window : domUtils.getWindow(this.document); var me = this, span = me.document.createElement('span'); //trace:717 span.innerHTML = '&nbsp;'; me.cloneRange().insertNode(span); domUtils.scrollToView(span, win, offset); domUtils.remove(span); return me; }, inFillChar : function(){ var start = this.startContainer; if(this.collapsed && start.nodeType == 3 && start.nodeValue.replace(new RegExp('^' + domUtils.fillChar),'').length + 1 == start.nodeValue.length ){ return true; } return false; }, createAddress : function(ignoreEnd,ignoreTxt){ var addr = {},me = this; function getAddress(isStart){ var node = isStart ? me.startContainer : me.endContainer; var parents = domUtils.findParents(node,true,function(node){return !domUtils.isBody(node)}), addrs = []; for(var i = 0,ci;ci = parents[i++];){ addrs.push(domUtils.getNodeIndex(ci,ignoreTxt)); } var firstIndex = 0; if(ignoreTxt){ if(node.nodeType == 3){ var tmpNode = node.previousSibling; while(tmpNode && tmpNode.nodeType == 3){ firstIndex += tmpNode.nodeValue.replace(fillCharReg,'').length; tmpNode = tmpNode.previousSibling; } firstIndex += (isStart ? me.startOffset : me.endOffset)// - (fillCharReg.test(node.nodeValue) ? 1 : 0 ) }else{ node = node.childNodes[ isStart ? me.startOffset : me.endOffset]; if(node){ firstIndex = domUtils.getNodeIndex(node,ignoreTxt); }else{ node = isStart ? me.startContainer : me.endContainer; var first = node.firstChild; while(first){ if(domUtils.isFillChar(first)){ first = first.nextSibling; continue; } firstIndex++; if(first.nodeType == 3){ while( first && first.nodeType == 3){ first = first.nextSibling; } }else{ first = first.nextSibling; } } } } }else{ firstIndex = isStart ? domUtils.isFillChar(node) ? 0 : me.startOffset : me.endOffset } if(firstIndex < 0){ firstIndex = 0; } addrs.push(firstIndex); return addrs; } addr.startAddress = getAddress(true); if(!ignoreEnd){ addr.endAddress = me.collapsed ? [].concat(addr.startAddress) : getAddress(); } return addr; }, moveToAddress : function(addr,ignoreEnd){ var me = this; function getNode(address,isStart){ var tmpNode = me.document.body, parentNode,offset; for(var i= 0,ci,l=address.length;i<l;i++){ ci = address[i]; parentNode = tmpNode; tmpNode = tmpNode.childNodes[ci]; if(!tmpNode){ offset = ci; break; } } if(isStart){ if(tmpNode){ me.setStartBefore(tmpNode) }else{ me.setStart(parentNode,offset) } }else{ if(tmpNode){ me.setEndBefore(tmpNode) }else{ me.setEnd(parentNode,offset) } } } getNode(addr.startAddress,true); !ignoreEnd && addr.endAddress && getNode(addr.endAddress); return me; }, equals : function(rng){ for(var p in this){ if(this.hasOwnProperty(p)){ if(this[p] !== rng[p]) return false } } return true; }, traversal:function(doFn,filterFn){ if (this.collapsed) return this; var bookmark = this.createBookmark(), end = bookmark.end, current = domUtils.getNextDomNode(bookmark.start, false, filterFn); while (current && current !== end && (domUtils.getPosition(current, end) & domUtils.POSITION_PRECEDING)) { var tmpNode = domUtils.getNextDomNode(current,false,filterFn); doFn(current); current = tmpNode; } return this.moveToBookmark(bookmark); } }; })();///import editor.js ///import core/browser.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/dom/domUtils.js ///import core/dom/Range.js /** * @class baidu.editor.dom.Selection Selection类 */ (function () { function getBoundaryInformation( range, start ) { var getIndex = domUtils.getNodeIndex; range = range.duplicate(); range.collapse( start ); var parent = range.parentElement(); //如果节点里没有子节点,直接退出 if ( !parent.hasChildNodes() ) { return {container:parent, offset:0}; } var siblings = parent.children, child, testRange = range.duplicate(), startIndex = 0, endIndex = siblings.length - 1, index = -1, distance; while ( startIndex <= endIndex ) { index = Math.floor( (startIndex + endIndex) / 2 ); child = siblings[index]; testRange.moveToElementText( child ); var position = testRange.compareEndPoints( 'StartToStart', range ); if ( position > 0 ) { endIndex = index - 1; } else if ( position < 0 ) { startIndex = index + 1; } else { //trace:1043 return {container:parent, offset:getIndex( child )}; } } if ( index == -1 ) { testRange.moveToElementText( parent ); testRange.setEndPoint( 'StartToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; siblings = parent.childNodes; if ( !distance ) { child = siblings[siblings.length - 1]; return {container:child, offset:child.nodeValue.length}; } var i = siblings.length; while ( distance > 0 ){ distance -= siblings[ --i ].nodeValue.length; } return {container:siblings[i], offset:-distance}; } testRange.collapse( position > 0 ); testRange.setEndPoint( position > 0 ? 'StartToStart' : 'EndToStart', range ); distance = testRange.text.replace( /(\r\n|\r)/g, '\n' ).length; if ( !distance ) { return dtd.$empty[child.tagName] || dtd.$nonChild[child.tagName] ? {container:parent, offset:getIndex( child ) + (position > 0 ? 0 : 1)} : {container:child, offset:position > 0 ? 0 : child.childNodes.length} } while ( distance > 0 ) { try { var pre = child; child = child[position > 0 ? 'previousSibling' : 'nextSibling']; distance -= child.nodeValue.length; } catch ( e ) { return {container:parent, offset:getIndex( pre )}; } } return {container:child, offset:position > 0 ? -distance : child.nodeValue.length + distance} } /** * 将ieRange转换为Range对象 * @param {Range} ieRange ieRange对象 * @param {Range} range Range对象 * @return {Range} range 返回转换后的Range对象 */ function transformIERangeToRange( ieRange, range ) { if ( ieRange.item ) { range.selectNode( ieRange.item( 0 ) ); } else { var bi = getBoundaryInformation( ieRange, true ); range.setStart( bi.container, bi.offset ); if ( ieRange.compareEndPoints( 'StartToEnd', ieRange ) != 0 ) { bi = getBoundaryInformation( ieRange, false ); range.setEnd( bi.container, bi.offset ); } } return range; } /** * 获得ieRange * @param {Selection} sel Selection对象 * @return {ieRange} 得到ieRange */ function _getIERange( sel ) { var ieRange; //ie下有可能报错 try { ieRange = sel.getNative().createRange(); } catch ( e ) { return null; } var el = ieRange.item ? ieRange.item( 0 ) : ieRange.parentElement(); if ( ( el.ownerDocument || el ) === sel.document ) { return ieRange; } return null; } var Selection = dom.Selection = function ( doc ) { var me = this, iframe; me.document = doc; if ( ie ) { iframe = domUtils.getWindow( doc ).frameElement; domUtils.on( iframe, 'beforedeactivate', function () { me._bakIERange = me.getIERange(); } ); domUtils.on( iframe, 'activate', function () { try { if ( !_getIERange( me ) && me._bakIERange ) { me._bakIERange.select(); } } catch ( ex ) { } me._bakIERange = null; } ); } iframe = doc = null; }; Selection.prototype = { /** * 获取原生seleciton对象 * @public * @function * @name baidu.editor.dom.Selection.getNative * @return {Selection} 获得selection对象 */ getNative:function () { var doc = this.document; try { return !doc ? null : ie && browser.ie < 9 ? doc.selection : domUtils.getWindow( doc ).getSelection(); } catch ( e ) { return null; } }, /** * 获得ieRange * @public * @function * @name baidu.editor.dom.Selection.getIERange * @return {ieRange} 返回ie原生的Range */ getIERange:function () { var ieRange = _getIERange( this ); if ( !ieRange ) { if ( this._bakIERange ) { return this._bakIERange; } } return ieRange; }, /** * 缓存当前选区的range和选区的开始节点 * @public * @function * @name baidu.editor.dom.Selection.cache */ cache:function () { this.clear(); this._cachedRange = this.getRange(); this._cachedStartElement = this.getStart(); this._cachedStartElementPath = this.getStartElementPath(); }, getStartElementPath:function () { if ( this._cachedStartElementPath ) { return this._cachedStartElementPath; } var start = this.getStart(); if ( start ) { return domUtils.findParents( start, true, null, true ) } return []; }, /** * 清空缓存 * @public * @function * @name baidu.editor.dom.Selection.clear */ clear:function () { this._cachedStartElementPath = this._cachedRange = this._cachedStartElement = null; }, /** * 编辑器是否得到了选区 */ isFocus:function () { try { return browser.ie && _getIERange( this ) || !browser.ie && this.getNative().rangeCount ? true : false; } catch ( e ) { return false; } }, /** * 获取选区对应的Range * @public * @function * @name baidu.editor.dom.Selection.getRange * @returns {baidu.editor.dom.Range} 得到Range对象 */ getRange:function () { var me = this; function optimze( range ) { var child = me.document.body.firstChild, collapsed = range.collapsed; while ( child && child.firstChild ) { range.setStart( child, 0 ); child = child.firstChild; } if ( !range.startContainer ) { range.setStart( me.document.body, 0 ) } if ( collapsed ) { range.collapse( true ); } } if ( me._cachedRange != null ) { return this._cachedRange; } var range = new baidu.editor.dom.Range( me.document ); if ( ie && browser.ie < 9 ) { var nativeRange = me.getIERange(); if ( nativeRange ) { //备份的_bakIERange可能已经实效了,dom树发生了变化比如从源码模式切回来,所以try一下,实效就放到body开始位置 try{ transformIERangeToRange( nativeRange, range ); }catch(e){ optimze( range ); } } else { optimze( range ); } } else { var sel = me.getNative(); if ( sel && sel.rangeCount ) { var firstRange = sel.getRangeAt( 0 ); var lastRange = sel.getRangeAt( sel.rangeCount - 1 ); range.setStart( firstRange.startContainer, firstRange.startOffset ).setEnd( lastRange.endContainer, lastRange.endOffset ); if ( range.collapsed && domUtils.isBody( range.startContainer ) && !range.startOffset ) { optimze( range ); } } else { //trace:1734 有可能已经不在dom树上了,标识的节点 if ( this._bakRange && domUtils.inDoc( this._bakRange.startContainer, this.document ) ){ return this._bakRange; } optimze( range ); } } return this._bakRange = range; }, /** * 获取开始元素,用于状态反射 * @public * @function * @name baidu.editor.dom.Selection.getStart * @return {Element} 获得开始元素 */ getStart:function () { if ( this._cachedStartElement ) { return this._cachedStartElement; } var range = ie ? this.getIERange() : this.getRange(), tmpRange, start, tmp, parent; if ( ie ) { if ( !range ) { //todo 给第一个值可能会有问题 return this.document.body.firstChild; } //control元素 if ( range.item ){ return range.item( 0 ); } tmpRange = range.duplicate(); //修正ie下<b>x</b>[xx] 闭合后 <b>x|</b>xx tmpRange.text.length > 0 && tmpRange.moveStart( 'character', 1 ); tmpRange.collapse( 1 ); start = tmpRange.parentElement(); parent = tmp = range.parentElement(); while ( tmp = tmp.parentNode ) { if ( tmp == start ) { start = parent; break; } } } else { range.shrinkBoundary(); start = range.startContainer; if ( start.nodeType == 1 && start.hasChildNodes() ){ start = start.childNodes[Math.min( start.childNodes.length - 1, range.startOffset )]; } if ( start.nodeType == 3 ){ return start.parentNode; } } return start; }, /** * 得到选区中的文本 * @public * @function * @name baidu.editor.dom.Selection.getText * @return {String} 选区中包含的文本 */ getText:function () { var nativeSel, nativeRange; if ( this.isFocus() && (nativeSel = this.getNative()) ) { nativeRange = browser.ie ? nativeSel.createRange() : nativeSel.getRangeAt( 0 ); return browser.ie ? nativeRange.text : nativeRange.toString(); } return ''; }, clearRange : function(){ this.getNative()[browser.ie ? 'empty' : 'removeAllRanges'](); } }; })();/** * @file * @name UE.Editor * @short Editor * @import editor.js,core/utils.js,core/EventBase.js,core/browser.js,core/dom/dtd.js,core/dom/domUtils.js,core/dom/Range.js,core/dom/Selection.js,plugins/serialize.js * @desc 编辑器主类,包含编辑器提供的大部分公用接口 */ (function () { var uid = 0, _selectionChangeTimer; /** * @private * @ignore * @param form 编辑器所在的form元素 * @param editor 编辑器实例对象 */ function setValue(form, editor) { var textarea; if (editor.textarea) { if (utils.isString(editor.textarea)) { for (var i = 0, ti, tis = domUtils.getElementsByTagName(form, 'textarea'); ti = tis[i++];) { if (ti.id == 'ueditor_textarea_' + editor.options.textarea) { textarea = ti; break; } } } else { textarea = editor.textarea; } } if (!textarea) { form.appendChild(textarea = domUtils.createElement(document, 'textarea', { 'name': editor.options.textarea, 'id': 'ueditor_textarea_' + editor.options.textarea, 'style': "display:none" })); //不要产生多个textarea editor.textarea = textarea; } textarea.value = editor.hasContents() ? (editor.options.allHtmlEnabled ? editor.getAllHtml() : editor.getContent(null, null, true)) : '' } function loadPlugins(me){ //初始化插件 for (var pi in UE.plugins) { UE.plugins[pi].call(me); } me.langIsReady = true; me.fireEvent("langReady"); } function checkCurLang(I18N){ for(var lang in I18N){ return lang } } /** * UEditor编辑器类 * @name Editor * @desc 创建一个跟编辑器实例 * - ***container*** 编辑器容器对象 * - ***iframe*** 编辑区域所在的iframe对象 * - ***window*** 编辑区域所在的window * - ***document*** 编辑区域所在的document对象 * - ***body*** 编辑区域所在的body对象 * - ***selection*** 编辑区域的选区对象 */ var Editor = UE.Editor = function (options) { var me = this; me.uid = uid++; EventBase.call(me); me.commands = {}; me.options = utils.extend(utils.clone(options || {}), UEDITOR_CONFIG, true); me.shortcutkeys = {}; me.inputRules = []; me.outputRules = []; //设置默认的常用属性 me.setOpt({ isShow: true, initialContent: '', initialStyle:'', autoClearinitialContent: false, iframeCssUrl: me.options.UEDITOR_HOME_URL + 'themes/iframe.css', textarea: 'editorValue', focus: false, focusInEnd: true, autoClearEmptyNode: true, fullscreen: false, readonly: false, zIndex: 999, imagePopup: true, enterTag: 'p', customDomain: false, lang: 'zh-cn', langPath: me.options.UEDITOR_HOME_URL + 'lang/', theme: 'default', themePath: me.options.UEDITOR_HOME_URL + 'themes/', allHtmlEnabled: false, scaleEnabled: false, tableNativeEditInFF: false, autoSyncData : true }); if(!utils.isEmptyObject(UE.I18N)){ //修改默认的语言类型 me.options.lang = checkCurLang(UE.I18N); loadPlugins(me) }else{ utils.loadFile(document, { src: me.options.langPath + me.options.lang + "/" + me.options.lang + ".js", tag: "script", type: "text/javascript", defer: "defer" }, function () { loadPlugins(me) }); } UE.instants['ueditorInstant' + me.uid] = me; }; Editor.prototype = { /** * 当编辑器ready后执行传入的fn,如果编辑器已经完成ready,就马上执行fn,fn的中的this是编辑器实例。 * 大部分的实例接口都需要放在该方法内部执行,否则在IE下可能会报错。 * @name ready * @grammar editor.ready(fn) fn是当编辑器渲染好后执行的function * @example * var editor = new UE.ui.Editor(); * editor.render("myEditor"); * editor.ready(function(){ * editor.setContent("欢迎使用UEditor!"); * }) */ ready: function (fn) { var me = this; if (fn) { me.isReady ? fn.apply(me) : me.addListener('ready', fn); } }, /** * 为编辑器设置默认参数值。若用户配置为空,则以默认配置为准 * @grammar editor.setOpt(key,value); //传入一个键、值对 * @grammar editor.setOpt({ key:value}); //传入一个json对象 */ setOpt: function (key, val) { var obj = {}; if (utils.isString(key)) { obj[key] = val } else { obj = key; } utils.extend(this.options, obj, true); }, /** * 销毁编辑器实例对象 * @name destroy * @grammar editor.destroy(); */ destroy: function () { var me = this; me.fireEvent('destroy'); var container = me.container.parentNode; var textarea = me.textarea; if (!textarea) { textarea = document.createElement('textarea'); container.parentNode.insertBefore(textarea, container); } else { textarea.style.display = '' } textarea.style.width = me.iframe.offsetWidth + 'px'; textarea.style.height = me.iframe.offsetHeight + 'px'; textarea.value = me.getContent(); textarea.id = me.key; container.innerHTML = ''; domUtils.remove(container); var key = me.key; //trace:2004 for (var p in me) { if (me.hasOwnProperty(p)) { delete this[p]; } } UE.delEditor(key); }, /** * 渲染编辑器的DOM到指定容器,必须且只能调用一次 * @name render * @grammar editor.render(containerId); //可以指定一个容器ID * @grammar editor.render(containerDom); //也可以直接指定容器对象 */ render: function (container) { var me = this, options = me.options, getStyleValue=function(attr){ return parseInt(domUtils.getComputedStyle(container,attr)); }; if (utils.isString(container)) { container = document.getElementById(container); } if (container) { if(options.initialFrameWidth){ options.minFrameWidth = options.initialFrameWidth }else{ options.minFrameWidth = options.initialFrameWidth = container.offsetWidth; } if(options.initialFrameHeight){ options.minFrameHeight = options.initialFrameHeight }else{ options.initialFrameHeight = options.minFrameHeight = container.offsetHeight; } container.style.width = /%$/.test(options.initialFrameWidth) ? '100%' : options.initialFrameWidth- getStyleValue("padding-left")- getStyleValue("padding-right") +'px'; container.style.height = /%$/.test(options.initialFrameHeight) ? '100%' : options.initialFrameHeight - getStyleValue("padding-top")- getStyleValue("padding-bottom") +'px'; container.style.zIndex = options.zIndex; var html = ( ie && browser.version < 9 ? '' : '<!DOCTYPE html>') + '<html xmlns=\'http://www.w3.org/1999/xhtml\' class=\'view\' ><head>' + '<style type=\'text/css\'>' + //设置四周的留边 '.view{padding:0;word-wrap:break-word;cursor:text;height:90%;}\n' + //设置默认字体和字号 //font-family不能呢随便改,在safari下fillchar会有解析问题 'body{margin:8px;font-family:sans-serif;font-size:16px;}' + //设置段落间距 'p{margin:5px 0;}</style>' + ( options.iframeCssUrl ? '<link rel=\'stylesheet\' type=\'text/css\' href=\'' + utils.unhtml(options.iframeCssUrl) + '\'/>' : '' ) + (options.initialStyle ? '<style>' + options.initialStyle + '</style>' : '') + '</head><body class=\'view\' ></body>' + '<script type=\'text/javascript\' ' + (ie ? 'defer=\'defer\'' : '' ) +' id=\'_initialScript\'>' + 'setTimeout(function(){window.parent.UE.instants[\'ueditorInstant' + me.uid + '\']._setup(document);},0);' + 'var _tmpScript = document.getElementById(\'_initialScript\');_tmpScript.parentNode.removeChild(_tmpScript);</script></html>'; container.appendChild(domUtils.createElement(document, 'iframe', { id: 'ueditor_' + me.uid, width: "100%", height: "100%", frameborder: "0", src: 'javascript:void(function(){document.open();' + (options.customDomain && document.domain != location.hostname ? 'document.domain="' + document.domain + '";' : '') + 'document.write("' + html + '");document.close();}())' })); container.style.overflow = 'hidden'; //解决如果是给定的百分比,会导致高度算不对的问题 setTimeout(function(){ if( /%$/.test(options.initialFrameWidth)){ options.minFrameWidth = options.initialFrameWidth = container.offsetWidth; container.style.width = options.initialFrameWidth + 'px'; } if(/%$/.test(options.initialFrameHeight)){ options.minFrameHeight = options.initialFrameHeight = container.offsetHeight; container.style.height = options.initialFrameHeight + 'px'; } }) } }, /** * 编辑器初始化 * @private * @ignore * @param {Element} doc 编辑器Iframe中的文档对象 */ _setup: function (doc) { var me = this, options = me.options; if (ie) { doc.body.disabled = true; doc.body.contentEditable = true; doc.body.disabled = false; } else { doc.body.contentEditable = true; } doc.body.spellcheck = false; me.document = doc; me.window = doc.defaultView || doc.parentWindow; me.iframe = me.window.frameElement; me.body = doc.body; me.selection = new dom.Selection(doc); //gecko初始化就能得到range,无法判断isFocus了 var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } this._initEvents(); //为form提交提供一个隐藏的textarea for (var form = this.iframe.parentNode; !domUtils.isBody(form); form = form.parentNode) { if (form.tagName == 'FORM') { me.form = form; if(me.options.autoSyncData){ domUtils.on(me.window,'blur',function(){ setValue(form,me); }); }else{ domUtils.on(form, 'submit', function () { setValue(this, me); }); } break; } } if (options.initialContent) { if (options.autoClearinitialContent) { var oldExecCommand = me.execCommand; me.execCommand = function () { me.fireEvent('firstBeforeExecCommand'); return oldExecCommand.apply(me, arguments); }; this._setDefaultContent(options.initialContent); } else this.setContent(options.initialContent, false, true); } //编辑器不能为空内容 if (domUtils.isEmptyNode(me.body)) { me.body.innerHTML = '<p>' + (browser.ie ? '' : '<br/>') + '</p>'; } //如果要求focus, 就把光标定位到内容开始 if (options.focus) { setTimeout(function () { me.focus(me.options.focusInEnd); //如果自动清除开着,就不需要做selectionchange; !me.options.autoClearinitialContent && me._selectionChange(); }, 0); } if (!me.container) { me.container = this.iframe.parentNode; } if (options.fullscreen && me.ui) { me.ui.setFullScreen(true); } try { me.document.execCommand('2D-position', false, false); } catch (e) { } try { me.document.execCommand('enableInlineTableEditing', false, false); } catch (e) { } try { me.document.execCommand('enableObjectResizing', false, false); } catch (e) { // domUtils.on(me.body,browser.ie ? 'resizestart' : 'resize', function( evt ) { // domUtils.preventDefault(evt) // }); } me._bindshortcutKeys(); me.isReady = 1; me.fireEvent('ready'); options.onready && options.onready.call(me); if (!browser.ie) { domUtils.on(me.window, ['blur', 'focus'], function (e) { //chrome下会出现alt+tab切换时,导致选区位置不对 if (e.type == 'blur') { me._bakRange = me.selection.getRange(); try { me._bakNativeRange = me.selection.getNative().getRangeAt(0); me.selection.getNative().removeAllRanges(); } catch (e) { me._bakNativeRange = null; } } else { try { me._bakRange && me._bakRange.select(); } catch (e) { } } }); } //trace:1518 ff3.6body不够寛,会导致点击空白处无法获得焦点 if (browser.gecko && browser.version <= 10902) { //修复ff3.6初始化进来,不能点击获得焦点 me.body.contentEditable = false; setTimeout(function () { me.body.contentEditable = true; }, 100); setInterval(function () { me.body.style.height = me.iframe.offsetHeight - 20 + 'px' }, 100) } !options.isShow && me.setHide(); options.readonly && me.setDisabled(); }, /** * 同步编辑器的数据,为提交数据做准备,主要用于你是手动提交的情况 * @name sync * @grammar editor.sync(); //从编辑器的容器向上查找,如果找到就同步数据 * @grammar editor.sync(formID); //formID制定一个要同步数据的form的id,编辑器的数据会同步到你指定form下 * @desc * 后台取得数据得键值使用你容器上得''name''属性,如果没有就使用参数传入的''textarea'' * @example * editor.sync(); * form.sumbit(); //form变量已经指向了form元素 * */ sync: function (formId) { var me = this, form = formId ? document.getElementById(formId) : domUtils.findParent(me.iframe.parentNode, function (node) { return node.tagName == 'FORM' }, true); form && setValue(form, me); }, /** * 设置编辑器高度 * @name setHeight * @grammar editor.setHeight(number); //纯数值,不带单位 */ setHeight: function (height,notSetHeight) { if (height !== parseInt(this.iframe.parentNode.style.height)) { this.iframe.parentNode.style.height = height + 'px'; } !notSetHeight && (this.options.minFrameHeight = this.options.initialFrameHeight = height); this.body.style.height = height + 'px'; }, addshortcutkey: function (cmd, keys) { var obj = {}; if (keys) { obj[cmd] = keys } else { obj = cmd; } utils.extend(this.shortcutkeys, obj) }, _bindshortcutKeys: function () { var me = this, shortcutkeys = this.shortcutkeys; me.addListener('keydown', function (type, e) { var keyCode = e.keyCode || e.which; for (var i in shortcutkeys) { var tmp = shortcutkeys[i].split(','); for (var t = 0, ti; ti = tmp[t++];) { ti = ti.split(':'); var key = ti[0], param = ti[1]; if (/^(ctrl)(\+shift)?\+(\d+)$/.test(key.toLowerCase()) || /^(\d+)$/.test(key)) { if (( (RegExp.$1 == 'ctrl' ? (e.ctrlKey || e.metaKey) : 0) && (RegExp.$2 != "" ? e[RegExp.$2.slice(1) + "Key"] : 1) && keyCode == RegExp.$3 ) || keyCode == RegExp.$1 ) { if (me.queryCommandState(i,param) != -1) me.execCommand(i, param); domUtils.preventDefault(e); } } } } }); }, /** * 获取编辑器内容 * @name getContent * @grammar editor.getContent() => String //若编辑器中只包含字符"&lt;p&gt;&lt;br /&gt;&lt;/p/&gt;"会返回空。 * @grammar editor.getContent(fn) => String * @example * getContent默认是会现调用hasContents来判断编辑器是否为空,如果是,就直接返回空字符串 * 你也可以传入一个fn来接替hasContents的工作,定制判断的规则 * editor.getContent(function(){ * return false //编辑器没有内容 ,getContent直接返回空 * }) */ getContent: function (cmd, fn,notSetCursor,ignoreBlank,formatter) { var me = this; if (cmd && utils.isFunction(cmd)) { fn = cmd; cmd = ''; } if (fn ? !fn() : !this.hasContents()) { return ''; } me.fireEvent('beforegetcontent'); var root = UE.htmlparser(me.body.innerHTML,ignoreBlank); me.filterOutputRule(root); me.fireEvent('aftergetcontent', cmd); return root.toHtml(formatter); }, /** * 取得完整的html代码,可以直接显示成完整的html文档 * @name getAllHtml * @grammar editor.getAllHtml() => String */ getAllHtml: function () { var me = this, headHtml = [], html = ''; me.fireEvent('getAllHtml', headHtml); if (browser.ie && browser.version > 8) { var headHtmlForIE9 = ''; utils.each(me.document.styleSheets, function (si) { headHtmlForIE9 += ( si.href ? '<link rel="stylesheet" type="text/css" href="' + si.href + '" />' : '<style>' + si.cssText + '</style>'); }); utils.each(me.document.getElementsByTagName('script'), function (si) { headHtmlForIE9 += si.outerHTML; }); } return '<html><head>' + (me.options.charset ? '<meta http-equiv="Content-Type" content="text/html; charset=' + me.options.charset + '"/>' : '') + (headHtmlForIE9 || me.document.getElementsByTagName('head')[0].innerHTML) + headHtml.join('\n') + '</head>' + '<body ' + (ie && browser.version < 9 ? 'class="view"' : '') + '>' + me.getContent(null, null, true) + '</body></html>'; }, /** * 得到编辑器的纯文本内容,但会保留段落格式 * @name getPlainTxt * @grammar editor.getPlainTxt() => String */ getPlainTxt: function () { var reg = new RegExp(domUtils.fillChar, 'g'), html = this.body.innerHTML.replace(/[\n\r]/g, '');//ie要先去了\n在处理 html = html.replace(/<(p|div)[^>]*>(<br\/?>|&nbsp;)<\/\1>/gi, '\n') .replace(/<br\/?>/gi, '\n') .replace(/<[^>/]+>/g, '') .replace(/(\n)?<\/([^>]+)>/g, function (a, b, c) { return dtd.$block[c] ? '\n' : b ? b : ''; }); //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0 return html.replace(reg, '').replace(/\u00a0/g, ' ').replace(/&nbsp;/g, ' '); }, /** * 获取编辑器中的纯文本内容,没有段落格式 * @name getContentTxt * @grammar editor.getContentTxt() => String */ getContentTxt: function () { var reg = new RegExp(domUtils.fillChar, 'g'); //取出来的空格会有c2a0会变成乱码,处理这种情况\u00a0 return this.body[browser.ie ? 'innerText' : 'textContent'].replace(reg, '').replace(/\u00a0/g, ' '); }, /** * 将html设置到编辑器中, 如果是用于初始化时给编辑器赋初值,则必须放在ready方法内部执行 * @name setContent * @grammar editor.setContent(html) * @example * var editor = new UE.ui.Editor() * editor.ready(function(){ * //需要ready后执行,否则可能报错 * editor.setContent("欢迎使用UEditor!"); * }) */ setContent: function (html, isAppendTo, notFireSelectionchange) { var me = this; me.fireEvent('beforesetcontent', html); var root = UE.htmlparser(html); me.filterInputRule(root); html = root.toHtml(); me.body.innerHTML = (isAppendTo ? me.body.innerHTML : '') + html; function isCdataDiv(node){ return node.tagName == 'DIV' && node.getAttribute('cdata_tag'); } //给文本或者inline节点套p标签 if (me.options.enterTag == 'p') { var child = this.body.firstChild, tmpNode; if (!child || child.nodeType == 1 && (dtd.$cdata[child.tagName] || isCdataDiv(child) || domUtils.isCustomeNode(child) ) && child === this.body.lastChild) { this.body.innerHTML = '<p>' + (browser.ie ? '&nbsp;' : '<br/>') + '</p>' + this.body.innerHTML; } else { var p = me.document.createElement('p'); while (child) { while (child && (child.nodeType == 3 || child.nodeType == 1 && dtd.p[child.tagName] && !dtd.$cdata[child.tagName])) { tmpNode = child.nextSibling; p.appendChild(child); child = tmpNode; } if (p.firstChild) { if (!child) { me.body.appendChild(p); break; } else { child.parentNode.insertBefore(p, child); p = me.document.createElement('p'); } } child = child.nextSibling; } } } me.fireEvent('aftersetcontent'); me.fireEvent('contentchange'); !notFireSelectionchange && me._selectionChange(); //清除保存的选区 me._bakRange = me._bakIERange = me._bakNativeRange = null; //trace:1742 setContent后gecko能得到焦点问题 var geckoSel; if (browser.gecko && (geckoSel = this.selection.getNative())) { geckoSel.removeAllRanges(); } if(me.options.autoSyncData){ me.form && setValue(me.form,me); } }, /** * 让编辑器获得焦点,toEnd确定focus位置 * @name focus * @grammar editor.focus([toEnd]) //默认focus到编辑器头部,toEnd为true时focus到内容尾部 */ focus: function (toEnd) { try { var me = this, rng = me.selection.getRange(); if (toEnd) { rng.setStartAtLast(me.body.lastChild).setCursor(false, true); } else { rng.select(true); } this.fireEvent('focus'); } catch (e) { } }, /** * 初始化UE事件及部分事件代理 * @private * @ignore */ _initEvents: function () { var me = this, doc = me.document, win = me.window; me._proxyDomEvent = utils.bind(me._proxyDomEvent, me); domUtils.on(doc, ['click', 'contextmenu', 'mousedown', 'keydown', 'keyup', 'keypress', 'mouseup', 'mouseover', 'mouseout', 'selectstart'], me._proxyDomEvent); domUtils.on(win, ['focus', 'blur'], me._proxyDomEvent); domUtils.on(doc, ['mouseup', 'keydown'], function (evt) { //特殊键不触发selectionchange if (evt.type == 'keydown' && (evt.ctrlKey || evt.metaKey || evt.shiftKey || evt.altKey)) { return; } if (evt.button == 2)return; me._selectionChange(250, evt); }); // //处理拖拽 // //ie ff不能从外边拖入 // //chrome只针对从外边拖入的内容过滤 // var innerDrag = 0, source = browser.ie ? me.body : me.document, dragoverHandler; // domUtils.on(source, 'dragstart', function () { // innerDrag = 1; // }); // domUtils.on(source, browser.webkit ? 'dragover' : 'drop', function () { // return browser.webkit ? // function () { // clearTimeout(dragoverHandler); // dragoverHandler = setTimeout(function () { // if (!innerDrag) { // var sel = me.selection, // range = sel.getRange(); // if (range) { // var common = range.getCommonAncestor(); // if (common && me.serialize) { // var f = me.serialize, // node = // f.filter( // f.transformInput( // f.parseHTML( // f.word(common.innerHTML) // ) // ) // ); // common.innerHTML = f.toHTML(node); // } // } // } // innerDrag = 0; // }, 200); // } : // function (e) { // if (!innerDrag) { // e.preventDefault ? e.preventDefault() : (e.returnValue = false); // } // innerDrag = 0; // } // }()); }, /** * 触发事件代理 * @private * @ignore */ _proxyDomEvent: function (evt) { return this.fireEvent(evt.type.replace(/^on/, ''), evt); }, /** * 变化选区 * @private * @ignore */ _selectionChange: function (delay, evt) { var me = this; //有光标才做selectionchange 为了解决未focus时点击source不能触发更改工具栏状态的问题(source命令notNeedUndo=1) // if ( !me.selection.isFocus() ){ // return; // } var hackForMouseUp = false; var mouseX, mouseY; if (browser.ie && browser.version < 9 && evt && evt.type == 'mouseup') { var range = this.selection.getRange(); if (!range.collapsed) { hackForMouseUp = true; mouseX = evt.clientX; mouseY = evt.clientY; } } clearTimeout(_selectionChangeTimer); _selectionChangeTimer = setTimeout(function () { if (!me.selection.getNative()) { return; } //修复一个IE下的bug: 鼠标点击一段已选择的文本中间时,可能在mouseup后的一段时间内取到的range是在selection的type为None下的错误值. //IE下如果用户是拖拽一段已选择文本,则不会触发mouseup事件,所以这里的特殊处理不会对其有影响 var ieRange; if (hackForMouseUp && me.selection.getNative().type == 'None') { ieRange = me.document.body.createTextRange(); try { ieRange.moveToPoint(mouseX, mouseY); } catch (ex) { ieRange = null; } } var bakGetIERange; if (ieRange) { bakGetIERange = me.selection.getIERange; me.selection.getIERange = function () { return ieRange; }; } me.selection.cache(); if (bakGetIERange) { me.selection.getIERange = bakGetIERange; } if (me.selection._cachedRange && me.selection._cachedStartElement) { me.fireEvent('beforeselectionchange'); // 第二个参数causeByUi为true代表由用户交互造成的selectionchange. me.fireEvent('selectionchange', !!evt); me.fireEvent('afterselectionchange'); me.selection.clear(); } }, delay || 50); }, _callCmdFn: function (fnName, args) { var cmdName = args[0].toLowerCase(), cmd, cmdFn; cmd = this.commands[cmdName] || UE.commands[cmdName]; cmdFn = cmd && cmd[fnName]; //没有querycommandstate或者没有command的都默认返回0 if ((!cmd || !cmdFn) && fnName == 'queryCommandState') { return 0; } else if (cmdFn) { return cmdFn.apply(this, args); } }, /** * 执行编辑命令cmdName,完成富文本编辑效果 * @name execCommand * @grammar editor.execCommand(cmdName) => {*} */ execCommand: function (cmdName) { cmdName = cmdName.toLowerCase(); var me = this, result, cmd = me.commands[cmdName] || UE.commands[cmdName]; if (!cmd || !cmd.execCommand) { return null; } if (!cmd.notNeedUndo && !me.__hasEnterExecCommand) { me.__hasEnterExecCommand = true; if (me.queryCommandState.apply(me,arguments) != -1) { me.fireEvent('beforeexeccommand', cmdName); result = this._callCmdFn('execCommand', arguments); !me._ignoreContentChange && me.fireEvent('contentchange'); me.fireEvent('afterexeccommand', cmdName); } me.__hasEnterExecCommand = false; } else { result = this._callCmdFn('execCommand', arguments); !me._ignoreContentChange && me.fireEvent('contentchange') } !me._ignoreContentChange && me._selectionChange(); return result; }, /** * 根据传入的command命令,查选编辑器当前的选区,返回命令的状态 * @name queryCommandState * @grammar editor.queryCommandState(cmdName) => (-1|0|1) * @desc * * ''-1'' 当前命令不可用 * * ''0'' 当前命令可用 * * ''1'' 当前命令已经执行过了 */ queryCommandState: function (cmdName) { return this._callCmdFn('queryCommandState', arguments); }, /** * 根据传入的command命令,查选编辑器当前的选区,根据命令返回相关的值 * @name queryCommandValue * @grammar editor.queryCommandValue(cmdName) => {*} */ queryCommandValue: function (cmdName) { return this._callCmdFn('queryCommandValue', arguments); }, /** * 检查编辑区域中是否有内容,若包含tags中的节点类型,直接返回true * @name hasContents * @desc * 默认有文本内容,或者有以下节点都不认为是空 * <code>{table:1,ul:1,ol:1,dl:1,iframe:1,area:1,base:1,col:1,hr:1,img:1,embed:1,input:1,link:1,meta:1,param:1}</code> * @grammar editor.hasContents() => (true|false) * @grammar editor.hasContents(tags) => (true|false) //若文档中包含tags数组里对应的tag,直接返回true * @example * editor.hasContents(['span']) //如果编辑器里有这些,不认为是空 */ hasContents: function (tags) { if (tags) { for (var i = 0, ci; ci = tags[i++];) { if (this.document.getElementsByTagName(ci).length > 0) { return true; } } } if (!domUtils.isEmptyBlock(this.body)) { return true } //随时添加,定义的特殊标签如果存在,不能认为是空 tags = ['div']; for (i = 0; ci = tags[i++];) { var nodes = domUtils.getElementsByTagName(this.document, ci); for (var n = 0, cn; cn = nodes[n++];) { if (domUtils.isCustomeNode(cn)) { return true; } } } return false; }, /** * 重置编辑器,可用来做多个tab使用同一个编辑器实例 * @name reset * @desc * * 清空编辑器内容 * * 清空回退列表 * @grammar editor.reset() */ reset: function () { this.fireEvent('reset'); }, setEnabled: function () { var me = this, range; if (me.body.contentEditable == 'false') { me.body.contentEditable = true; range = me.selection.getRange(); //有可能内容丢失了 try { range.moveToBookmark(me.lastBk); delete me.lastBk } catch (e) { range.setStartAtFirst(me.body).collapse(true) } range.select(true); if (me.bkqueryCommandState) { me.queryCommandState = me.bkqueryCommandState; delete me.bkqueryCommandState; } me.fireEvent('selectionchange'); } }, /** * 设置当前编辑区域可以编辑 * @name enable * @grammar editor.enable() */ enable: function () { return this.setEnabled(); }, setDisabled: function (except) { var me = this; except = except ? utils.isArray(except) ? except : [except] : []; if (me.body.contentEditable == 'true') { if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.body.contentEditable = false; me.bkqueryCommandState = me.queryCommandState; me.queryCommandState = function (type) { if (utils.indexOf(except, type) != -1) { return me.bkqueryCommandState.apply(me, arguments); } return -1; }; me.fireEvent('selectionchange'); } }, /** 设置当前编辑区域不可编辑,except中的命令除外 * @name disable * @grammar editor.disable() * @grammar editor.disable(except) //例外的命令,也即即使设置了disable,此处配置的命令仍然可以执行 * @example * //禁用工具栏中除加粗和插入图片之外的所有功能 * editor.disable(['bold','insertimage']);//可以是单一的String,也可以是Array */ disable: function (except) { return this.setDisabled(except); }, /** * 设置默认内容 * @ignore * @private * @param {String} cont 要存入的内容 */ _setDefaultContent: function () { function clear() { var me = this; if (me.document.getElementById('initContent')) { me.body.innerHTML = '<p>' + (ie ? '' : '<br/>') + '</p>'; me.removeListener('firstBeforeExecCommand focus', clear); setTimeout(function () { me.focus(); me._selectionChange(); }, 0) } } return function (cont) { var me = this; me.body.innerHTML = '<p id="initContent">' + cont + '</p>'; me.addListener('firstBeforeExecCommand focus', clear); } }(), /** * show方法的兼容版本 * @private * @ignore */ setShow: function () { var me = this, range = me.selection.getRange(); if (me.container.style.display == 'none') { //有可能内容丢失了 try { range.moveToBookmark(me.lastBk); delete me.lastBk } catch (e) { range.setStartAtFirst(me.body).collapse(true) } //ie下focus实效,所以做了个延迟 setTimeout(function () { range.select(true); }, 100); me.container.style.display = ''; } }, /** * 显示编辑器 * @name show * @grammar editor.show() */ show: function () { return this.setShow(); }, /** * hide方法的兼容版本 * @private * @ignore */ setHide: function () { var me = this; if (!me.lastBk) { me.lastBk = me.selection.getRange().createBookmark(true); } me.container.style.display = 'none' }, /** * 隐藏编辑器 * @name hide * @grammar editor.hide() */ hide: function () { return this.setHide(); }, /** * 根据制定的路径,获取对应的语言资源 * @name getLang * @grammar editor.getLang(path) => (JSON|String) 路径根据的是lang目录下的语言文件的路径结构 * @example * editor.getLang('contextMenu.delete') //如果当前是中文,那返回是的是删除 */ getLang: function (path) { var lang = UE.I18N[this.options.lang]; if (!lang) { throw Error("not import language file"); } path = (path || "").split("."); for (var i = 0, ci; ci = path[i++];) { lang = lang[ci]; if (!lang)break; } return lang; }, /** * 计算编辑器当前内容的长度 * @name getContentLength * @grammar editor.getContentLength(ingoneHtml,tagNames) => * @example * editor.getLang(true) */ getContentLength: function (ingoneHtml, tagNames) { var count = this.getContent(false,false,true).length; if (ingoneHtml) { tagNames = (tagNames || []).concat([ 'hr', 'img', 'iframe']); count = this.getContentTxt().replace(/[\t\r\n]+/g, '').length; for (var i = 0, ci; ci = tagNames[i++];) { count += this.document.getElementsByTagName(ci).length; } } return count; }, addInputRule: function (rule) { this.inputRules.push(rule); }, filterInputRule: function (root) { for (var i = 0, ci; ci = this.inputRules[i++];) { ci.call(this, root) } }, addOutputRule: function (rule) { this.outputRules.push(rule) }, filterOutputRule: function (root) { for (var i = 0, ci; ci = this.outputRules[i++];) { ci.call(this, root) } } /** * 得到dialog实例对象 * @name getDialog * @grammar editor.getDialog(dialogName) => Object * @example * var dialog = editor.getDialog("insertimage"); * dialog.open(); //打开dialog * dialog.close(); //关闭dialog */ }; utils.inherits(Editor, EventBase); })(); /** * @file * @name UE.ajax * @short Ajax * @desc UEditor内置的ajax请求模块 * @import core/utils.js * @user: taoqili * @date: 11-8-18 * @time: 下午3:18 */ UE.ajax = function() { /** * 创建一个ajaxRequest对象 */ var fnStr = 'XMLHttpRequest()'; try { new ActiveXObject("Msxml2.XMLHTTP"); fnStr = 'ActiveXObject(\'Msxml2.XMLHTTP\')'; } catch (e) { try { new ActiveXObject("Microsoft.XMLHTTP"); fnStr = 'ActiveXObject(\'Microsoft.XMLHTTP\')' } catch (e) { } } var creatAjaxRequest = new Function('return new ' + fnStr); /** * 将json参数转化成适合ajax提交的参数列表 * @param json */ function json2str(json) { var strArr = []; for (var i in json) { //忽略默认的几个参数 if(i=="method" || i=="timeout" || i=="async") continue; //传递过来的对象和函数不在提交之列 if (!((typeof json[i]).toLowerCase() == "function" || (typeof json[i]).toLowerCase() == "object")) { strArr.push( encodeURIComponent(i) + "="+encodeURIComponent(json[i]) ); } } return strArr.join("&"); } return { /** * @name request * @desc 发出ajax请求,ajaxOpt中默认包含method,timeout,async,data,onsuccess以及onerror等六个,支持自定义添加参数 * @grammar UE.ajax.request(url,ajaxOpt); * @example * UE.ajax.request('http://www.xxxx.com/test.php',{ * //可省略,默认POST * method:'POST', * //可以自定义参数 * content:'这里是提交的内容', * //也可以直接传json,但是只能命名为data,否则当做一般字符串处理 * data:{ * name:'UEditor', * age:'1' * } * onsuccess:function(xhr){ * console.log(xhr.responseText); * }, * onerror:function(xhr){ * console.log(xhr.responseText); * } * }) * @param ajaxOptions */ request:function(url, ajaxOptions) { var ajaxRequest = creatAjaxRequest(), //是否超时 timeIsOut = false, //默认参数 defaultAjaxOptions = { method:"POST", timeout:5000, async:true, data:{},//需要传递对象的话只能覆盖 onsuccess:function() { }, onerror:function() { } }; if (typeof url === "object") { ajaxOptions = url; url = ajaxOptions.url; } if (!ajaxRequest || !url) return; var ajaxOpts = ajaxOptions ? utils.extend(defaultAjaxOptions,ajaxOptions) : defaultAjaxOptions; var submitStr = json2str(ajaxOpts); // { name:"Jim",city:"Beijing" } --> "name=Jim&city=Beijing" //如果用户直接通过data参数传递json对象过来,则也要将此json对象转化为字符串 if (!utils.isEmptyObject(ajaxOpts.data)){ submitStr += (submitStr? "&":"") + json2str(ajaxOpts.data); } //超时检测 var timerID = setTimeout(function() { if (ajaxRequest.readyState != 4) { timeIsOut = true; ajaxRequest.abort(); clearTimeout(timerID); } }, ajaxOpts.timeout); var method = ajaxOpts.method.toUpperCase(); var str = url + (url.indexOf("?")==-1?"?":"&") + (method=="POST"?"":submitStr+ "&noCache=" + +new Date); ajaxRequest.open(method, str, ajaxOpts.async); ajaxRequest.onreadystatechange = function() { if (ajaxRequest.readyState == 4) { if (!timeIsOut && ajaxRequest.status == 200) { ajaxOpts.onsuccess(ajaxRequest); } else { ajaxOpts.onerror(ajaxRequest); } } }; if (method == "POST") { ajaxRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); ajaxRequest.send(submitStr); } else { ajaxRequest.send(null); } } }; }(); /** * @file * @name UE.filterWord * @short filterWord * @desc 用来过滤word粘贴过来的字符串 * @import editor.js,core/utils.js * @anthor zhanyi */ var filterWord = UE.filterWord = function () { //是否是word过来的内容 function isWordDocument( str ) { return /(class="?Mso|style="[^"]*\bmso\-|w:WordDocument|<v:)/ig.test( str ); } //去掉小数 function transUnit( v ) { v = v.replace( /[\d.]+\w+/g, function ( m ) { return utils.transUnitToPx(m); } ); return v; } function filterPasteWord( str ) { return str.replace( /[\t\r\n]+/g, "" ) .replace( /<!--[\s\S]*?-->/ig, "" ) //转换图片 .replace(/<v:shape [^>]*>[\s\S]*?.<\/v:shape>/gi,function(str){ //opera能自己解析出image所这里直接返回空 if(browser.opera){ return ''; } try{ var width = str.match(/width:([ \d.]*p[tx])/i)[1], height = str.match(/height:([ \d.]*p[tx])/i)[1], src = str.match(/src=\s*"([^"]*)"/i)[1]; return '<img width="'+ transUnit(width) +'" height="'+transUnit(height) +'" src="' + src + '" />'; } catch(e){ return ''; } }) //针对wps添加的多余标签处理 .replace(/<\/?div[^>]*>/g,'') //去掉多余的属性 .replace( /v:\w+=(["']?)[^'"]+\1/g, '' ) .replace( /<(!|script[^>]*>.*?<\/script(?=[>\s])|\/?(\?xml(:\w+)?|xml|meta|link|style|\w+:\w+)(?=[\s\/>]))[^>]*>/gi, "" ) .replace( /<p [^>]*class="?MsoHeading"?[^>]*>(.*?)<\/p>/gi, "<p><strong>$1</strong></p>" ) //去掉多余的属性 .replace( /\s+(class|lang|align)\s*=\s*(['"]?)([\w-]+)\2/ig, function(str,name,marks,val){ //保留list的标示 return name == 'class' && val == 'MsoListParagraph' ? str : '' }) //清除多余的font/span不能匹配&nbsp;有可能是空格 .replace( /<(font|span)[^>]*>\s*<\/\1>/gi, '' ) //处理style的问题 .replace( /(<[a-z][^>]*)\sstyle=(["'])([^\2]*?)\2/gi, function( str, tag, tmp, style ) { var n = [], s = style.replace( /^\s+|\s+$/, '' ) .replace(/&#39;/g,'\'') .replace( /&quot;/gi, "'" ) .split( /;\s*/g ); for ( var i = 0,v; v = s[i];i++ ) { var name, value, parts = v.split( ":" ); if ( parts.length == 2 ) { name = parts[0].toLowerCase(); value = parts[1].toLowerCase(); if(/^(background)\w*/.test(name) && value.replace(/(initial|\s)/g,'').length == 0 || /^(margin)\w*/.test(name) && /^0\w+$/.test(value) ){ continue; } switch ( name ) { case "mso-padding-alt": case "mso-padding-top-alt": case "mso-padding-right-alt": case "mso-padding-bottom-alt": case "mso-padding-left-alt": case "mso-margin-alt": case "mso-margin-top-alt": case "mso-margin-right-alt": case "mso-margin-bottom-alt": case "mso-margin-left-alt": //ie下会出现挤到一起的情况 //case "mso-table-layout-alt": case "mso-height": case "mso-width": case "mso-vertical-align-alt": //trace:1819 ff下会解析出padding在table上 if(!/<table/.test(tag)) n[i] = name.replace( /^mso-|-alt$/g, "" ) + ":" + transUnit( value ); continue; case "horiz-align": n[i] = "text-align:" + value; continue; case "vert-align": n[i] = "vertical-align:" + value; continue; case "font-color": case "mso-foreground": n[i] = "color:" + value; continue; case "mso-background": case "mso-highlight": n[i] = "background:" + value; continue; case "mso-default-height": n[i] = "min-height:" + transUnit( value ); continue; case "mso-default-width": n[i] = "min-width:" + transUnit( value ); continue; case "mso-padding-between-alt": n[i] = "border-collapse:separate;border-spacing:" + transUnit( value ); continue; case "text-line-through": if ( (value == "single") || (value == "double") ) { n[i] = "text-decoration:line-through"; } continue; case "mso-zero-height": if ( value == "yes" ) { n[i] = "display:none"; } continue; case 'background': break; case 'margin': if ( !/[1-9]/.test( value ) ) { continue; } } if ( /^(mso|column|font-emph|lang|layout|line-break|list-image|nav|panose|punct|row|ruby|sep|size|src|tab-|table-border|text-(?:decor|trans)|top-bar|version|vnd|word-break)/.test( name ) || /text\-indent|padding|margin/.test(name) && /\-[\d.]+/.test(value) ) { continue; } n[i] = name + ":" + parts[1]; } } return tag + (n.length ? ' style="' + n.join( ';').replace(/;{2,}/g,';') + '"' : ''); }) .replace(/[\d.]+(cm|pt)/g,function(str){ return utils.transUnitToPx(str) }) } return function ( html ) { return (isWordDocument( html ) ? filterPasteWord( html ) : html); }; }();///import editor.js ///import core/utils.js ///import core/dom/dom.js ///import core/dom/dtd.js ///import core/htmlparser.js //模拟的节点类 //by zhanyi (function () { var uNode = UE.uNode = function (obj) { this.type = obj.type; this.data = obj.data; this.tagName = obj.tagName; this.parentNode = obj.parentNode; this.attrs = obj.attrs || {}; this.children = obj.children; }; var indentChar = ' ', breakChar = '\n'; function insertLine(arr, current, begin) { arr.push(breakChar); return current + (begin ? 1 : -1); } function insertIndent(arr, current) { //插入缩进 for (var i = 0; i < current; i++) { arr.push(indentChar); } } //创建uNode的静态方法 //支持标签和html uNode.createElement = function (html) { if (/[<>]/.test(html)) { return UE.htmlparser(html).children[0] } else { return new uNode({ type:'element', children:[], tagName:html }) } }; uNode.createText = function (data) { return new UE.uNode({ type:'text', 'data':utils.unhtml(data || '') }) }; function nodeToHtml(node, arr, formatter, current) { switch (node.type) { case 'root': for (var i = 0, ci; ci = node.children[i++];) { //插入新行 if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) { insertLine(arr, current, true); insertIndent(arr, current) } nodeToHtml(ci, arr, formatter, current) } break; case 'text': isText(node, arr); break; case 'element': isElement(node, arr, formatter, current); break; case 'comment': isComment(node, arr, formatter); } return arr; } function isText(node, arr) { arr.push(node.parentNode.tagName == 'pre' ? node.data : node.data.replace(/[ ]{2}/g,' &nbsp;')) } function isElement(node, arr, formatter, current) { var attrhtml = ''; if (node.attrs) { attrhtml = []; var attrs = node.attrs; for (var a in attrs) { attrhtml.push(a + (attrs[a] !== undefined ? '="' + utils.unhtml(attrs[a]) + '"' : '')) } attrhtml = attrhtml.join(' '); } arr.push('<' + node.tagName + (attrhtml ? ' ' + attrhtml : '') + (dtd.$empty[node.tagName] ? '\/' : '' ) + '>' ); //插入新行 if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') { if(node.children && node.children.length){ current = insertLine(arr, current, true); insertIndent(arr, current) } } if (node.children && node.children.length) { for (var i = 0, ci; ci = node.children[i++];) { if (formatter && ci.type == 'element' && !dtd.$inlineWithA[ci.tagName] && i > 1) { insertLine(arr, current); insertIndent(arr, current) } nodeToHtml(ci, arr, formatter, current) } } if (!dtd.$empty[node.tagName]) { if (formatter && !dtd.$inlineWithA[node.tagName] && node.tagName != 'pre') { if(node.children && node.children.length){ current = insertLine(arr, current); insertIndent(arr, current) } } arr.push('<\/' + node.tagName + '>'); } } function isComment(node, arr) { arr.push('<!--' + node.data + '-->'); } function getNodeById(root, id) { var node; if (root.type == 'element' && root.getAttr('id') == id) { return root; } if (root.children && root.children.length) { for (var i = 0, ci; ci = root.children[i++];) { if (node = getNodeById(ci, id)) { return node; } } } } function getNodesByTagName(node, tagName, arr) { if (node.type == 'element' && node.tagName == tagName) { arr.push(node); } if (node.children && node.children.length) { for (var i = 0, ci; ci = node.children[i++];) { getNodesByTagName(ci, tagName, arr) } } } function nodeTraversal(root,fn){ if(root.children && root.children.length){ for(var i= 0,ci;ci=root.children[i];){ nodeTraversal(ci,fn); //ci被替换的情况,这里就不再走 fn了 if(ci.parentNode ){ if(ci.children && ci.children.length){ fn(ci) } if(ci.parentNode) i++ } } }else{ fn(root) } } uNode.prototype = { toHtml:function (formatter) { var arr = []; nodeToHtml(this, arr, formatter, 0); return arr.join('') }, innerHTML:function (htmlstr) { if (this.type != 'element' || dtd.$empty[this.tagName]) { return this; } if (utils.isString(htmlstr)) { if(this.children){ for (var i = 0, ci; ci = this.children[i++];) { ci.parentNode = null; } } this.children = []; var tmpRoot = UE.htmlparser(htmlstr); for (var i = 0, ci; ci = tmpRoot.children[i++];) { this.children.push(ci); ci.parentNode = this; } return this; } else { var tmpRoot = new UE.uNode({ type:'root', children:this.children }); return tmpRoot.toHtml(); } }, innerText:function (textStr) { if (this.type != 'element' || dtd.$empty[this.tagName]) { return this; } if (textStr) { if(this.children){ for (var i = 0, ci; ci = this.children[i++];) { ci.parentNode = null; } } this.children = []; this.appendChild(uNode.createText(textStr)); return this; } else { return this.toHtml().replace(/<[^>]+>/g, ''); } }, getData:function () { if (this.type == 'element') return ''; return this.data }, firstChild:function () { // if (this.type != 'element' || dtd.$empty[this.tagName]) { // return this; // } return this.children ? this.children[0] : null; }, lastChild:function () { // if (this.type != 'element' || dtd.$empty[this.tagName] ) { // return this; // } return this.children ? this.children[this.children.length - 1] : null; }, previousSibling : function(){ var parent = this.parentNode; for (var i = 0, ci; ci = parent.children[i]; i++) { if (ci === this) { return i == 0 ? null : parent.children[i-1]; } } }, nextSibling : function(){ var parent = this.parentNode; for (var i = 0, ci; ci = parent.children[i++];) { if (ci === this) { return parent.children[i]; } } }, replaceChild:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i, 1, target); source.parentNode = null; target.parentNode = this; return target; } } } }, appendChild:function (node) { if (this.type == 'root' || (this.type == 'element' && !dtd.$empty[this.tagName])) { if (!this.children) { this.children = [] } if(node.parentNode){ node.parentNode.removeChild(node); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === node) { this.children.splice(i, 1); break; } } this.children.push(node); node.parentNode = this; return node; } }, insertBefore:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i, 0, target); target.parentNode = this; return target; } } } }, insertAfter:function (target, source) { if (this.children) { if(target.parentNode){ target.parentNode.removeChild(target); } for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === source) { this.children.splice(i + 1, 0, target); target.parentNode = this; return target; } } } }, removeChild:function (node,keepChildren) { if (this.children) { for (var i = 0, ci; ci = this.children[i]; i++) { if (ci === node) { this.children.splice(i, 1); ci.parentNode = null; if(keepChildren && ci.children && ci.children.length){ for(var j= 0,cj;cj=ci.children[j];j++){ this.children.splice(i+j,0,cj); cj.parentNode = this; } } return ci; } } } }, getAttr:function (attrName) { return this.attrs && this.attrs[attrName.toLowerCase()] }, setAttr:function (attrName, attrVal) { if (!attrName) { delete this.attrs; return; } if(!this.attrs){ this.attrs = {}; } if (utils.isObject(attrName)) { for (var a in attrName) { if (!attrName[a]) { delete this.attrs[a] } else { this.attrs[a.toLowerCase()] = attrName[a]; } } } else { if (!attrVal) { delete this.attrs[attrName] } else { this.attrs[attrName.toLowerCase()] = attrVal; } } }, getIndex:function(){ var parent = this.parentNode; for(var i= 0,ci;ci=parent.children[i];i++){ if(ci === this){ return i; } } return -1; }, getNodeById:function (id) { var node; if (this.children && this.children.length) { for (var i = 0, ci; ci = this.children[i++];) { if (node = getNodeById(ci, id)) { return node; } } } }, getNodesByTagName:function (tagNames) { tagNames = utils.trim(tagNames).replace(/[ ]{2,}/g, ' ').split(' '); var arr = [], me = this; utils.each(tagNames, function (tagName) { if (me.children && me.children.length) { for (var i = 0, ci; ci = me.children[i++];) { getNodesByTagName(ci, tagName, arr) } } }); return arr; }, getStyle:function (name) { var cssStyle = this.getAttr('style'); if (!cssStyle) { return '' } var reg = new RegExp(name + ':([^;]+)','i'); var match = cssStyle.match(reg); if (match && match[0]) { return match[1] } return ''; }, setStyle:function (name, val) { function exec(name, val) { var reg = new RegExp(name + ':([^;]+;?)', 'gi'); cssStyle = cssStyle.replace(reg, ''); if (val) { cssStyle = name + ':' + utils.unhtml(val) + ';' + cssStyle } } var cssStyle = this.getAttr('style'); if (!cssStyle) { cssStyle = ''; } if (utils.isObject(name)) { for (var a in name) { exec(a, name[a]) } } else { exec(name, val) } this.setAttr('style', utils.trim(cssStyle)) }, traversal:function(fn){ if(this.children && this.children.length){ nodeTraversal(this,fn); } return this; } } })(); //html字符串转换成uNode节点 //by zhanyi var htmlparser = UE.htmlparser = function (htmlstr,ignoreBlank) { var re_tag = /<(?:(?:\/([^>]+)>)|(?:!--([\S|\s]*?)-->)|(?:([^\s\/>]+)\s*((?:(?:"[^"]*")|(?:'[^']*')|[^"'<>])*)\/?>))/g, re_attr = /([\w\-:.]+)(?:(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^\s>]+)))|(?=\s|$))/g; //ie下取得的html可能会有\n存在,要去掉,在处理replace(/[\t\r\n]*/g,'');代码高量的\n不能去除 var allowEmptyTags = { b:1,code:1,i:1,u:1,strike:1,s:1,tt:1,strong:1,q:1,samp:1,em:1,span:1, sub:1,img:1,sup:1,font:1,big:1,small:1,iframe:1,a:1,br:1,pre:1 }; htmlstr = htmlstr.replace(new RegExp(domUtils.fillChar, 'g'), ''); if(!ignoreBlank){ htmlstr = htmlstr.replace(new RegExp('[\\r\\t\\n'+(ignoreBlank?'':' ')+']*<\/?(\\w+)\\s*(?:[^>]*)>[\\r\\t\\n'+(ignoreBlank?'':' ')+']*','g'), function(a,b){ //br暂时单独处理 if(b && allowEmptyTags[b.toLowerCase()]){ return a.replace(/(^[\n\r]+)|([\n\r]+$)/g,''); } return a.replace(new RegExp('^[\\r\\n'+(ignoreBlank?'':' ')+']+'),'').replace(new RegExp('[\\r\\n'+(ignoreBlank?'':' ')+']+$'),''); }); } var uNode = UE.uNode, needParentNode = { 'td':'tr', 'tr':['tbody','thead','tfoot'], 'tbody':'table', 'th':'tr', 'thead':'table', 'tfoot':'table', 'caption':'table', 'li':['ul', 'ol'], 'dt':'dl', 'dd':'dl', 'option':'select' }, needChild = { 'ol':'li', 'ul':'li' }; function text(parent, data) { if(needChild[parent.tagName]){ var tmpNode = uNode.createElement(needChild[parent.tagName]); parent.appendChild(tmpNode); tmpNode.appendChild(uNode.createText(data)); parent = tmpNode; }else{ parent.appendChild(uNode.createText(data)); } } function element(parent, tagName, htmlattr) { var needParentTag; if (needParentTag = needParentNode[tagName]) { var tmpParent = parent,hasParent; while(tmpParent.type != 'root'){ if(utils.isArray(needParentTag) ? utils.indexOf(needParentTag, tmpParent.tagName) != -1 : needParentTag == tmpParent.tagName){ parent = tmpParent; hasParent = true; break; } tmpParent = tmpParent.parentNode; } if(!hasParent){ parent = element(parent, utils.isArray(needParentTag) ? needParentTag[0] : needParentTag) } } //按dtd处理嵌套 // if(parent.type != 'root' && !dtd[parent.tagName][tagName]) // parent = parent.parentNode; var elm = new uNode({ parentNode:parent, type:'element', tagName:tagName.toLowerCase(), //是自闭合的处理一下 children:dtd.$empty[tagName] ? null : [] }); //如果属性存在,处理属性 if (htmlattr) { var attrs = {}, match; while (match = re_attr.exec(htmlattr)) { attrs[match[1].toLowerCase()] = utils.unhtml(match[2] || match[3] || match[4]) } elm.attrs = attrs; } parent.children.push(elm); //如果是自闭合节点返回父亲节点 return dtd.$empty[tagName] ? parent : elm } function comment(parent, data) { parent.children.push(new uNode({ type:'comment', data:data, parentNode:parent })); } var match, currentIndex = 0, nextIndex = 0; //设置根节点 var root = new uNode({ type:'root', children:[] }); var currentParent = root; while (match = re_tag.exec(htmlstr)) { currentIndex = match.index; try{ if (currentIndex > nextIndex) { //text node text(currentParent, htmlstr.slice(nextIndex, currentIndex)); } if (match[3]) { //start tag currentParent = element(currentParent, match[3].toLowerCase(), match[4]); } else if (match[1]) { if(currentParent.type != 'root'){ var tmpParent = currentParent; while(currentParent.type == 'element' && currentParent.tagName != match[1].toLowerCase()){ currentParent = currentParent.parentNode; if(currentParent.type == 'root'){ currentParent = tmpParent; throw 'break' } } //end tag currentParent = currentParent.parentNode; } } else if (match[2]) { //comment comment(currentParent, match[2]) } }catch(e){} nextIndex = re_tag.lastIndex; } //如果结束是文本,就有可能丢掉,所以这里手动判断一下 //例如 <li>sdfsdfsdf<li>sdfsdfsdfsdf if (nextIndex < htmlstr.length) { text(currentParent, htmlstr.slice(nextIndex)); } return root; };/** * @file * @name UE.filterNode * @short filterNode * @desc 根据给定的规则过滤节点 * @import editor.js,core/utils.js * @anthor zhanyi */ var filterNode = UE.filterNode = function () { function filterNode(node,rules){ switch (node.type) { case 'text': break; case 'element': var val; if(val = rules[node.tagName]){ if(val === '-'){ node.parentNode.removeChild(node) }else if(utils.isFunction(val)){ var parentNode = node.parentNode, index = node.getIndex(); val(node); if(node.parentNode){ if(node.children){ for(var i = 0,ci;ci=node.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } }else{ for(var i = index,ci;ci=parentNode.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } }else{ var attrs = val['$']; if(attrs && node.attrs){ var tmpAttrs = {},tmpVal; for(var a in attrs){ tmpVal = node.getAttr(a); //todo 只先对style单独处理 if(a == 'style' && utils.isArray(attrs[a])){ var tmpCssStyle = []; utils.each(attrs[a],function(v){ var tmp; if(tmp = node.getStyle(v)){ tmpCssStyle.push(v + ':' + tmp); } }); tmpVal = tmpCssStyle.join(';') } if(tmpVal){ tmpAttrs[a] = tmpVal; } } node.attrs = tmpAttrs; } if(node.children){ for(var i = 0,ci;ci=node.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } } }else{ //如果不在名单里扣出子节点并删除该节点,cdata除外 if(dtd.$cdata[node.tagName]){ node.parentNode.removeChild(node) }else{ var parentNode = node.parentNode, index = node.getIndex(); node.parentNode.removeChild(node,true); for(var i = index,ci;ci=parentNode.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } } } break; case 'comment': node.parentNode.removeChild(node) } } return function(root,rules){ if(utils.isEmptyObject(rules)){ return root; } var val; if(val = rules['-']){ utils.each(val.split(' '),function(k){ rules[k] = '-' }) } for(var i= 0,ci;ci=root.children[i];){ filterNode(ci,rules); if(ci.parentNode){ i++; } } return root; } }();///import core ///plugin 编辑器默认的过滤转换机制 UE.plugins['defaultfilter'] = function () { var me = this; me.setOpt('allowDivTransToP',true); //默认的过滤处理 //进入编辑器的内容处理 me.addInputRule(function (root) { var allowDivTransToP = this.options.allowDivTransToP; var val; //进行默认的处理 root.traversal(function (node) { if (node.type == 'element') { if (!dtd.$cdata[node.tagName] && me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) { if (!node.firstChild()) node.parentNode.removeChild(node); else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) { node.parentNode.removeChild(node, true) } return; } switch (node.tagName) { case 'style': case 'script': node.setAttr({ cdata_tag: node.tagName, cdata_data: encodeURIComponent(node.innerText() || '') }); node.tagName = 'div'; node.removeChild(node.firstChild()); break; case 'a': if (val = node.getAttr('href')) { node.setAttr('_href', val) } break; case 'img': //todo base64暂时去掉,后边做远程图片上传后,干掉这个 if (val = node.getAttr('src')) { if (/^data:/.test(val)) { node.parentNode.removeChild(node); break; } } node.setAttr('_src', node.getAttr('src')); break; case 'span': if (browser.webkit && (val = node.getStyle('white-space'))) { if (/nowrap|normal/.test(val)) { node.setStyle('white-space', ''); if (me.options.autoClearEmptyNode && utils.isEmptyObject(node.attrs)) { node.parentNode.removeChild(node, true) } } } break; case 'p': if (val = node.getAttr('align')) { node.setAttr('align'); node.setStyle('text-align', val) } //trace:3431 // var cssStyle = node.getAttr('style'); // if (cssStyle) { // cssStyle = cssStyle.replace(/(margin|padding)[^;]+/g, ''); // node.setAttr('style', cssStyle) // // } if (!node.firstChild()) { node.innerHTML(browser.ie ? '&nbsp;' : '<br/>') } break; case 'div': if(node.getAttr('cdata_tag')){ break; } //针对代码这里不处理插入代码的div val = node.getAttr('class'); if(val && /^line number\d+/.test(val)){ break; } if(!allowDivTransToP){ break; } var tmpNode, p = UE.uNode.createElement('p'); while (tmpNode = node.firstChild()) { if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) { p.appendChild(tmpNode); } else { if (p.firstChild()) { node.parentNode.insertBefore(p, node); p = UE.uNode.createElement('p'); } else { node.parentNode.insertBefore(tmpNode, node); } } } if (p.firstChild()) { node.parentNode.insertBefore(p, node); } node.parentNode.removeChild(node); break; case 'dl': node.tagName = 'ul'; break; case 'dt': case 'dd': node.tagName = 'li'; break; case 'li': var className = node.getAttr('class'); if (!className || !/list\-/.test(className)) { node.setAttr() } var tmpNodes = node.getNodesByTagName('ol ul'); UE.utils.each(tmpNodes, function (n) { node.parentNode.insertAfter(n, node); }); break; case 'td': case 'th': case 'caption': if(!node.children || !node.children.length){ node.appendChild(browser.ie ? UE.uNode.createText(' ') : UE.uNode.createElement('br')) } } } if(node.type == 'comment'){ node.parentNode.removeChild(node); } }) }); //从编辑器出去的内容处理 me.addOutputRule(function (root) { var val; root.traversal(function (node) { if (node.type == 'element') { if (me.options.autoClearEmptyNode && dtd.$inline[node.tagName] && !dtd.$empty[node.tagName] && (!node.attrs || utils.isEmptyObject(node.attrs))) { if (!node.firstChild()) node.parentNode.removeChild(node); else if (node.tagName == 'span' && (!node.attrs || utils.isEmptyObject(node.attrs))) { node.parentNode.removeChild(node, true) } return; } switch (node.tagName) { case 'div': if (val = node.getAttr('cdata_tag')) { node.tagName = val; node.appendChild(UE.uNode.createText(node.getAttr('cdata_data'))); node.setAttr({cdata_tag: '', cdata_data: ''}); } break; case 'a': if (val = node.getAttr('_href')) { node.setAttr({ 'href': val, '_href': '' }) } break; case 'img': if (val = node.getAttr('_src')) { node.setAttr({ 'src': node.getAttr('_src'), '_src': '' }) } } } }) }); }; ///import core /** * @description 插入内容 * @name baidu.editor.execCommand * @param {String} cmdName inserthtml插入内容的命令 * @param {String} html 要插入的内容 * @author zhanyi */ UE.commands['inserthtml'] = { execCommand: function (command,html,notNeedFilter){ var me = this, range, div; if(!html){ return; } if(me.fireEvent('beforeinserthtml',html) === true){ return; } range = me.selection.getRange(); div = range.document.createElement( 'div' ); div.style.display = 'inline'; if (!notNeedFilter) { var root = UE.htmlparser(html); //如果给了过滤规则就先进行过滤 if(me.options.filterRules){ UE.filterNode(root,me.options.filterRules); } //执行默认的处理 me.filterInputRule(root); html = root.toHtml() } div.innerHTML = utils.trim( html ); if ( !range.collapsed ) { var tmpNode = range.startContainer; if(domUtils.isFillChar(tmpNode)){ range.setStartBefore(tmpNode) } tmpNode = range.endContainer; if(domUtils.isFillChar(tmpNode)){ range.setEndAfter(tmpNode) } range.txtToElmBoundary(); //结束边界可能放到了br的前边,要把br包含进来 // x[xxx]<br/> if(range.endContainer && range.endContainer.nodeType == 1){ tmpNode = range.endContainer.childNodes[range.endOffset]; if(tmpNode && domUtils.isBr(tmpNode)){ range.setEndAfter(tmpNode); } } if(range.startOffset == 0){ tmpNode = range.startContainer; if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){ tmpNode = range.endContainer; if(range.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){ me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>'; range.setStart(me.body.firstChild,0).collapse(true) } } } !range.collapsed && range.deleteContents(); if(range.startContainer.nodeType == 1){ var child = range.startContainer.childNodes[range.startOffset],pre; if(child && domUtils.isBlockElm(child) && (pre = child.previousSibling) && domUtils.isBlockElm(pre)){ range.setEnd(pre,pre.childNodes.length).collapse(); while(child.firstChild){ pre.appendChild(child.firstChild); } domUtils.remove(child); } } } var child,parent,pre,tmp,hadBreak = 0, nextNode; //如果当前位置选中了fillchar要干掉,要不会产生空行 if(range.inFillChar()){ child = range.startContainer; if(domUtils.isFillChar(child)){ range.setStartBefore(child).collapse(true); domUtils.remove(child); }else if(domUtils.isFillChar(child,true)){ child.nodeValue = child.nodeValue.replace(fillCharReg,''); range.startOffset--; range.collapsed && range.collapse(true) } } //列表单独处理 var li = domUtils.findParentByTagName(range.startContainer,'li',true); if(li){ var next,last; while(child = div.firstChild){ //针对hr单独处理一下先 while(child && (child.nodeType == 3 || !domUtils.isBlockElm(child) || child.tagName=='HR' )){ next = child.nextSibling; range.insertNode( child).collapse(); last = child; child = next; } if(child){ if(/^(ol|ul)$/i.test(child.tagName)){ while(child.firstChild){ last = child.firstChild; domUtils.insertAfter(li,child.firstChild); li = li.nextSibling; } domUtils.remove(child) }else{ var tmpLi; next = child.nextSibling; tmpLi = me.document.createElement('li'); domUtils.insertAfter(li,tmpLi); tmpLi.appendChild(child); last = child; child = next; li = tmpLi; } } } li = domUtils.findParentByTagName(range.startContainer,'li',true); if(domUtils.isEmptyBlock(li)){ domUtils.remove(li) } if(last){ range.setStartAfter(last).collapse(true).select(true) } }else{ while ( child = div.firstChild ) { if(hadBreak){ var p = me.document.createElement('p'); while(child && (child.nodeType == 3 || !dtd.$block[child.tagName])){ nextNode = child.nextSibling; p.appendChild(child); child = nextNode; } if(p.firstChild){ child = p } } range.insertNode( child ); nextNode = child.nextSibling; if ( !hadBreak && child.nodeType == domUtils.NODE_ELEMENT && domUtils.isBlockElm( child ) ){ parent = domUtils.findParent( child,function ( node ){ return domUtils.isBlockElm( node ); } ); if ( parent && parent.tagName.toLowerCase() != 'body' && !(dtd[parent.tagName][child.nodeName] && child.parentNode === parent)){ if(!dtd[parent.tagName][child.nodeName]){ pre = parent; }else{ tmp = child.parentNode; while (tmp !== parent){ pre = tmp; tmp = tmp.parentNode; } } domUtils.breakParent( child, pre || tmp ); //去掉break后前一个多余的节点 <p>|<[p> ==> <p></p><div></div><p>|</p> var pre = child.previousSibling; domUtils.trimWhiteTextNode(pre); if(!pre.childNodes.length){ domUtils.remove(pre); } //trace:2012,在非ie的情况,切开后剩下的节点有可能不能点入光标添加br占位 if(!browser.ie && (next = child.nextSibling) && domUtils.isBlockElm(next) && next.lastChild && !domUtils.isBr(next.lastChild)){ next.appendChild(me.document.createElement('br')); } hadBreak = 1; } } var next = child.nextSibling; if(!div.firstChild && next && domUtils.isBlockElm(next)){ range.setStart(next,0).collapse(true); break; } range.setEndAfter( child ).collapse(); } child = range.startContainer; if(nextNode && domUtils.isBr(nextNode)){ domUtils.remove(nextNode) } //用chrome可能有空白展位符 if(domUtils.isBlockElm(child) && domUtils.isEmptyNode(child)){ if(nextNode = child.nextSibling){ domUtils.remove(child); if(nextNode.nodeType == 1 && dtd.$block[nextNode.tagName]){ range.setStart(nextNode,0).collapse(true).shrinkBoundary() } }else{ try{ child.innerHTML = browser.ie ? domUtils.fillChar : '<br/>'; }catch(e){ range.setStartBefore(child); domUtils.remove(child) } } } //加上true因为在删除表情等时会删两次,第一次是删的fillData try{ range.select(true); }catch(e){} } setTimeout(function(){ range = me.selection.getRange(); range.scrollToView(me.autoHeightEnabled,me.autoHeightEnabled ? domUtils.getXY(me.iframe).y:0); me.fireEvent('afterinserthtml'); },200); } }; ///import core ///import plugins\inserthtml.js ///commands 插入图片,操作图片的对齐方式 ///commandsName InsertImage,ImageNone,ImageLeft,ImageRight,ImageCenter ///commandsTitle 图片,默认,居左,居右,居中 ///commandsDialog dialogs\image /** * Created by . * User: zhanyi * for image */ UE.commands['imagefloat'] = { execCommand:function (cmd, align) { var me = this, range = me.selection.getRange(); if (!range.collapsed) { var img = range.getClosedNode(); if (img && img.tagName == 'IMG') { switch (align) { case 'left': case 'right': case 'none': var pN = img.parentNode, tmpNode, pre, next; while (dtd.$inline[pN.tagName] || pN.tagName == 'A') { pN = pN.parentNode; } tmpNode = pN; if (tmpNode.tagName == 'P' && domUtils.getStyle(tmpNode, 'text-align') == 'center') { if (!domUtils.isBody(tmpNode) && domUtils.getChildCount(tmpNode, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node); }) == 1) { pre = tmpNode.previousSibling; next = tmpNode.nextSibling; if (pre && next && pre.nodeType == 1 && next.nodeType == 1 && pre.tagName == next.tagName && domUtils.isBlockElm(pre)) { pre.appendChild(tmpNode.firstChild); while (next.firstChild) { pre.appendChild(next.firstChild); } domUtils.remove(tmpNode); domUtils.remove(next); } else { domUtils.setStyle(tmpNode, 'text-align', ''); } } range.selectNode(img).select(); } domUtils.setStyle(img, 'float', align == 'none' ? '' : align); if(align == 'none'){ domUtils.removeAttributes(img,'align'); } break; case 'center': if (me.queryCommandValue('imagefloat') != 'center') { pN = img.parentNode; domUtils.setStyle(img, 'float', ''); domUtils.removeAttributes(img,'align'); tmpNode = img; while (pN && domUtils.getChildCount(pN, function (node) { return !domUtils.isBr(node) && !domUtils.isWhitespace(node); }) == 1 && (dtd.$inline[pN.tagName] || pN.tagName == 'A')) { tmpNode = pN; pN = pN.parentNode; } range.setStartBefore(tmpNode).setCursor(false); pN = me.document.createElement('div'); pN.appendChild(tmpNode); domUtils.setStyle(tmpNode, 'float', ''); me.execCommand('insertHtml', '<p id="_img_parent_tmp" style="text-align:center">' + pN.innerHTML + '</p>'); tmpNode = me.document.getElementById('_img_parent_tmp'); tmpNode.removeAttribute('id'); tmpNode = tmpNode.firstChild; range.selectNode(tmpNode).select(); //去掉后边多余的元素 next = tmpNode.parentNode.nextSibling; if (next && domUtils.isEmptyNode(next)) { domUtils.remove(next); } } break; } } } }, queryCommandValue:function () { var range = this.selection.getRange(), startNode, floatStyle; if (range.collapsed) { return 'none'; } startNode = range.getClosedNode(); if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') { floatStyle = startNode.getAttribute('align')||domUtils.getComputedStyle(startNode, 'float'); if (floatStyle == 'none') { floatStyle = domUtils.getComputedStyle(startNode.parentNode, 'text-align') == 'center' ? 'center' : floatStyle; } return { left:1, right:1, center:1 }[floatStyle] ? floatStyle : 'none'; } return 'none'; }, queryCommandState:function () { var range = this.selection.getRange(), startNode; if (range.collapsed) return -1; startNode = range.getClosedNode(); if (startNode && startNode.nodeType == 1 && startNode.tagName == 'IMG') { return 0; } return -1; } }; UE.commands['insertimage'] = { execCommand:function (cmd, opt) { opt = utils.isArray(opt) ? opt : [opt]; if (!opt.length) { return; } var me = this, range = me.selection.getRange(), img = range.getClosedNode(); if (img && /img/i.test(img.tagName) && img.className != "edui-faked-video" && !img.getAttribute("word_img")) { var first = opt.shift(); var floatStyle = first['floatStyle']; delete first['floatStyle']; //// img.style.border = (first.border||0) +"px solid #000"; //// img.style.margin = (first.margin||0) +"px"; // img.style.cssText += ';margin:' + (first.margin||0) +"px;" + 'border:' + (first.border||0) +"px solid #000"; domUtils.setAttributes(img, first); me.execCommand('imagefloat', floatStyle); if (opt.length > 0) { range.setStartAfter(img).setCursor(false, true); me.execCommand('insertimage', opt); } } else { var html = [], str = '', ci; ci = opt[0]; if (opt.length == 1) { str = '<img src="' + ci.src + '" ' + (ci._src ? ' _src="' + ci._src + '" ' : '') + (ci.width ? 'width="' + ci.width + '" ' : '') + (ci.height ? ' height="' + ci.height + '" ' : '') + (ci['floatStyle'] == 'left' || ci['floatStyle'] == 'right' ? ' style="float:' + ci['floatStyle'] + ';"' : '') + (ci.title && ci.title != "" ? ' title="' + ci.title + '"' : '') + (ci.border && ci.border != "0" ? ' border="' + ci.border + '"' : '') + (ci.alt && ci.alt != "" ? ' alt="' + ci.alt + '"' : '') + (ci.hspace && ci.hspace != "0" ? ' hspace = "' + ci.hspace + '"' : '') + (ci.vspace && ci.vspace != "0" ? ' vspace = "' + ci.vspace + '"' : '') + '/>'; if (ci['floatStyle'] == 'center') { str = '<p style="text-align: center">' + str + '</p>'; } html.push(str); } else { for (var i = 0; ci = opt[i++];) { str = '<p ' + (ci['floatStyle'] == 'center' ? 'style="text-align: center" ' : '') + '><img src="' + ci.src + '" ' + (ci.width ? 'width="' + ci.width + '" ' : '') + (ci._src ? ' _src="' + ci._src + '" ' : '') + (ci.height ? ' height="' + ci.height + '" ' : '') + ' style="' + (ci['floatStyle'] && ci['floatStyle'] != 'center' ? 'float:' + ci['floatStyle'] + ';' : '') + (ci.border || '') + '" ' + (ci.title ? ' title="' + ci.title + '"' : '') + ' /></p>'; html.push(str); } } me.execCommand('insertHtml', html.join('')); } } };///import core ///import plugins\removeformat.js ///commands 字体颜色,背景色,字号,字体,下划线,删除线 ///commandsName ForeColor,BackColor,FontSize,FontFamily,Underline,StrikeThrough ///commandsTitle 字体颜色,背景色,字号,字体,下划线,删除线 /** * @description 字体 * @name baidu.editor.execCommand * @param {String} cmdName 执行的功能名称 * @param {String} value 传入的值 */ UE.plugins['font'] = function () { var me = this, fonts = { 'forecolor': 'color', 'backcolor': 'background-color', 'fontsize': 'font-size', 'fontfamily': 'font-family', 'underline': 'text-decoration', 'strikethrough': 'text-decoration', 'fontborder': 'border' }, needCmd = {'underline': 1, 'strikethrough': 1, 'fontborder': 1}, needSetChild = { 'forecolor': 'color', 'backcolor': 'background-color', 'fontsize': 'font-size', 'fontfamily': 'font-family' }; me.setOpt({ 'fontfamily': [ { name: 'songti', val: '宋体,SimSun'}, { name: 'yahei', val: '微软雅黑,Microsoft YaHei'}, { name: 'kaiti', val: '楷体,楷体_GB2312, SimKai'}, { name: 'heiti', val: '黑体, SimHei'}, { name: 'lishu', val: '隶书, SimLi'}, { name: 'andaleMono', val: 'andale mono'}, { name: 'arial', val: 'arial, helvetica,sans-serif'}, { name: 'arialBlack', val: 'arial black,avant garde'}, { name: 'comicSansMs', val: 'comic sans ms'}, { name: 'impact', val: 'impact,chicago'}, { name: 'timesNewRoman', val: 'times new roman'} ], 'fontsize': [10, 11, 12, 14, 16, 18, 20, 24, 36] }); function mergeWithParent(node){ var parent; while(parent = node.parentNode){ if(parent.tagName == 'SPAN' && domUtils.getChildCount(parent,function(child){ return !domUtils.isBookmarkNode(child) && !domUtils.isBr(child) }) == 1) { parent.style.cssText += node.style.cssText; domUtils.remove(node,true); node = parent; }else{ break; } } } function mergeChild(rng,cmdName,value){ if(needSetChild[cmdName]){ rng.adjustmentBoundary(); if(!rng.collapsed && rng.startContainer.nodeType == 1){ var start = rng.startContainer.childNodes[rng.startOffset]; if(start && domUtils.isTagNode(start,'span')){ var bk = rng.createBookmark(); utils.each(domUtils.getElementsByTagName(start, 'span'), function (span) { if (!span.parentNode || domUtils.isBookmarkNode(span))return; if(cmdName == 'backcolor' && domUtils.getComputedStyle(span,'background-color').toLowerCase() === value){ return; } domUtils.removeStyle(span,needSetChild[cmdName]); if(span.style.cssText.replace(/^\s+$/,'').length == 0){ domUtils.remove(span,true) } }); rng.moveToBookmark(bk) } } } } function mergesibling(rng,cmdName,value) { var collapsed = rng.collapsed, bk = rng.createBookmark(), common; if (collapsed) { common = bk.start.parentNode; while (dtd.$inline[common.tagName]) { common = common.parentNode; } } else { common = domUtils.getCommonAncestor(bk.start, bk.end); } utils.each(domUtils.getElementsByTagName(common, 'span'), function (span) { if (!span.parentNode || domUtils.isBookmarkNode(span))return; if (/\s*border\s*:\s*none;?\s*/i.test(span.style.cssText)) { if(/^\s*border\s*:\s*none;?\s*$/.test(span.style.cssText)){ domUtils.remove(span, true); }else{ domUtils.removeStyle(span,'border'); } return } if (/border/i.test(span.style.cssText) && span.parentNode.tagName == 'SPAN' && /border/i.test(span.parentNode.style.cssText)) { span.style.cssText = span.style.cssText.replace(/border[^:]*:[^;]+;?/gi, ''); } if(!(cmdName=='fontborder' && value=='none')){ var next = span.nextSibling; while (next && next.nodeType == 1 && next.tagName == 'SPAN' ) { if(domUtils.isBookmarkNode(next) && cmdName == 'fontborder') { span.appendChild(next); next = span.nextSibling; continue; } if (next.style.cssText == span.style.cssText) { domUtils.moveChild(next, span); domUtils.remove(next); } if (span.nextSibling === next) break; next = span.nextSibling; } } mergeWithParent(span); if(browser.ie && browser.version > 8 ){ //拷贝父亲们的特别的属性,这里只做背景颜色的处理 var parent = domUtils.findParent(span,function(n){return n.tagName == 'SPAN' && /background-color/.test(n.style.cssText)}); if(parent && !/background-color/.test(span.style.cssText)){ span.style.backgroundColor = parent.style.backgroundColor; } } }); rng.moveToBookmark(bk); mergeChild(rng,cmdName,value) } me.addInputRule(function (root) { utils.each(root.getNodesByTagName('u s del font strike'), function (node) { if (node.tagName == 'font') { var cssStyle = []; for (var p in node.attrs) { switch (p) { case 'size': cssStyle.push('font-size:' + node.attrs[p] + 'px'); break; case 'color': cssStyle.push('color:' + node.attrs[p]); break; case 'face': cssStyle.push('font-family:' + node.attrs[p]); break; case 'style': cssStyle.push(node.attrs[p]); } } node.attrs = { 'style': cssStyle.join(';') }; } else { var val = node.tagName == 'u' ? 'underline' : 'line-through'; node.attrs = { 'style': (node.getAttr('style') || '') + 'text-decoration:' + val + ';' } } node.tagName = 'span'; }); // utils.each(root.getNodesByTagName('span'), function (node) { // var val; // if(val = node.getAttr('class')){ // if(/fontstrikethrough/.test(val)){ // node.setStyle('text-decoration','line-through'); // if(node.attrs['class']){ // node.attrs['class'] = node.attrs['class'].replace(/fontstrikethrough/,''); // }else{ // node.setAttr('class') // } // } // if(/fontborder/.test(val)){ // node.setStyle('border','1px solid #000'); // if(node.attrs['class']){ // node.attrs['class'] = node.attrs['class'].replace(/fontborder/,''); // }else{ // node.setAttr('class') // } // } // } // }); }); // me.addOutputRule(function(root){ // utils.each(root.getNodesByTagName('span'), function (node) { // var val; // if(val = node.getStyle('text-decoration')){ // if(/line-through/.test(val)){ // if(node.attrs['class']){ // node.attrs['class'] += ' fontstrikethrough'; // }else{ // node.setAttr('class','fontstrikethrough') // } // } // // node.setStyle('text-decoration') // } // if(val = node.getStyle('border')){ // if(/1px/.test(val) && /solid/.test(val)){ // if(node.attrs['class']){ // node.attrs['class'] += ' fontborder'; // // }else{ // node.setAttr('class','fontborder') // } // } // node.setStyle('border') // // } // }); // }); for (var p in fonts) { (function (cmd, style) { UE.commands[cmd] = { execCommand: function (cmdName, value) { value = value || (this.queryCommandState(cmdName) ? 'none' : cmdName == 'underline' ? 'underline' : cmdName == 'fontborder' ? '1px solid #000' : 'line-through'); var me = this, range = this.selection.getRange(), text; if (value == 'default') { if (range.collapsed) { text = me.document.createTextNode('font'); range.insertNode(text).select(); } me.execCommand('removeFormat', 'span,a', style); if (text) { range.setStartBefore(text).collapse(true); domUtils.remove(text); } mergesibling(range,cmdName,value); range.select() } else { if (!range.collapsed) { if (needCmd[cmd] && me.queryCommandValue(cmd)) { me.execCommand('removeFormat', 'span,a', style); } range = me.selection.getRange(); range.applyInlineStyle('span', {'style': style + ':' + value}); mergesibling(range, cmdName,value); range.select(); } else { var span = domUtils.findParentByTagName(range.startContainer, 'span', true); text = me.document.createTextNode('font'); if (span && !span.children.length && !span[browser.ie ? 'innerText' : 'textContent'].replace(fillCharReg, '').length) { //for ie hack when enter range.insertNode(text); if (needCmd[cmd]) { range.selectNode(text).select(); me.execCommand('removeFormat', 'span,a', style, null); span = domUtils.findParentByTagName(text, 'span', true); range.setStartBefore(text); } span && (span.style.cssText += ';' + style + ':' + value); range.collapse(true).select(); } else { range.insertNode(text); range.selectNode(text).select(); span = range.document.createElement('span'); if (needCmd[cmd]) { //a标签内的不处理跳过 if (domUtils.findParentByTagName(text, 'a', true)) { range.setStartBefore(text).setCursor(); domUtils.remove(text); return; } me.execCommand('removeFormat', 'span,a', style); } span.style.cssText = style + ':' + value; text.parentNode.insertBefore(span, text); //修复,span套span 但样式不继承的问题 if (!browser.ie || browser.ie && browser.version == 9) { var spanParent = span.parentNode; while (!domUtils.isBlockElm(spanParent)) { if (spanParent.tagName == 'SPAN') { //opera合并style不会加入";" span.style.cssText = spanParent.style.cssText + ";" + span.style.cssText; } spanParent = spanParent.parentNode; } } if (opera) { setTimeout(function () { range.setStart(span, 0).collapse(true); mergesibling(range, cmdName,value); range.select(); }); } else { range.setStart(span, 0).collapse(true); mergesibling(range,cmdName,value); range.select(); } //trace:981 //domUtils.mergeToParent(span) } domUtils.remove(text); } } return true; }, queryCommandValue: function (cmdName) { var startNode = this.selection.getStart(); //trace:946 if (cmdName == 'underline' || cmdName == 'strikethrough') { var tmpNode = startNode, value; while (tmpNode && !domUtils.isBlockElm(tmpNode) && !domUtils.isBody(tmpNode)) { if (tmpNode.nodeType == 1) { value = domUtils.getComputedStyle(tmpNode, style); if (value != 'none') { return value; } } tmpNode = tmpNode.parentNode; } return 'none'; } if (cmdName == 'fontborder') { var tmp = startNode, val; while (tmp && dtd.$inline[tmp.tagName]) { if (val = domUtils.getComputedStyle(tmp, 'border')) { if (/1px/.test(val) && /solid/.test(val)) { return val; } } tmp = tmp.parentNode; } return '' } if( cmdName == 'FontSize' ) { var styleVal = domUtils.getComputedStyle(startNode, style), tmp = /^([\d\.]+)(\w+)$/.exec( styleVal ); if( tmp ) { return Math.floor( tmp[1] ) + tmp[2]; } return styleVal; } return domUtils.getComputedStyle(startNode, style); }, queryCommandState: function (cmdName) { if (!needCmd[cmdName]) return 0; var val = this.queryCommandValue(cmdName); if (cmdName == 'fontborder') { return /1px/.test(val) && /solid/.test(val) } else { return val == (cmdName == 'underline' ? 'underline' : 'line-through'); } } }; })(p, fonts[p]); } };///import core ///commands 清除格式 ///commandsName RemoveFormat ///commandsTitle 清除格式 /** * @description 清除格式 * @name baidu.editor.execCommand * @param {String} cmdName removeformat清除格式命令 * @param {String} tags 以逗号隔开的标签。如:span,a * @param {String} style 样式 * @param {String} attrs 属性 * @param {String} notIncluedA 是否把a标签切开 * @author zhanyi */ UE.plugins['removeformat'] = function(){ var me = this; me.setOpt({ 'removeFormatTags': 'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var', 'removeFormatAttributes':'class,style,lang,width,height,align,hspace,valign' }); me.commands['removeformat'] = { execCommand : function( cmdName, tags, style, attrs,notIncludeA ) { var tagReg = new RegExp( '^(?:' + (tags || this.options.removeFormatTags).replace( /,/g, '|' ) + ')$', 'i' ) , removeFormatAttributes = style ? [] : (attrs || this.options.removeFormatAttributes).split( ',' ), range = new dom.Range( this.document ), bookmark,node,parent, filter = function( node ) { return node.nodeType == 1; }; function isRedundantSpan (node) { if (node.nodeType == 3 || node.tagName.toLowerCase() != 'span'){ return 0; } if (browser.ie) { //ie 下判断实效,所以只能简单用style来判断 //return node.style.cssText == '' ? 1 : 0; var attrs = node.attributes; if ( attrs.length ) { for ( var i = 0,l = attrs.length; i<l; i++ ) { if ( attrs[i].specified ) { return 0; } } return 1; } } return !node.attributes.length; } function doRemove( range ) { var bookmark1 = range.createBookmark(); if ( range.collapsed ) { range.enlarge( true ); } //不能把a标签切了 if(!notIncludeA){ var aNode = domUtils.findParentByTagName(range.startContainer,'a',true); if(aNode){ range.setStartBefore(aNode); } aNode = domUtils.findParentByTagName(range.endContainer,'a',true); if(aNode){ range.setEndAfter(aNode); } } bookmark = range.createBookmark(); node = bookmark.start; //切开始 while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } if ( bookmark.end ) { //切结束 node = bookmark.end; while ( (parent = node.parentNode) && !domUtils.isBlockElm( parent ) ) { domUtils.breakParent( node, parent ); domUtils.clearEmptySibling( node ); } //开始去除样式 var current = domUtils.getNextDomNode( bookmark.start, false, filter ), next; while ( current ) { if ( current == bookmark.end ) { break; } next = domUtils.getNextDomNode( current, true, filter ); if ( !dtd.$empty[current.tagName.toLowerCase()] && !domUtils.isBookmarkNode( current ) ) { if ( tagReg.test( current.tagName ) ) { if ( style ) { domUtils.removeStyle( current, style ); if ( isRedundantSpan( current ) && style != 'text-decoration'){ domUtils.remove( current, true ); } } else { domUtils.remove( current, true ); } } else { //trace:939 不能把list上的样式去掉 if(!dtd.$tableContent[current.tagName] && !dtd.$list[current.tagName]){ domUtils.removeAttributes( current, removeFormatAttributes ); if ( isRedundantSpan( current ) ){ domUtils.remove( current, true ); } } } } current = next; } } //trace:1035 //trace:1096 不能把td上的样式去掉,比如边框 var pN = bookmark.start.parentNode; if(domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName] && !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } pN = bookmark.end.parentNode; if(bookmark.end && domUtils.isBlockElm(pN) && !dtd.$tableContent[pN.tagName]&& !dtd.$list[pN.tagName]){ domUtils.removeAttributes( pN,removeFormatAttributes ); } range.moveToBookmark( bookmark ).moveToBookmark(bookmark1); //清除冗余的代码 <b><bookmark></b> var node = range.startContainer, tmp, collapsed = range.collapsed; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setStartBefore(node); //trace:937 //更新结束边界 if(range.startContainer === range.endContainer){ range.endOffset--; } domUtils.remove(node); node = tmp; } if(!collapsed){ node = range.endContainer; while(node.nodeType == 1 && domUtils.isEmptyNode(node) && dtd.$removeEmpty[node.tagName]){ tmp = node.parentNode; range.setEndBefore(node); domUtils.remove(node); node = tmp; } } } range = this.selection.getRange(); doRemove( range ); range.select(); } }; }; ///import core ///import plugins/inserthtml.js ///commands 插入代码 ///commandsName code ///commandsTitle 插入代码 UE.plugins['insertcode'] = function() { var me = this; me.ready(function(){ utils.cssRule('pre','pre{margin:.5em 0;padding:.4em .6em;border-radius:8px;background:#f8f8f8;}', me.document) }); me.setOpt('insertcode',{ 'as3':'ActionScript3', 'bash':'Bash/Shell', 'cpp':'C/C++', 'css':'Css', 'cf':'CodeFunction', 'c#':'C#', 'delphi':'Delphi', 'diff':'Diff', 'erlang':'Erlang', 'groovy':'Groovy', 'html':'Html', 'java':'Java', 'jfx':'JavaFx', 'js':'Javascript', 'pl':'Perl', 'php':'Php', 'plain':'Plain Text', 'ps':'PowerShell', 'python':'Python', 'ruby':'Ruby', 'scala':'Scala', 'sql':'Sql', 'vb':'Vb', 'xml':'Xml' }); me.commands['insertcode'] = { execCommand : function(cmd,lang){ var me = this, rng = me.selection.getRange(), pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ pre.className = 'brush:'+lang+';toolbar:false;'; }else{ var code = ''; if(rng.collapsed){ code = browser.ie? (browser.version > 8 ? '' : '&nbsp;'):'<br/>'; }else{ var frag = rng.extractContents(); var div = me.document.createElement('div'); div.appendChild(frag); utils.each(UE.filterNode(UE.htmlparser(div.innerHTML.replace(/[\r\t]/g,'')),me.options.filterTxtRules).children,function(node){ if(browser.ie && browser.version > 8){ if(node.type =='element'){ if(node.tagName == 'br'){ code += '\n' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ code += '\n' }else if(!dtd.$empty[node.tagName]){ code += cn.innerText(); } }else{ code += cn.data } }) if(!/\n$/.test(code)){ code += '\n'; } } }else{ code += node.data + '\n' } if(!node.nextSibling() && /\n$/.test(code)){ code = code.replace(/\n$/,''); } }else{ if(browser.ie){ if(node.type =='element'){ if(node.tagName == 'br'){ code += '<br>' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ code += '<br>' }else if(!dtd.$empty[node.tagName]){ code += cn.innerText(); } }else{ code += cn.data } }); if(!/br>$/.test(code)){ code += '<br>'; } } }else{ code += node.data + '<br>' } if(!node.nextSibling() && /<br>$/.test(code)){ code = code.replace(/<br>$/,''); } }else{ code += (node.type == 'element' ? (dtd.$empty[node.tagName] ? '' : node.innerText()) : node.data); if(!/br\/?\s*>$/.test(code)){ if(!node.nextSibling()) return; code += '<br>' } } } }); } me.execCommand('inserthtml','<pre id="coder"class="brush:'+lang+';toolbar:false">'+code+'</pre>',true); pre = me.document.getElementById('coder'); domUtils.removeAttributes(pre,'id'); var tmpNode = pre.previousSibling; if(tmpNode && (tmpNode.nodeType == 3 && tmpNode.nodeValue.length == 1 && browser.ie && browser.version == 6 || domUtils.isEmptyBlock(tmpNode))){ domUtils.remove(tmpNode) } var rng = me.selection.getRange(); if(domUtils.isEmptyBlock(pre)){ rng.setStart(pre,0).setCursor(false,true) }else{ rng.selectNodeContents(pre).select() } } }, queryCommandValue : function(){ var path = this.selection.getStartElementPath(); var lang = ''; utils.each(path,function(node){ if(node.nodeName =='PRE'){ var match = node.className.match(/brush:([^;]+)/); lang = match && match[1] ? match[1] : ''; return false; } }); return lang; } }; me.addInputRule(function(root){ utils.each(root.getNodesByTagName('pre'),function(pre){ var brs = pre.getNodesByTagName('br'); if(brs.length){ browser.ie && browser.version > 8 && utils.each(brs,function(br){ var txt = UE.uNode.createText('\n'); br.parentNode.insertBefore(txt,br); br.parentNode.removeChild(br); }); return; } if(browser.ie && browser.version > 8) return; var code = pre.innerText().split(/\n/); pre.innerHTML(''); utils.each(code,function(c){ if(c.length){ pre.appendChild(UE.uNode.createText(c)); } pre.appendChild(UE.uNode.createElement('br')) }) }) }); me.addOutputRule(function(root){ utils.each(root.getNodesByTagName('pre'),function(pre){ var code = ''; utils.each(pre.children,function(n){ if(n.type == 'text'){ //在ie下文本内容有可能末尾带有\n要去掉 //trace:3396 code += n.data.replace(/[ ]/g,'&nbsp;').replace(/\n$/,''); }else{ if(n.tagName == 'br'){ code += '\n' }else{ code += (!dtd.$empty[n.tagName] ? '' : n.innerText()); } } }); pre.innerText(code.replace(/(&nbsp;|\n)+$/,'')) }) }); //不需要判断highlight的command列表 me.notNeedCodeQuery ={ help:1, undo:1, redo:1, source:1, print:1, searchreplace:1, fullscreen:1, preview:1, insertparagraph:1, elementpath:1, highlightcode:1, insertcode:1, inserthtml:1, selectall:1 }; //将queyCommamndState重置 var orgQuery = me.queryCommandState; me.queryCommandState = function(cmd){ var me = this; if(!me.notNeedCodeQuery[cmd.toLowerCase()] && me.selection && me.queryCommandValue('insertcode')){ return -1; } return UE.Editor.prototype.queryCommandState.apply(this,arguments) }; me.addListener('beforeenterkeydown',function(){ var rng = me.selection.getRange(); var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ me.fireEvent('saveScene'); if(!rng.collapsed){ rng.deleteContents(); } if(!browser.ie ){ var tmpNode = me.document.createElement('br'),pre; rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true); var next = tmpNode.nextSibling; if(!next){ rng.insertNode(tmpNode.cloneNode(false)); }else{ rng.setStartAfter(tmpNode); } pre = tmpNode.previousSibling; var tmp; while(pre ){ tmp = pre; pre = pre.previousSibling; if(!pre || pre.nodeName == 'BR'){ pre = tmp; break; } } if(pre){ var str = ''; while(pre && pre.nodeName != 'BR' && new RegExp('^[\\s'+domUtils.fillChar+']*$').test(pre.nodeValue)){ str += pre.nodeValue; pre = pre.nextSibling; } if(pre.nodeName != 'BR'){ var match = pre.nodeValue.match(new RegExp('^([\\s'+domUtils.fillChar+']+)')); if(match && match[1]){ str += match[1] } } if(str){ str = me.document.createTextNode(str); rng.insertNode(str).setStartAfter(str); } } rng.collapse(true).select(true); }else{ if(browser.version > 8){ var txt = me.document.createTextNode('\n'); var start = rng.startContainer; if(rng.startOffset == 0){ var preNode = start.previousSibling; if(preNode){ rng.insertNode(txt); var fillchar = me.document.createTextNode(' '); rng.setStartAfter(txt).insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true) } }else{ rng.insertNode(txt).setStartAfter(txt); var fillchar = me.document.createTextNode(' '); start = rng.startContainer.childNodes[rng.startOffset]; if(start && !/^\n/.test(start.nodeValue)){ rng.setStartBefore(txt) } rng.insertNode(fillchar).setStart(fillchar,0).collapse(true).select(true) } }else{ var tmpNode = me.document.createElement('br'); rng.insertNode(tmpNode); rng.insertNode(me.document.createTextNode(domUtils.fillChar)); rng.setStartAfter(tmpNode); pre = tmpNode.previousSibling; var tmp; while(pre ){ tmp = pre; pre = pre.previousSibling; if(!pre || pre.nodeName == 'BR'){ pre = tmp; break; } } if(pre){ var str = ''; while(pre && pre.nodeName != 'BR' && new RegExp('^[ '+domUtils.fillChar+']*$').test(pre.nodeValue)){ str += pre.nodeValue; pre = pre.nextSibling; } if(pre.nodeName != 'BR'){ var match = pre.nodeValue.match(new RegExp('^([ '+domUtils.fillChar+']+)')); if(match && match[1]){ str += match[1] } } str = me.document.createTextNode(str); rng.insertNode(str).setStartAfter(str); } rng.collapse(true).select(); } } me.fireEvent('saveScene'); return true; } }); me.addListener('tabkeydown',function(cmd,evt){ var rng = me.selection.getRange(); var pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ me.fireEvent('saveScene'); if(evt.shiftKey){ // if(!rng.collapsed){ // var bk = rng.createBookmark(); // var start = bk.start.previousSibling; // if(start === pre.firstChild){ // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // }else{ // while(start){ // if(domUtils.isBr(start)){ // start = start.nextSibling; // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // break; // } // while(start.previousSibling && start.previousSibling.nodeType == 3){ // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue; // domUtils.remove(start.previousSibling) // } // start = start.previousSibling; // } // } // // var end = bk.end; // start = bk.start.nextSibling; // // while(start && start !== end){ // if(domUtils.isBr(start) && start.nextSibling){ // if(start.nextSibling === end){ // break; // } // start = start.nextSibling; // while(start.nextSibling && start.nextSibling.nodeType == 3){ // start.nodeValue += start.nextSibling.nodeValue; // domUtils.remove(start.nextSibling) // } // // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // } // // start = start.nextSibling; // } // rng.moveToBookmark(bk).select(); // }else{ // var bk = rng.createBookmark(); // var start = bk.start.previousSibling; // if(start === pre.firstChild){ // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // }else{ // while(start){ // if(domUtils.isBr(start)){ // start = start.nextSibling; // start.nodeValue = start.nodeValue.replace(/^\s{4}/,''); // break; // } // while(start.previousSibling && start.previousSibling.nodeType == 3){ // start.nodeValue = start.previousSibling.nodeValue + start.nodeValue; // domUtils.remove(start.previousSibling) // } // start = start.previousSibling; // } // } // } }else{ if(!rng.collapsed){ var bk = rng.createBookmark(); var start = bk.start.previousSibling; while(start){ if(pre.firstChild === start && !domUtils.isBr(start)){ pre.insertBefore(me.document.createTextNode(' '),start); break; } if(domUtils.isBr(start)){ pre.insertBefore(me.document.createTextNode(' '),start.nextSibling); break; } start = start.previousSibling; } var end = bk.end; start = bk.start.nextSibling; if(pre.firstChild === bk.start){ pre.insertBefore(me.document.createTextNode(' '),start.nextSibling) } while(start && start !== end){ if(domUtils.isBr(start) && start.nextSibling){ if(start.nextSibling === end){ break; } pre.insertBefore(me.document.createTextNode(' '),start.nextSibling) } start = start.nextSibling; } rng.moveToBookmark(bk).select(); }else{ var tmpNode = me.document.createTextNode(' '); rng.insertNode(tmpNode).setStartAfter(tmpNode).collapse(true).select(true); } } me.fireEvent('saveScene'); return true; } }); me.addListener('beforeinserthtml',function(evtName,html){ var me = this, rng = me.selection.getRange(), pre = domUtils.findParentByTagName(rng.startContainer,'pre',true); if(pre){ if(!rng.collapsed){ rng.deleteContents() } var htmlstr = ''; if(browser.ie && browser.version > 8){ utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){ if(node.type =='element'){ if(node.tagName == 'br'){ htmlstr += '\n' }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ htmlstr += '\n' }else if(!dtd.$empty[node.tagName]){ htmlstr += cn.innerText(); } }else{ htmlstr += cn.data } }) if(!/\n$/.test(htmlstr)){ htmlstr += '\n'; } } }else{ htmlstr += node.data + '\n' } if(!node.nextSibling() && /\n$/.test(htmlstr)){ htmlstr = htmlstr.replace(/\n$/,''); } }); var tmpNode = me.document.createTextNode(utils.html(htmlstr.replace(/&nbsp;/g,' '))); rng.insertNode(tmpNode).selectNode(tmpNode).select(); }else{ var frag = me.document.createDocumentFragment(); utils.each(UE.filterNode(UE.htmlparser(html),me.options.filterTxtRules).children,function(node){ if(node.type =='element'){ if(node.tagName == 'br'){ frag.appendChild(me.document.createElement('br')) }else if(!dtd.$empty[node.tagName]){ utils.each(node.children,function(cn){ if(cn.type =='element'){ if(cn.tagName == 'br'){ frag.appendChild(me.document.createElement('br')) }else if(!dtd.$empty[node.tagName]){ frag.appendChild(me.document.createTextNode(utils.html(cn.innerText().replace(/&nbsp;/g,' ')))); } }else{ frag.appendChild(me.document.createTextNode(utils.html( cn.data.replace(/&nbsp;/g,' ')))); } }) if(frag.lastChild.nodeName != 'BR'){ frag.appendChild(me.document.createElement('br')) } } }else{ frag.appendChild(me.document.createTextNode(utils.html( node.data.replace(/&nbsp;/g,' ')))); } if(!node.nextSibling() && frag.lastChild.nodeName == 'BR'){ frag.removeChild(frag.lastChild) } }); rng.insertNode(frag).select(); } return true; } }); //方向键的处理 me.addListener('keydown',function(cmd,evt){ var me = this,keyCode = evt.keyCode || evt.which; if(keyCode == 40){ var rng = me.selection.getRange(),pre,start = rng.startContainer; if(rng.collapsed && (pre = domUtils.findParentByTagName(rng.startContainer,'pre',true)) && !pre.nextSibling){ var last = pre.lastChild while(last && last.nodeName == 'BR'){ last = last.previousSibling; } if(last === start || rng.startContainer === pre && rng.startOffset == pre.childNodes.length){ me.execCommand('insertparagraph'); domUtils.preventDefault(evt) } } } }); //trace:3395 me.addListener('delkeydown',function(type,evt){ var rng = this.selection.getRange(); rng.txtToElmBoundary(true); var start = rng.startContainer; if(domUtils.isTagNode(start,'pre') && rng.collapsed && domUtils.isStartInblock(rng)){ var p = me.document.createElement('p'); domUtils.fillNode(me.document,p); start.parentNode.insertBefore(p,start); domUtils.remove(start); rng.setStart(p,0).setCursor(false,true); domUtils.preventDefault(evt); return true; } }) }; ///import core ///commands 字数统计 ///commandsName WordCount,wordCount ///commandsTitle 字数统计 /** * Created by JetBrains WebStorm. * User: taoqili * Date: 11-9-7 * Time: 下午8:18 * To change this template use File | Settings | File Templates. */ UE.plugins['wordcount'] = function(){ var me = this; me.addListener('contentchange',function(){ me.fireEvent('wordcount'); }); var timer; me.addListener('ready',function(){ var me = this; domUtils.on(me.body,"keyup",function(evt){ var code = evt.keyCode||evt.which, //忽略的按键,ctr,alt,shift,方向键 ignores = {"16":1,"18":1,"20":1,"37":1,"38":1,"39":1,"40":1}; if(code in ignores) return; clearTimeout(timer); timer = setTimeout(function(){ me.fireEvent('wordcount'); },200) }) }); }; UE.plugins['dragdrop'] = function (){ var me = this; me.ready(function(){ domUtils.on(this.body,'dragend',function(){ var rng = me.selection.getRange(); var node = rng.getClosedNode()||me.selection.getStart(); if(node && node.tagName == 'IMG'){ var pre = node.previousSibling,next; while(next = node.nextSibling){ if(next.nodeType == 1 && next.tagName == 'SPAN' && !next.firstChild){ domUtils.remove(next) }else{ break; } } if((pre && pre.nodeType == 1 && !domUtils.isEmptyBlock(pre) || !pre) && (!next || next && !domUtils.isEmptyBlock(next))){ if(pre && pre.tagName == 'P' && !domUtils.isEmptyBlock(pre)){ pre.appendChild(node); domUtils.moveChild(next,pre); domUtils.remove(next); }else if(next && next.tagName == 'P' && !domUtils.isEmptyBlock(next)){ next.insertBefore(node,next.firstChild); } if(pre && pre.tagName == 'P' && domUtils.isEmptyBlock(pre)){ domUtils.remove(pre) } if(next && next.tagName == 'P' && domUtils.isEmptyBlock(next)){ domUtils.remove(next) } rng.selectNode(node).select(); me.fireEvent('saveScene'); } } }) }); me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) { var rng = me.selection.getRange(),node; if(node = domUtils.findParentByTagName(rng.startContainer,'p',true)){ if(domUtils.getComputedStyle(node,'text-align') == 'center'){ domUtils.removeStyle(node,'text-align') } } } }) }; ///import core ///import plugins/inserthtml.js ///import plugins/undo.js ///import plugins/serialize.js ///commands 粘贴 ///commandsName PastePlain ///commandsTitle 纯文本粘贴模式 /* ** @description 粘贴 * @author zhanyi */ UE.plugins['paste'] = function () { function getClipboardData(callback) { var doc = this.document; if (doc.getElementById('baidu_pastebin')) { return; } var range = this.selection.getRange(), bk = range.createBookmark(), //创建剪贴的容器div pastebin = doc.createElement('div'); pastebin.id = 'baidu_pastebin'; // Safari 要求div必须有内容,才能粘贴内容进来 browser.webkit && pastebin.appendChild(doc.createTextNode(domUtils.fillChar + domUtils.fillChar)); doc.body.appendChild(pastebin); //trace:717 隐藏的span不能得到top //bk.start.innerHTML = '&nbsp;'; bk.start.style.display = ''; pastebin.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;left:-1000px;white-space:nowrap;top:" + //要在现在光标平行的位置加入,否则会出现跳动的问题 domUtils.getXY(bk.start).y + 'px'; range.selectNodeContents(pastebin).select(true); setTimeout(function () { if (browser.webkit) { for (var i = 0, pastebins = doc.querySelectorAll('#baidu_pastebin'), pi; pi = pastebins[i++];) { if (domUtils.isEmptyNode(pi)) { domUtils.remove(pi); } else { pastebin = pi; break; } } } try { pastebin.parentNode.removeChild(pastebin); } catch (e) { } range.moveToBookmark(bk).select(true); callback(pastebin); }, 0); } var me = this; var txtContent, htmlContent, address; function filter(div) { var html; if (div.firstChild) { //去掉cut中添加的边界值 var nodes = domUtils.getElementsByTagName(div, 'span'); for (var i = 0, ni; ni = nodes[i++];) { if (ni.id == '_baidu_cut_start' || ni.id == '_baidu_cut_end') { domUtils.remove(ni); } } if (browser.webkit) { var brs = div.querySelectorAll('div br'); for (var i = 0, bi; bi = brs[i++];) { var pN = bi.parentNode; if (pN.tagName == 'DIV' && pN.childNodes.length == 1) { pN.innerHTML = '<p><br/></p>'; domUtils.remove(pN); } } var divs = div.querySelectorAll('#baidu_pastebin'); for (var i = 0, di; di = divs[i++];) { var tmpP = me.document.createElement('p'); di.parentNode.insertBefore(tmpP, di); while (di.firstChild) { tmpP.appendChild(di.firstChild); } domUtils.remove(di); } var metas = div.querySelectorAll('meta'); for (var i = 0, ci; ci = metas[i++];) { domUtils.remove(ci); } var brs = div.querySelectorAll('br'); for (i = 0; ci = brs[i++];) { if (/^apple-/i.test(ci.className)) { domUtils.remove(ci); } } } if (browser.gecko) { var dirtyNodes = div.querySelectorAll('[_moz_dirty]'); for (i = 0; ci = dirtyNodes[i++];) { ci.removeAttribute('_moz_dirty'); } } if (!browser.ie) { var spans = div.querySelectorAll('span.Apple-style-span'); for (var i = 0, ci; ci = spans[i++];) { domUtils.remove(ci, true); } } //ie下使用innerHTML会产生多余的\r\n字符,也会产生&nbsp;这里过滤掉 html = div.innerHTML;//.replace(/>(?:(\s|&nbsp;)*?)</g,'><'); //过滤word粘贴过来的冗余属性 html = UE.filterWord(html); //取消了忽略空白的第二个参数,粘贴过来的有些是有空白的,会被套上相关的标签 var root = UE.htmlparser(html); //如果给了过滤规则就先进行过滤 if (me.options.filterRules) { UE.filterNode(root, me.options.filterRules); } //执行默认的处理 me.filterInputRule(root); //针对chrome的处理 if (browser.webkit) { var br = root.lastChild(); if (br && br.type == 'element' && br.tagName == 'br') { root.removeChild(br) } utils.each(me.body.querySelectorAll('div'), function (node) { if (domUtils.isEmptyBlock(node)) { domUtils.remove(node) } }) } html = {'html': root.toHtml()}; me.fireEvent('beforepaste', html, root); //抢了默认的粘贴,那后边的内容就不执行了,比如表格粘贴 if(!html.html){ return; } root = UE.htmlparser(html.html,true); //如果开启了纯文本模式 if (me.queryCommandState('pasteplain') === 1) { me.execCommand('insertHtml', UE.filterNode(root, me.options.filterTxtRules).toHtml(), true); } else { //文本模式 UE.filterNode(root, me.options.filterTxtRules); txtContent = root.toHtml(); //完全模式 htmlContent = html.html; address = me.selection.getRange().createAddress(true); me.execCommand('insertHtml', htmlContent, true); } me.fireEvent("afterpaste", html); } } me.addListener('pasteTransfer', function (cmd, plainType) { if (address && txtContent && htmlContent && txtContent != htmlContent) { var range = me.selection.getRange(); range.moveToAddress(address, true); if (!range.collapsed) { while (!domUtils.isBody(range.startContainer) ) { var start = range.startContainer; if(start.nodeType == 1){ start = start.childNodes[range.startOffset]; if(!start){ range.setStartBefore(range.startContainer); continue; } var pre = start.previousSibling; if(pre && pre.nodeType == 3 && new RegExp('^[\n\r\t '+domUtils.fillChar+']*$').test(pre.nodeValue)){ range.setStartBefore(pre) } } if(range.startOffset == 0){ range.setStartBefore(range.startContainer); }else{ break; } } while (!domUtils.isBody(range.endContainer) ) { var end = range.endContainer; if(end.nodeType == 1){ end = end.childNodes[range.endOffset]; if(!end){ range.setEndAfter(range.endContainer); continue; } var next = end.nextSibling; if(next && next.nodeType == 3 && new RegExp('^[\n\r\t'+domUtils.fillChar+']*$').test(next.nodeValue)){ range.setEndAfter(next) } } if(range.endOffset == range.endContainer[range.endContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length){ range.setEndAfter(range.endContainer); }else{ break; } } } range.deleteContents(); range.select(true); me.__hasEnterExecCommand = true; var html = htmlContent; if (plainType === 2) { html = html.replace(/<(\/?)([\w\-]+)([^>]*)>/gi, function (a, b, tagName, attrs) { tagName = tagName.toLowerCase(); if ({img: 1}[tagName]) { return a; } attrs = attrs.replace(/([\w\-]*?)\s*=\s*(("([^"]*)")|('([^']*)')|([^\s>]+))/gi, function (str, atr, val) { if ({ 'src': 1, 'href': 1, 'name': 1 }[atr.toLowerCase()]) { return atr + '=' + val + ' ' } return '' }); if ({ 'span': 1, 'div': 1 }[tagName]) { return '' } else { return '<' + b + tagName + ' ' + utils.trim(attrs) + '>' } }); } else if (plainType) { html = txtContent; } me.execCommand('inserthtml', html, true); me.__hasEnterExecCommand = false; var rng = me.selection.getRange(); while (!domUtils.isBody(rng.startContainer) && !rng.startOffset && rng.startContainer[rng.startContainer.nodeType == 3 ? 'nodeValue' : 'childNodes'].length ) { rng.setStartBefore(rng.startContainer); } var tmpAddress = rng.createAddress(true); address.endAddress = tmpAddress.startAddress; } }); me.addListener('ready', function () { domUtils.on(me.body, 'cut', function () { var range = me.selection.getRange(); if (!range.collapsed && me.undoManger) { me.undoManger.save(); } }); //ie下beforepaste在点击右键时也会触发,所以用监控键盘才处理 domUtils.on(me.body, browser.ie || browser.opera ? 'keydown' : 'paste', function (e) { if ((browser.ie || browser.opera) && ((!e.ctrlKey && !e.metaKey) || e.keyCode != '86')) { return; } getClipboardData.call(me, function (div) { filter(div); }); }); }); }; ///import core ///commands 有序列表,无序列表 ///commandsName InsertOrderedList,InsertUnorderedList ///commandsTitle 有序列表,无序列表 /** * 有序列表 * @function * @name baidu.editor.execCommand * @param {String} cmdName insertorderlist插入有序列表 * @param {String} style 值为:decimal,lower-alpha,lower-roman,upper-alpha,upper-roman * @author zhanyi */ /** * 无序链接 * @function * @name baidu.editor.execCommand * @param {String} cmdName insertunorderlist插入无序列表 * * @param {String} style 值为:circle,disc,square * @author zhanyi */ UE.plugins['list'] = function () { var me = this, notExchange = { 'TD':1, 'PRE':1, 'BLOCKQUOTE':1 }; var customStyle = { 'cn' : 'cn-1-', 'cn1' : 'cn-2-', 'cn2' : 'cn-3-', 'num': 'num-1-', 'num1' : 'num-2-', 'num2' : 'num-3-', 'dash' : 'dash', 'dot':'dot' }; me.setOpt( { 'insertorderedlist':{ 'num':'', 'num1':'', 'num2':'', 'cn':'', 'cn1':'', 'cn2':'', 'decimal':'', 'lower-alpha':'', 'lower-roman':'', 'upper-alpha':'', 'upper-roman':'' }, 'insertunorderedlist':{ 'circle':'', 'disc':'', 'square':'', 'dash' : '', 'dot':'' }, listDefaultPaddingLeft : '30', listiconpath : 'http://bs.baidu.com/listicon/', maxListLevel : -1//-1不限制 } ); function listToArray(list){ var arr = []; for(var p in list){ arr.push(p) } return arr; } var listStyle = { 'OL':listToArray(me.options.insertorderedlist), 'UL':listToArray(me.options.insertunorderedlist) }; var liiconpath = me.options.listiconpath; //根据用户配置,调整customStyle for(var s in customStyle){ if(!me.options.insertorderedlist.hasOwnProperty(s) && !me.options.insertunorderedlist.hasOwnProperty(s)){ delete customStyle[s]; } } me.ready(function () { var customCss = []; for(var p in customStyle){ if(p == 'dash' || p == 'dot'){ customCss.push('li.list-' + customStyle[p] + '{background-image:url(' + liiconpath +customStyle[p]+'.gif)}'); customCss.push('ul.custom_'+p+'{list-style:none;}ul.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}'); }else{ for(var i= 0;i<99;i++){ customCss.push('li.list-' + customStyle[p] + i + '{background-image:url(' + liiconpath + 'list-'+customStyle[p] + i + '.gif)}') } customCss.push('ol.custom_'+p+'{list-style:none;}ol.custom_'+p+' li{background-position:0 3px;background-repeat:no-repeat}'); } switch(p){ case 'cn': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}'); break; case 'cn1': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:30px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:55px}'); break; case 'cn2': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:40px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:55px}'); customCss.push('li.list-'+p+'-paddingleft-3{padding-left:68px}'); break; case 'num': case 'num1': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:25px}'); break; case 'num2': customCss.push('li.list-'+p+'-paddingleft-1{padding-left:35px}'); customCss.push('li.list-'+p+'-paddingleft-2{padding-left:40px}'); break; case 'dash': customCss.push('li.list-'+p+'-paddingleft{padding-left:35px}'); break; case 'dot': customCss.push('li.list-'+p+'-paddingleft{padding-left:20px}'); } } customCss.push('.list-paddingleft-1{padding-left:0}'); customCss.push('.list-paddingleft-2{padding-left:'+me.options.listDefaultPaddingLeft+'px}'); customCss.push('.list-paddingleft-3{padding-left:'+me.options.listDefaultPaddingLeft*2+'px}'); //如果不给宽度会在自定应样式里出现滚动条 utils.cssRule('list', 'ol,ul{margin:0;pading:0;'+(browser.ie ? '' : 'width:95%')+'}li{clear:both;}'+customCss.join('\n'), me.document); }); //单独处理剪切的问题 me.ready(function(){ domUtils.on(me.body,'cut',function(){ setTimeout(function(){ var rng = me.selection.getRange(),li; //trace:3416 if(!rng.collapsed){ if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){ if(!li.nextSibling && domUtils.isEmptyBlock(li)){ var pn = li.parentNode,node; if(node = pn.previousSibling){ domUtils.remove(pn); rng.setStartAtLast(node).collapse(true); rng.select(true); }else if(node = pn.nextSibling){ domUtils.remove(pn); rng.setStartAtFirst(node).collapse(true); rng.select(true); }else{ var tmpNode = me.document.createElement('p'); domUtils.fillNode(me.document,tmpNode); pn.parentNode.insertBefore(tmpNode,pn); domUtils.remove(pn); rng.setStart(tmpNode,0).collapse(true); rng.select(true); } } } } }) }) }); function getStyle(node){ var cls = node.className; if(domUtils.hasClass(node,/custom_/)){ return cls.match(/custom_(\w+)/)[1] } return domUtils.getStyle(node, 'list-style-type') } me.addListener('beforepaste',function(type,html){ var me = this, rng = me.selection.getRange(),li; var root = UE.htmlparser(html.html,true); if(li = domUtils.findParentByTagName(rng.startContainer,'li',true)){ var list = li.parentNode,tagName = list.tagName == 'OL' ? 'ul':'ol'; utils.each(root.getNodesByTagName(tagName),function(n){ n.tagName = list.tagName; n.setAttr(); if(n.parentNode === root){ type = getStyle(list) || (list.tagName == 'OL' ? 'decimal' : 'disc') }else{ var className = n.parentNode.getAttr('class'); if(className && /custom_/.test(className)){ type = className.match(/custom_(\w+)/)[1] }else{ type = n.parentNode.getStyle('list-style-type'); } if(!type){ type = list.tagName == 'OL' ? 'decimal' : 'disc'; } } var index = utils.indexOf(listStyle[list.tagName], type); if(n.parentNode !== root) index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][index]; if(customStyle[currentStyle]){ n.setAttr('class', 'custom_' + currentStyle) }else{ n.setStyle('list-style-type',currentStyle) } }) } html.html = root.toHtml(); }); //进入编辑器的li要套p标签 me.addInputRule(function(root){ utils.each(root.getNodesByTagName('li'),function(li){ var tmpP = UE.uNode.createElement('p'); for(var i= 0,ci;ci=li.children[i];){ if(ci.type == 'text' || dtd.p[ci.tagName]){ tmpP.appendChild(ci); }else{ if(tmpP.firstChild()){ li.insertBefore(tmpP,ci); tmpP = UE.uNode.createElement('p'); i = i + 2; }else{ i++; } } } if(tmpP.firstChild() && !tmpP.parentNode || !li.firstChild()){ li.appendChild(tmpP); } //trace:3357 //p不能为空 if (!tmpP.firstChild()) { tmpP.innerHTML(browser.ie ? '&nbsp;' : '<br/>') } //去掉末尾的空白 var p = li.firstChild(); var lastChild = p.lastChild(); if(lastChild && lastChild.type == 'text' && /^\s*$/.test(lastChild.data)){ p.removeChild(lastChild) } }); var orderlisttype = { 'num1':/^\d+\)/, 'decimal':/^\d+\./, 'lower-alpha':/^[a-z]+\)/, 'upper-alpha':/^[A-Z]+\./, 'cn':/^[\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+[\u3001]/, 'cn2':/^\([\u4E00\u4E8C\u4E09\u56DB\u516d\u4e94\u4e03\u516b\u4e5d]+\)/ }, unorderlisttype = { 'square':'n' }; function checkListType(content,container){ var span = container.firstChild(); if(span && span.type == 'element' && span.tagName == 'span' && /Wingdings|Symbol/.test(span.getStyle('font-family'))){ for(var p in unorderlisttype){ if(unorderlisttype[p] == span.data){ return p } } return 'disc' } for(var p in orderlisttype){ if(orderlisttype[p].test(content)){ return p; } } } utils.each(root.getNodesByTagName('p'),function(node){ if(node.getAttr('class') != 'MsoListParagraph'){ return } //word粘贴过来的会带有margin要去掉,但这样也可能会误命中一些央视 node.setStyle('margin',''); node.setStyle('margin-left',''); node.setAttr('class',''); function appendLi(list,p,type){ if(list.tagName == 'ol'){ if(browser.ie){ var first = p.firstChild(); if(first.type =='element' && first.tagName == 'span' && orderlisttype[type].test(first.innerText())){ p.removeChild(first); } }else{ p.innerHTML(p.innerHTML().replace(orderlisttype[type],'')); } }else{ p.removeChild(p.firstChild()) } var li = UE.uNode.createElement('li'); li.appendChild(p); list.appendChild(li); } var tmp = node,type,cacheNode = node; if(node.parentNode.tagName != 'li' && (type = checkListType(node.innerText(),node))){ var list = UE.uNode.createElement(me.options.insertorderedlist.hasOwnProperty(type) ? 'ol' : 'ul'); if(customStyle[type]){ list.setAttr('class','custom_'+type) }else{ list.setStyle('list-style-type',type) } while(node && node.parentNode.tagName != 'li' && checkListType(node.innerText(),node)){ tmp = node.nextSibling(); if(!tmp){ node.parentNode.insertBefore(list,node) } appendLi(list,node,type); node = tmp; } if(!list.parentNode && node && node.parentNode){ node.parentNode.insertBefore(list,node) } } var span = cacheNode.firstChild(); if(span && span.type == 'element' && span.tagName == 'span' && /^\s*(&nbsp;)+\s*$/.test(span.innerText())){ span.parentNode.removeChild(span) } }) }); //调整索引标签 me.addListener('contentchange',function(){ adjustListStyle(me.document) }); function adjustListStyle(doc,ignore){ utils.each(domUtils.getElementsByTagName(doc,'ol ul'),function(node){ if(!domUtils.inDoc(node,doc)) return; var parent = node.parentNode; if(parent.tagName == node.tagName){ var nodeStyleType = getStyle(node) || (node.tagName == 'OL' ? 'decimal' : 'disc'), parentStyleType = getStyle(parent) || (parent.tagName == 'OL' ? 'decimal' : 'disc'); if(nodeStyleType == parentStyleType){ var styleIndex = utils.indexOf(listStyle[node.tagName], nodeStyleType); styleIndex = styleIndex + 1 == listStyle[node.tagName].length ? 0 : styleIndex + 1; setListStyle(node,listStyle[node.tagName][styleIndex]) } } var index = 0,type = 2; if( domUtils.hasClass(node,/custom_/)){ if(!(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/))){ type = 1; } }else{ if(/[ou]l/i.test(parent.tagName) && domUtils.hasClass(parent,/custom_/)){ type = 3; } } var style = domUtils.getStyle(node, 'list-style-type'); style && (node.style.cssText = 'list-style-type:' + style); node.className = utils.trim(node.className.replace(/list-paddingleft-\w+/,'')) + ' list-paddingleft-' + type; utils.each(domUtils.getElementsByTagName(node,'li'),function(li){ li.style.cssText && (li.style.cssText = ''); if(!li.firstChild){ domUtils.remove(li); return; } if(li.parentNode !== node){ return; } index++; if(domUtils.hasClass(node,/custom_/) ){ var paddingLeft = 1,currentStyle = getStyle(node); if(node.tagName == 'OL'){ if(currentStyle){ switch(currentStyle){ case 'cn' : case 'cn1': case 'cn2': if(index > 10 && (index % 10 == 0 || index > 10 && index < 20)){ paddingLeft = 2 }else if(index > 20){ paddingLeft = 3 } break; case 'num2' : if(index > 9){ paddingLeft = 2 } } } li.className = 'list-'+customStyle[currentStyle]+ index + ' ' + 'list-'+currentStyle+'-paddingleft-' + paddingLeft; }else{ li.className = 'list-'+customStyle[currentStyle] + ' ' + 'list-'+currentStyle+'-paddingleft'; } }else{ li.className = li.className.replace(/list-[\w\-]+/gi,''); } var className = li.getAttribute('class'); if(className !== null && !className.replace(/\s/g,'')){ domUtils.removeAttributes(li,'class') } }); !ignore && adjustList(node,node.tagName.toLowerCase(),getStyle(node)||domUtils.getStyle(node, 'list-style-type'),true); }) } function adjustList(list, tag, style,ignoreEmpty) { var nextList = list.nextSibling; if (nextList && nextList.nodeType == 1 && nextList.tagName.toLowerCase() == tag && (getStyle(nextList) || domUtils.getStyle(nextList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) { domUtils.moveChild(nextList, list); if (nextList.childNodes.length == 0) { domUtils.remove(nextList); } } if(nextList && domUtils.isFillChar(nextList)){ domUtils.remove(nextList); } var preList = list.previousSibling; if (preList && preList.nodeType == 1 && preList.tagName.toLowerCase() == tag && (getStyle(preList) || domUtils.getStyle(preList, 'list-style-type') || (tag == 'ol' ? 'decimal' : 'disc')) == style) { domUtils.moveChild(list, preList); } if(preList && domUtils.isFillChar(preList)){ domUtils.remove(preList); } !ignoreEmpty && domUtils.isEmptyBlock(list) && domUtils.remove(list); if(getStyle(list)){ adjustListStyle(list.ownerDocument,true) } } function setListStyle(list,style){ if(customStyle[style]){ list.className = 'custom_' + style; } try{ domUtils.setStyle(list, 'list-style-type', style); }catch(e){} } function clearEmptySibling(node) { var tmpNode = node.previousSibling; if (tmpNode && domUtils.isEmptyBlock(tmpNode)) { domUtils.remove(tmpNode); } tmpNode = node.nextSibling; if (tmpNode && domUtils.isEmptyBlock(tmpNode)) { domUtils.remove(tmpNode); } } me.addListener('keydown', function (type, evt) { function preventAndSave() { evt.preventDefault ? evt.preventDefault() : (evt.returnValue = false); me.fireEvent('contentchange'); me.undoManger && me.undoManger.save(); } function findList(node,filterFn){ while(node && !domUtils.isBody(node)){ if(filterFn(node)){ return null } if(node.nodeType == 1 && /[ou]l/i.test(node.tagName)){ return node; } node = node.parentNode; } return null; } var keyCode = evt.keyCode || evt.which; if (keyCode == 13 && !evt.shiftKey) {//回车 var rng = me.selection.getRange(), parent = domUtils.findParent(rng.startContainer,function(node){return domUtils.isBlockElm(node)},true), li = domUtils.findParentByTagName(rng.startContainer,'li',true); if(parent && parent.tagName != 'PRE' && !li){ var html = parent.innerHTML.replace(new RegExp(domUtils.fillChar, 'g'),''); if(/^\s*1\s*\.[^\d]/.test(html)){ parent.innerHTML = html.replace(/^\s*1\s*\./,''); rng.setStartAtLast(parent).collapse(true).select(); me.__hasEnterExecCommand = true; me.execCommand('insertorderedlist'); me.__hasEnterExecCommand = false; } } var range = me.selection.getRange(), start = findList(range.startContainer,function (node) { return node.tagName == 'TABLE'; }), end = range.collapsed ? start : findList(range.endContainer,function (node) { return node.tagName == 'TABLE'; }); if (start && end && start === end) { if (!range.collapsed) { start = domUtils.findParentByTagName(range.startContainer, 'li', true); end = domUtils.findParentByTagName(range.endContainer, 'li', true); if (start && end && start === end) { range.deleteContents(); li = domUtils.findParentByTagName(range.startContainer, 'li', true); if (li && domUtils.isEmptyBlock(li)) { pre = li.previousSibling; next = li.nextSibling; p = me.document.createElement('p'); domUtils.fillNode(me.document, p); parentList = li.parentNode; if (pre && next) { range.setStart(next, 0).collapse(true).select(true); domUtils.remove(li); } else { if (!pre && !next || !pre) { parentList.parentNode.insertBefore(p, parentList); } else { li.parentNode.parentNode.insertBefore(p, parentList.nextSibling); } domUtils.remove(li); if (!parentList.firstChild) { domUtils.remove(parentList); } range.setStart(p, 0).setCursor(); } preventAndSave(); return; } } else { var tmpRange = range.cloneRange(), bk = tmpRange.collapse(false).createBookmark(); range.deleteContents(); tmpRange.moveToBookmark(bk); var li = domUtils.findParentByTagName(tmpRange.startContainer, 'li', true); clearEmptySibling(li); tmpRange.select(); preventAndSave(); return; } } li = domUtils.findParentByTagName(range.startContainer, 'li', true); if (li) { if (domUtils.isEmptyBlock(li)) { bk = range.createBookmark(); var parentList = li.parentNode; if (li !== parentList.lastChild) { domUtils.breakParent(li, parentList); clearEmptySibling(li); } else { parentList.parentNode.insertBefore(li, parentList.nextSibling); if (domUtils.isEmptyNode(parentList)) { domUtils.remove(parentList); } } //嵌套不处理 if (!dtd.$list[li.parentNode.tagName]) { if (!domUtils.isBlockElm(li.firstChild)) { p = me.document.createElement('p'); li.parentNode.insertBefore(p, li); while (li.firstChild) { p.appendChild(li.firstChild); } domUtils.remove(li); } else { domUtils.remove(li, true); } } range.moveToBookmark(bk).select(); } else { var first = li.firstChild; if (!first || !domUtils.isBlockElm(first)) { var p = me.document.createElement('p'); !li.firstChild && domUtils.fillNode(me.document, p); while (li.firstChild) { p.appendChild(li.firstChild); } li.appendChild(p); first = p; } var span = me.document.createElement('span'); range.insertNode(span); domUtils.breakParent(span, li); var nextLi = span.nextSibling; first = nextLi.firstChild; if (!first) { p = me.document.createElement('p'); domUtils.fillNode(me.document, p); nextLi.appendChild(p); first = p; } if (domUtils.isEmptyNode(first)) { first.innerHTML = ''; domUtils.fillNode(me.document, first); } range.setStart(first, 0).collapse(true).shrinkBoundary().select(); domUtils.remove(span); var pre = nextLi.previousSibling; if (pre && domUtils.isEmptyBlock(pre)) { pre.innerHTML = '<p></p>'; domUtils.fillNode(me.document, pre.firstChild); } } // } preventAndSave(); } } } if (keyCode == 8) { //修中ie中li下的问题 range = me.selection.getRange(); if (range.collapsed && domUtils.isStartInblock(range)) { tmpRange = range.cloneRange().trimBoundary(); li = domUtils.findParentByTagName(range.startContainer, 'li', true); //要在li的最左边,才能处理 if (li && domUtils.isStartInblock(tmpRange)) { start = domUtils.findParentByTagName(range.startContainer, 'p', true); if (start && start !== li.firstChild) { var parentList = domUtils.findParentByTagName(start,['ol','ul']); domUtils.breakParent(start,parentList); clearEmptySibling(start); me.fireEvent('contentchange'); range.setStart(start,0).setCursor(false,true); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } if (li && (pre = li.previousSibling)) { if (keyCode == 46 && li.childNodes.length) { return; } //有可能上边的兄弟节点是个2级菜单,要追加到2级菜单的最后的li if (dtd.$list[pre.tagName]) { pre = pre.lastChild; } me.undoManger && me.undoManger.save(); first = li.firstChild; if (domUtils.isBlockElm(first)) { if (domUtils.isEmptyNode(first)) { // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true); pre.appendChild(first); range.setStart(first, 0).setCursor(false, true); //first不是唯一的节点 while (li.firstChild) { pre.appendChild(li.firstChild); } } else { span = me.document.createElement('span'); range.insertNode(span); //判断pre是否是空的节点,如果是<p><br/></p>类型的空节点,干掉p标签防止它占位 if (domUtils.isEmptyBlock(pre)) { pre.innerHTML = ''; } domUtils.moveChild(li, pre); range.setStartBefore(span).collapse(true).select(true); domUtils.remove(span); } } else { if (domUtils.isEmptyNode(li)) { var p = me.document.createElement('p'); pre.appendChild(p); range.setStart(p, 0).setCursor(); // range.setEnd(pre, pre.childNodes.length).shrinkBoundary().collapse().select(true); } else { range.setEnd(pre, pre.childNodes.length).collapse().select(true); while (li.firstChild) { pre.appendChild(li.firstChild); } } } domUtils.remove(li); me.fireEvent('contentchange'); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } //trace:980 if (li && !li.previousSibling) { var parentList = li.parentNode; var bk = range.createBookmark(); if(domUtils.isTagNode(parentList.parentNode,'ol ul')){ parentList.parentNode.insertBefore(li,parentList); if(domUtils.isEmptyNode(parentList)){ domUtils.remove(parentList) } }else{ while(li.firstChild){ parentList.parentNode.insertBefore(li.firstChild,parentList); } domUtils.remove(li); if(domUtils.isEmptyNode(parentList)){ domUtils.remove(parentList) } } range.moveToBookmark(bk).setCursor(false,true); me.fireEvent('contentchange'); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } } } } }); me.addListener('keyup',function(type, evt){ var keyCode = evt.keyCode || evt.which; if (keyCode == 8) { var rng = me.selection.getRange(),list; if(list = domUtils.findParentByTagName(rng.startContainer,['ol', 'ul'],true)){ adjustList(list,list.tagName.toLowerCase(),getStyle(list)||domUtils.getComputedStyle(list,'list-style-type'),true) } } }); //处理tab键 me.addListener('tabkeydown',function(){ var range = me.selection.getRange(); //控制级数 function checkLevel(li){ if(me.options.maxListLevel != -1){ var level = li.parentNode,levelNum = 0; while(/[ou]l/i.test(level.tagName)){ levelNum++; level = level.parentNode; } if(levelNum >= me.options.maxListLevel){ return true; } } } //只以开始为准 //todo 后续改进 var li = domUtils.findParentByTagName(range.startContainer, 'li', true); if(li){ var bk; if(range.collapsed){ if(checkLevel(li)) return true; var parentLi = li.parentNode, list = me.document.createElement(parentLi.tagName), index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type')); index = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][index]; setListStyle(list,currentStyle); if(domUtils.isStartInblock(range)){ me.fireEvent('saveScene'); bk = range.createBookmark(); parentLi.insertBefore(list, li); list.appendChild(li); adjustList(list,list.tagName.toLowerCase(),currentStyle); me.fireEvent('contentchange'); range.moveToBookmark(bk).select(true); return true; } }else{ me.fireEvent('saveScene'); bk = range.createBookmark(); for(var i= 0,closeList,parents = domUtils.findParents(li),ci;ci=parents[i++];){ if(domUtils.isTagNode(ci,'ol ul')){ closeList = ci; break; } } var current = li; if(bk.end){ while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){ if(checkLevel(current)){ current = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList}); continue; } var parentLi = current.parentNode, list = me.document.createElement(parentLi.tagName), index = utils.indexOf(listStyle[list.tagName], getStyle(parentLi)||domUtils.getComputedStyle(parentLi, 'list-style-type')); var currentIndex = index + 1 == listStyle[list.tagName].length ? 0 : index + 1; var currentStyle = listStyle[list.tagName][currentIndex]; setListStyle(list,currentStyle); parentLi.insertBefore(list, current); while(current && !(domUtils.getPosition(current, bk.end) & domUtils.POSITION_FOLLOWING)){ li = current.nextSibling; list.appendChild(current); if(!li || domUtils.isTagNode(li,'ol ul')){ if(li){ while(li = li.firstChild){ if(li.tagName == 'LI'){ break; } } }else{ li = domUtils.getNextDomNode(current,false,null,function(node){return node !== closeList}); } break; } current = li; } adjustList(list,list.tagName.toLowerCase(),currentStyle); current = li; } } me.fireEvent('contentchange'); range.moveToBookmark(bk).select(); return true; } } }); function getLi(start){ while(start && !domUtils.isBody(start)){ if(start.nodeName == 'TABLE'){ return null; } if(start.nodeName == 'LI'){ return start } start = start.parentNode; } } me.commands['insertorderedlist'] = me.commands['insertunorderedlist'] = { execCommand:function (command, style) { if (!style) { style = command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc'; } var me = this, range = this.selection.getRange(), filterFn = function (node) { return node.nodeType == 1 ? node.tagName.toLowerCase() != 'br' : !domUtils.isWhitespace(node); }, tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul', frag = me.document.createDocumentFragment(); //去掉是因为会出现选到末尾,导致adjustmentBoundary缩到ol/ul的位置 //range.shrinkBoundary();//.adjustmentBoundary(); range.adjustmentBoundary().shrinkBoundary(); var bko = range.createBookmark(true), start = getLi(me.document.getElementById(bko.start)), modifyStart = 0, end = getLi(me.document.getElementById(bko.end)), modifyEnd = 0, startParent, endParent, list, tmp; if (start || end) { start && (startParent = start.parentNode); if (!bko.end) { end = start; } end && (endParent = end.parentNode); if (startParent === endParent) { while (start !== end) { tmp = start; start = start.nextSibling; if (!domUtils.isBlockElm(tmp.firstChild)) { var p = me.document.createElement('p'); while (tmp.firstChild) { p.appendChild(tmp.firstChild); } tmp.appendChild(p); } frag.appendChild(tmp); } tmp = me.document.createElement('span'); startParent.insertBefore(tmp, end); if (!domUtils.isBlockElm(end.firstChild)) { p = me.document.createElement('p'); while (end.firstChild) { p.appendChild(end.firstChild); } end.appendChild(p); } frag.appendChild(end); domUtils.breakParent(tmp, startParent); if (domUtils.isEmptyNode(tmp.previousSibling)) { domUtils.remove(tmp.previousSibling); } if (domUtils.isEmptyNode(tmp.nextSibling)) { domUtils.remove(tmp.nextSibling) } var nodeStyle = getStyle(startParent) || domUtils.getComputedStyle(startParent, 'list-style-type') || (command.toLowerCase() == 'insertorderedlist' ? 'decimal' : 'disc'); if (startParent.tagName.toLowerCase() == tag && nodeStyle == style) { for (var i = 0, ci, tmpFrag = me.document.createDocumentFragment(); ci = frag.childNodes[i++];) { if(domUtils.isTagNode(ci,'ol ul')){ utils.each(domUtils.getElementsByTagName(ci,'li'),function(li){ while(li.firstChild){ tmpFrag.appendChild(li.firstChild); } }); }else{ while (ci.firstChild) { tmpFrag.appendChild(ci.firstChild); } } } tmp.parentNode.insertBefore(tmpFrag, tmp); } else { list = me.document.createElement(tag); setListStyle(list,style); list.appendChild(frag); tmp.parentNode.insertBefore(list, tmp); } domUtils.remove(tmp); list && adjustList(list, tag, style); range.moveToBookmark(bko).select(); return; } //开始 if (start) { while (start) { tmp = start.nextSibling; if (domUtils.isTagNode(start, 'ol ul')) { frag.appendChild(start); } else { var tmpfrag = me.document.createDocumentFragment(), hasBlock = 0; while (start.firstChild) { if (domUtils.isBlockElm(start.firstChild)) { hasBlock = 1; } tmpfrag.appendChild(start.firstChild); } if (!hasBlock) { var tmpP = me.document.createElement('p'); tmpP.appendChild(tmpfrag); frag.appendChild(tmpP); } else { frag.appendChild(tmpfrag); } domUtils.remove(start); } start = tmp; } startParent.parentNode.insertBefore(frag, startParent.nextSibling); if (domUtils.isEmptyNode(startParent)) { range.setStartBefore(startParent); domUtils.remove(startParent); } else { range.setStartAfter(startParent); } modifyStart = 1; } if (end && domUtils.inDoc(endParent, me.document)) { //结束 start = endParent.firstChild; while (start && start !== end) { tmp = start.nextSibling; if (domUtils.isTagNode(start, 'ol ul')) { frag.appendChild(start); } else { tmpfrag = me.document.createDocumentFragment(); hasBlock = 0; while (start.firstChild) { if (domUtils.isBlockElm(start.firstChild)) { hasBlock = 1; } tmpfrag.appendChild(start.firstChild); } if (!hasBlock) { tmpP = me.document.createElement('p'); tmpP.appendChild(tmpfrag); frag.appendChild(tmpP); } else { frag.appendChild(tmpfrag); } domUtils.remove(start); } start = tmp; } var tmpDiv = domUtils.createElement(me.document, 'div', { 'tmpDiv':1 }); domUtils.moveChild(end, tmpDiv); frag.appendChild(tmpDiv); domUtils.remove(end); endParent.parentNode.insertBefore(frag, endParent); range.setEndBefore(endParent); if (domUtils.isEmptyNode(endParent)) { domUtils.remove(endParent); } modifyEnd = 1; } } if (!modifyStart) { range.setStartBefore(me.document.getElementById(bko.start)); } if (bko.end && !modifyEnd) { range.setEndAfter(me.document.getElementById(bko.end)); } range.enlarge(true, function (node) { return notExchange[node.tagName]; }); frag = me.document.createDocumentFragment(); var bk = range.createBookmark(), current = domUtils.getNextDomNode(bk.start, false, filterFn), tmpRange = range.cloneRange(), tmpNode, block = domUtils.isBlockElm; while (current && current !== bk.end && (domUtils.getPosition(current, bk.end) & domUtils.POSITION_PRECEDING)) { if (current.nodeType == 3 || dtd.li[current.tagName]) { if (current.nodeType == 1 && dtd.$list[current.tagName]) { while (current.firstChild) { frag.appendChild(current.firstChild); } tmpNode = domUtils.getNextDomNode(current, false, filterFn); domUtils.remove(current); current = tmpNode; continue; } tmpNode = current; tmpRange.setStartBefore(current); while (current && current !== bk.end && (!block(current) || domUtils.isBookmarkNode(current) )) { tmpNode = current; current = domUtils.getNextDomNode(current, false, null, function (node) { return !notExchange[node.tagName]; }); } if (current && block(current)) { tmp = domUtils.getNextDomNode(tmpNode, false, filterFn); if (tmp && domUtils.isBookmarkNode(tmp)) { current = domUtils.getNextDomNode(tmp, false, filterFn); tmpNode = tmp; } } tmpRange.setEndAfter(tmpNode); current = domUtils.getNextDomNode(tmpNode, false, filterFn); var li = range.document.createElement('li'); li.appendChild(tmpRange.extractContents()); if(domUtils.isEmptyNode(li)){ var tmpNode = range.document.createElement('p'); while(li.firstChild){ tmpNode.appendChild(li.firstChild) } li.appendChild(tmpNode); } frag.appendChild(li); } else { current = domUtils.getNextDomNode(current, true, filterFn); } } range.moveToBookmark(bk).collapse(true); list = me.document.createElement(tag); setListStyle(list,style); list.appendChild(frag); range.insertNode(list); //当前list上下看能否合并 adjustList(list, tag, style); //去掉冗余的tmpDiv for (var i = 0, ci, tmpDivs = domUtils.getElementsByTagName(list, 'div'); ci = tmpDivs[i++];) { if (ci.getAttribute('tmpDiv')) { domUtils.remove(ci, true) } } range.moveToBookmark(bko).select(); }, queryCommandState:function (command) { var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul'; var path = this.selection.getStartElementPath(); for(var i= 0,ci;ci = path[i++];){ if(ci.nodeName == 'TABLE'){ return 0 } if(tag == ci.nodeName.toLowerCase()){ return 1 }; } return 0; }, queryCommandValue:function (command) { var tag = command.toLowerCase() == 'insertorderedlist' ? 'ol' : 'ul'; var path = this.selection.getStartElementPath(), node; for(var i= 0,ci;ci = path[i++];){ if(ci.nodeName == 'TABLE'){ node = null; break; } if(tag == ci.nodeName.toLowerCase()){ node = ci; break; }; } return node ? getStyle(node) || domUtils.getComputedStyle(node, 'list-style-type') : null; } }; }; ///import core ///import plugins/undo.js ///commands 设置回车标签p或br ///commandsName EnterKey ///commandsTitle 设置回车标签p或br /** * @description 处理回车 * @author zhanyi */ UE.plugins['enterkey'] = function() { var hTag, me = this, tag = me.options.enterTag; me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) { var range = me.selection.getRange(), start = range.startContainer, doSave; //修正在h1-h6里边回车后不能嵌套p的问题 if (!browser.ie) { if (/h\d/i.test(hTag)) { if (browser.gecko) { var h = domUtils.findParentByTagName(start, [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption','table'], true); if (!h) { me.document.execCommand('formatBlock', false, '<p>'); doSave = 1; } } else { //chrome remove div if (start.nodeType == 1) { var tmp = me.document.createTextNode(''),div; range.insertNode(tmp); div = domUtils.findParentByTagName(tmp, 'div', true); if (div) { var p = me.document.createElement('p'); while (div.firstChild) { p.appendChild(div.firstChild); } div.parentNode.insertBefore(p, div); domUtils.remove(div); range.setStartBefore(tmp).setCursor(); doSave = 1; } domUtils.remove(tmp); } } if (me.undoManger && doSave) { me.undoManger.save(); } } //没有站位符,会出现多行的问题 browser.opera && range.select(); }else{ me.fireEvent('saveScene',true,true) } } }); me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which; if (keyCode == 13) {//回车 if(me.fireEvent('beforeenterkeydown')){ domUtils.preventDefault(evt); return; } me.fireEvent('saveScene',true,true); hTag = ''; var range = me.selection.getRange(); if (!range.collapsed) { //跨td不能删 var start = range.startContainer, end = range.endContainer, startTd = domUtils.findParentByTagName(start, 'td', true), endTd = domUtils.findParentByTagName(end, 'td', true); if (startTd && endTd && startTd !== endTd || !startTd && endTd || startTd && !endTd) { evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false); return; } } if (tag == 'p') { if (!browser.ie) { start = domUtils.findParentByTagName(range.startContainer, ['ol','ul','p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6','blockquote','caption'], true); //opera下执行formatblock会在table的场景下有问题,回车在opera原生支持很好,所以暂时在opera去掉调用这个原生的command //trace:2431 if (!start && !browser.opera) { me.document.execCommand('formatBlock', false, '<p>'); if (browser.gecko) { range = me.selection.getRange(); start = domUtils.findParentByTagName(range.startContainer, 'p', true); start && domUtils.removeDirtyAttr(start); } } else { hTag = start.tagName; start.tagName.toLowerCase() == 'p' && browser.gecko && domUtils.removeDirtyAttr(start); } } } else { evt.preventDefault ? evt.preventDefault() : ( evt.returnValue = false); if (!range.collapsed) { range.deleteContents(); start = range.startContainer; if (start.nodeType == 1 && (start = start.childNodes[range.startOffset])) { while (start.nodeType == 1) { if (dtd.$empty[start.tagName]) { range.setStartBefore(start).setCursor(); if (me.undoManger) { me.undoManger.save(); } return false; } if (!start.firstChild) { var br = range.document.createElement('br'); start.appendChild(br); range.setStart(start, 0).setCursor(); if (me.undoManger) { me.undoManger.save(); } return false; } start = start.firstChild; } if (start === range.startContainer.childNodes[range.startOffset]) { br = range.document.createElement('br'); range.insertNode(br).setCursor(); } else { range.setStart(start, 0).setCursor(); } } else { br = range.document.createElement('br'); range.insertNode(br).setStartAfter(br).setCursor(); } } else { br = range.document.createElement('br'); range.insertNode(br); var parent = br.parentNode; if (parent.lastChild === br) { br.parentNode.insertBefore(br.cloneNode(true), br); range.setStartBefore(br); } else { range.setStartAfter(br); } range.setCursor(); } } } }); }; /* * 处理特殊键的兼容性问题 */ UE.plugins['keystrokes'] = function() { var me = this; var collapsed = true; me.addListener('keydown', function(type, evt) { var keyCode = evt.keyCode || evt.which, rng = me.selection.getRange(); //处理全选的情况 if(!rng.collapsed && !(evt.ctrlKey || evt.shiftKey || evt.altKey || evt.metaKey) && (keyCode >= 65 && keyCode <=90 || keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 111 || { 13:1, 8:1, 46:1 }[keyCode]) ){ var tmpNode = rng.startContainer; if(domUtils.isFillChar(tmpNode)){ rng.setStartBefore(tmpNode) } tmpNode = rng.endContainer; if(domUtils.isFillChar(tmpNode)){ rng.setEndAfter(tmpNode) } rng.txtToElmBoundary(); //结束边界可能放到了br的前边,要把br包含进来 // x[xxx]<br/> if(rng.endContainer && rng.endContainer.nodeType == 1){ tmpNode = rng.endContainer.childNodes[rng.endOffset]; if(tmpNode && domUtils.isBr(tmpNode)){ rng.setEndAfter(tmpNode); } } if(rng.startOffset == 0){ tmpNode = rng.startContainer; if(domUtils.isBoundaryNode(tmpNode,'firstChild') ){ tmpNode = rng.endContainer; if(rng.endOffset == (tmpNode.nodeType == 3 ? tmpNode.nodeValue.length : tmpNode.childNodes.length) && domUtils.isBoundaryNode(tmpNode,'lastChild')){ me.fireEvent('saveScene'); me.body.innerHTML = '<p>'+(browser.ie ? '' : '<br/>')+'</p>'; rng.setStart(me.body.firstChild,0).setCursor(false,true); me._selectionChange(); return; } } } } //处理backspace if (keyCode == 8) { rng = me.selection.getRange(); collapsed = rng.collapsed; if(me.fireEvent('delkeydown',evt)){ return; } var start,end; //避免按两次删除才能生效的问题 if(rng.collapsed && rng.inFillChar()){ start = rng.startContainer; if(domUtils.isFillChar(start)){ rng.setStartBefore(start).shrinkBoundary(true).collapse(true); domUtils.remove(start) }else{ start.nodeValue = start.nodeValue.replace(new RegExp('^' + domUtils.fillChar ),''); rng.startOffset--; rng.collapse(true).select(true) } } //解决选中control元素不能删除的问题 if (start = rng.getClosedNode()) { me.fireEvent('saveScene'); rng.setStartBefore(start); domUtils.remove(start); rng.setCursor(); me.fireEvent('saveScene'); domUtils.preventDefault(evt); return; } //阻止在table上的删除 if (!browser.ie) { start = domUtils.findParentByTagName(rng.startContainer, 'table', true); end = domUtils.findParentByTagName(rng.endContainer, 'table', true); if (start && !end || !start && end || start !== end) { evt.preventDefault(); return; } } } //处理tab键的逻辑 if (keyCode == 9) { //不处理以下标签 var excludeTagNameForTabKey = { 'ol' : 1, 'ul' : 1, 'table':1 }; //处理组件里的tab按下事件 if(me.fireEvent('tabkeydown',evt)){ domUtils.preventDefault(evt); return; } var range = me.selection.getRange(); me.fireEvent('saveScene'); for (var i = 0,txt = '',tabSize = me.options.tabSize|| 4,tabNode = me.options.tabNode || '&nbsp;'; i < tabSize; i++) { txt += tabNode; } var span = me.document.createElement('span'); span.innerHTML = txt + domUtils.fillChar; if (range.collapsed) { range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { //普通的情况 start = domUtils.findParent(range.startContainer, filterFn); end = domUtils.findParent(range.endContainer, filterFn); if (start && end && start === end) { range.deleteContents(); range.insertNode(span.cloneNode(true).firstChild).setCursor(true); } else { var bookmark = range.createBookmark(), filterFn = function(node) { return domUtils.isBlockElm(node) && !excludeTagNameForTabKey[node.tagName.toLowerCase()] }; range.enlarge(true); var bookmark2 = range.createBookmark(), current = domUtils.getNextDomNode(bookmark2.start, false, filterFn); while (current && !(domUtils.getPosition(current, bookmark2.end) & domUtils.POSITION_FOLLOWING)) { current.insertBefore(span.cloneNode(true).firstChild, current.firstChild); current = domUtils.getNextDomNode(current, false, filterFn); } range.moveToBookmark(bookmark2).moveToBookmark(bookmark).select(); } } domUtils.preventDefault(evt) } //trace:1634 //ff的del键在容器空的时候,也会删除 if(browser.gecko && keyCode == 46){ range = me.selection.getRange(); if(range.collapsed){ start = range.startContainer; if(domUtils.isEmptyBlock(start)){ var parent = start.parentNode; while(domUtils.getChildCount(parent) == 1 && !domUtils.isBody(parent)){ start = parent; parent = parent.parentNode; } if(start === parent.lastChild) evt.preventDefault(); return; } } } }); me.addListener('keyup', function(type, evt) { var keyCode = evt.keyCode || evt.which, rng,me = this; if(keyCode == 8){ if(me.fireEvent('delkeyup')){ return; } rng = me.selection.getRange(); if(rng.collapsed){ var tmpNode, autoClearTagName = ['h1','h2','h3','h4','h5','h6']; if(tmpNode = domUtils.findParentByTagName(rng.startContainer,autoClearTagName,true)){ if(domUtils.isEmptyBlock(tmpNode)){ var pre = tmpNode.previousSibling; if(pre && pre.nodeName != 'TABLE'){ domUtils.remove(tmpNode); rng.setStartAtLast(pre).setCursor(false,true); return; }else{ var next = tmpNode.nextSibling; if(next && next.nodeName != 'TABLE'){ domUtils.remove(tmpNode); rng.setStartAtFirst(next).setCursor(false,true); return; } } } } //处理当删除到body时,要重新给p标签展位 if(domUtils.isBody(rng.startContainer)){ var tmpNode = domUtils.createElement(me.document,'p',{ 'innerHTML' : browser.ie ? domUtils.fillChar : '<br/>' }); rng.insertNode(tmpNode).setStart(tmpNode,0).setCursor(false,true); } } //chrome下如果删除了inline标签,浏览器会有记忆,在输入文字还是会套上刚才删除的标签,所以这里再选一次就不会了 if( !collapsed && (rng.startContainer.nodeType == 3 || rng.startContainer.nodeType == 1 && domUtils.isEmptyBlock(rng.startContainer))){ if(browser.ie){ var span = rng.document.createElement('span'); rng.insertNode(span).setStartBefore(span).collapse(true); rng.select(); domUtils.remove(span) }else{ rng.select() } } } }) };///import core ///commands 修复chrome下图片不能点击的问题 ///commandsName FixImgClick ///commandsTitle 修复chrome下图片不能点击的问题 //修复chrome下图片不能点击的问题 //todo 可以改大小 UE.plugins['fiximgclick'] = function() { var me = this; if ( browser.webkit ) { me.addListener( 'click', function( type, e ) { if ( e.target.tagName == 'IMG' ) { var range = new dom.Range( me.document ); range.selectNode( e.target ).select(); } } ); } };///import core ///commands 当输入内容超过编辑器高度时,编辑器自动增高 ///commandsName AutoHeight,autoHeightEnabled ///commandsTitle 自动增高 /** * @description 自动伸展 * @author zhanyi */ UE.plugins['autoheight'] = function () { var me = this; //提供开关,就算加载也可以关闭 me.autoHeightEnabled = me.options.autoHeightEnabled !== false; if (!me.autoHeightEnabled) { return; } var bakOverflow, span, tmpNode, lastHeight = 0, options = me.options, currentHeight, timer; function adjustHeight() { var me = this; clearTimeout(timer); if(isFullscreen)return; timer = setTimeout(function () { if (!me.queryCommandState || me.queryCommandState && me.queryCommandState('source') != 1) { if (!span) { span = me.document.createElement('span'); //trace:1764 span.style.cssText = 'display:block;width:0;margin:0;padding:0;border:0;clear:both;'; span.innerHTML = '.'; } tmpNode = span.cloneNode(true); me.body.appendChild(tmpNode); currentHeight = Math.max(domUtils.getXY(tmpNode).y + tmpNode.offsetHeight,Math.max(options.minFrameHeight, options.initialFrameHeight)); if (currentHeight != lastHeight) { me.setHeight(currentHeight,true); lastHeight = currentHeight; } domUtils.remove(tmpNode); } }, 50); } var isFullscreen; me.addListener('fullscreenchanged',function(cmd,f){ isFullscreen = f }); me.addListener('destroy', function () { me.removeListener('contentchange afterinserthtml keyup mouseup',adjustHeight) }); me.enableAutoHeight = function () { var me = this; if (!me.autoHeightEnabled) { return; } var doc = me.document; me.autoHeightEnabled = true; bakOverflow = doc.body.style.overflowY; doc.body.style.overflowY = 'hidden'; me.addListener('contentchange afterinserthtml keyup mouseup',adjustHeight); //ff不给事件算得不对 setTimeout(function () { adjustHeight.call(me); }, browser.gecko ? 100 : 0); me.fireEvent('autoheightchanged', me.autoHeightEnabled); }; me.disableAutoHeight = function () { me.body.style.overflowY = bakOverflow || ''; me.removeListener('contentchange', adjustHeight); me.removeListener('keyup', adjustHeight); me.removeListener('mouseup', adjustHeight); me.autoHeightEnabled = false; me.fireEvent('autoheightchanged', me.autoHeightEnabled); }; me.addListener('ready', function () { me.enableAutoHeight(); //trace:1764 var timer; domUtils.on(browser.ie ? me.body : me.document, browser.webkit ? 'dragover' : 'drop', function () { clearTimeout(timer); timer = setTimeout(function () { adjustHeight.call(this); }, 100); }); }); }; ///import core ///commands 悬浮工具栏 ///commandsName AutoFloat,autoFloatEnabled ///commandsTitle 悬浮工具栏 /* * modified by chengchao01 * * 注意: 引入此功能后,在IE6下会将body的背景图片覆盖掉! */ UE.plugins['autofloat'] = function() { var me = this, lang = me.getLang(); me.setOpt({ topOffset:0 }); var optsAutoFloatEnabled = me.options.autoFloatEnabled !== false, topOffset = me.options.topOffset; //如果不固定toolbar的位置,则直接退出 if(!optsAutoFloatEnabled){ return; } var uiUtils = UE.ui.uiUtils, LteIE6 = browser.ie && browser.version <= 6, quirks = browser.quirks; function checkHasUI(){ if(!UE.ui){ alert(lang.autofloatMsg); return 0; } return 1; } function fixIE6FixedPos(){ var docStyle = document.body.style; docStyle.backgroundImage = 'url("about:blank")'; docStyle.backgroundAttachment = 'fixed'; } var bakCssText, placeHolder = document.createElement('div'), toolbarBox,orgTop, getPosition, flag =true; //ie7模式下需要偏移 function setFloating(){ var toobarBoxPos = domUtils.getXY(toolbarBox), origalFloat = domUtils.getComputedStyle(toolbarBox,'position'), origalLeft = domUtils.getComputedStyle(toolbarBox,'left'); toolbarBox.style.width = toolbarBox.offsetWidth + 'px'; toolbarBox.style.zIndex = me.options.zIndex * 1 + 1; toolbarBox.parentNode.insertBefore(placeHolder, toolbarBox); if (LteIE6 || (quirks && browser.ie)) { if(toolbarBox.style.position != 'absolute'){ toolbarBox.style.position = 'absolute'; } toolbarBox.style.top = (document.body.scrollTop||document.documentElement.scrollTop) - orgTop + topOffset + 'px'; } else { if (browser.ie7Compat && flag) { flag = false; toolbarBox.style.left = domUtils.getXY(toolbarBox).x - document.documentElement.getBoundingClientRect().left+2 + 'px'; } if(toolbarBox.style.position != 'fixed'){ toolbarBox.style.position = 'fixed'; toolbarBox.style.top = topOffset +"px"; ((origalFloat == 'absolute' || origalFloat == 'relative') && parseFloat(origalLeft)) && (toolbarBox.style.left = toobarBoxPos.x + 'px'); } } } function unsetFloating(){ flag = true; if(placeHolder.parentNode){ placeHolder.parentNode.removeChild(placeHolder); } toolbarBox.style.cssText = bakCssText; } function updateFloating(){ var rect3 = getPosition(me.container); var offset=me.options.toolbarTopOffset||0; if (rect3.top < 0 && rect3.bottom - toolbarBox.offsetHeight > offset) { setFloating(); }else{ unsetFloating(); } } var defer_updateFloating = utils.defer(function(){ updateFloating(); },browser.ie ? 200 : 100,true); me.addListener('destroy',function(){ domUtils.un(window, ['scroll','resize'], updateFloating); me.removeListener('keydown', defer_updateFloating); }); me.addListener('ready', function(){ if(checkHasUI(me)){ getPosition = uiUtils.getClientRect; toolbarBox = me.ui.getDom('toolbarbox'); orgTop = getPosition(toolbarBox).top; bakCssText = toolbarBox.style.cssText; placeHolder.style.height = toolbarBox.offsetHeight + 'px'; if(LteIE6){ fixIE6FixedPos(); } domUtils.on(window, ['scroll','resize'], updateFloating); me.addListener('keydown', defer_updateFloating); me.addListener('beforefullscreenchange', function (t, enabled){ if (enabled) { unsetFloating(); } }); me.addListener('fullscreenchanged', function (t, enabled){ if (!enabled) { updateFloating(); } }); me.addListener('sourcemodechanged', function (t, enabled){ setTimeout(function (){ updateFloating(); },0); }); me.addListener("clearDoc",function(){ setTimeout(function(){ updateFloating(); },0); }) } }); }; /** * @description 纯文本粘贴 * @name puretxtpaste * @author zhanyi */ UE.plugins['pasteplain'] = function(){ var me = this; me.setOpt({ 'pasteplain':false, 'filterTxtRules' : function(){ function transP(node){ node.tagName = 'p'; node.setStyle(); } function removeNode(node){ node.parentNode.removeChild(node,true) } return { //直接删除及其字节点内容 '-' : 'script style object iframe embed input select', 'p': {$:{}}, 'br':{$:{}}, div: function (node) { var tmpNode, p = UE.uNode.createElement('p'); while (tmpNode = node.firstChild()) { if (tmpNode.type == 'text' || !UE.dom.dtd.$block[tmpNode.tagName]) { p.appendChild(tmpNode); } else { if (p.firstChild()) { node.parentNode.insertBefore(p, node); p = UE.uNode.createElement('p'); } else { node.parentNode.insertBefore(tmpNode, node); } } } if (p.firstChild()) { node.parentNode.insertBefore(p, node); } node.parentNode.removeChild(node); }, ol: removeNode, ul: removeNode, dl:removeNode, dt:removeNode, dd:removeNode, 'li':removeNode, 'caption':transP, 'th':transP, 'tr':transP, 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP, 'td':function(node){ //没有内容的td直接删掉 var txt = !!node.innerText(); if(txt){ node.parentNode.insertAfter(UE.uNode.createText(' &nbsp; &nbsp;'),node); } node.parentNode.removeChild(node,node.innerText()) } } }() }); //暂时这里支持一下老版本的属性 var pasteplain = me.options.pasteplain; me.commands['pasteplain'] = { queryCommandState: function (){ return pasteplain ? 1 : 0; }, execCommand: function (){ pasteplain = !pasteplain|0; }, notNeedUndo : 1 }; };///import core ///commands 右键菜单 ///commandsName ContextMenu ///commandsTitle 右键菜单 /** * 右键菜单 * @function * @name baidu.editor.plugins.contextmenu * @author zhanyi */ UE.plugins['contextmenu'] = function () { var me = this, lang = me.getLang( "contextMenu" ), menu, items = me.options.contextMenu || [ {label:lang['selectall'], cmdName:'selectall'}, { label:lang.deletecode, cmdName:'highlightcode', icon:'deletehighlightcode' }, { label:lang.cleardoc, cmdName:'cleardoc', exec:function () { if ( confirm( lang.confirmclear ) ) { this.execCommand( 'cleardoc' ); } } }, '-', { label:lang.unlink, cmdName:'unlink' }, '-', { group:lang.paragraph, icon:'justifyjustify', subMenu:[ { label:lang.justifyleft, cmdName:'justify', value:'left' }, { label:lang.justifyright, cmdName:'justify', value:'right' }, { label:lang.justifycenter, cmdName:'justify', value:'center' }, { label:lang.justifyjustify, cmdName:'justify', value:'justify' } ] }, '-', { group:lang.table, icon:'table', subMenu:[ { label:lang.inserttable, cmdName:'inserttable' }, { label:lang.deletetable, cmdName:'deletetable' }, '-', { label:lang.deleterow, cmdName:'deleterow' }, { label:lang.deletecol, cmdName:'deletecol' }, { label:lang.insertcol, cmdName:'insertcol' }, { label:lang.insertcolnext, cmdName:'insertcolnext' }, { label:lang.insertrow, cmdName:'insertrow' }, { label:lang.insertrownext, cmdName:'insertrownext' }, '-', { label:lang.insertcaption, cmdName:'insertcaption' }, { label:lang.deletecaption, cmdName:'deletecaption' }, { label:lang.inserttitle, cmdName:'inserttitle' }, { label:lang.deletetitle, cmdName:'deletetitle' }, '-', { label:lang.mergecells, cmdName:'mergecells' }, { label:lang.mergeright, cmdName:'mergeright' }, { label:lang.mergedown, cmdName:'mergedown' }, '-', { label:lang.splittorows, cmdName:'splittorows' }, { label:lang.splittocols, cmdName:'splittocols' }, { label:lang.splittocells, cmdName:'splittocells' }, '-', { label:lang.averageDiseRow, cmdName:'averagedistributerow' }, { label:lang.averageDisCol, cmdName:'averagedistributecol' }, '-', { label:lang.edittd, cmdName:'edittd', exec:function () { if ( UE.ui['edittd'] ) { new UE.ui['edittd']( this ); } this.getDialog('edittd').open(); } }, { label:lang.edittable, cmdName:'edittable', exec:function () { if ( UE.ui['edittable'] ) { new UE.ui['edittable']( this ); } this.getDialog('edittable').open(); } } ] }, { group:lang.tablesort, icon:'tablesort', subMenu:[ { label:lang.reversecurrent, cmdName:'sorttable', value:1 }, { label:lang.orderbyasc, cmdName:'sorttable' }, { label:lang.reversebyasc, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1.innerHTML, value2 = td2.innerHTML; return value2.localeCompare(value1); }); } }, { label:lang.orderbynum, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/), value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/); if(value1) value1 = +value1[0]; if(value2) value2 = +value2[0]; return (value1||0) - (value2||0); }); } }, { label:lang.reversebynum, cmdName:'sorttable', exec:function(){ this.execCommand("sorttable",function(td1,td2){ var value1 = td1[browser.ie ? 'innerText':'textContent'].match(/\d+/), value2 = td2[browser.ie ? 'innerText':'textContent'].match(/\d+/); if(value1) value1 = +value1[0]; if(value2) value2 = +value2[0]; return (value2||0) - (value1||0); }); } } ] }, { group:lang.borderbk, icon:'borderBack', subMenu:[ { label:lang.setcolor, cmdName:"interlacetable", exec:function(){ this.execCommand("interlacetable"); } }, { label:lang.unsetcolor, cmdName:"uninterlacetable", exec:function(){ this.execCommand("uninterlacetable"); } }, { label:lang.setbackground, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["#bbb","#ccc"]}); } }, { label:lang.unsetbackground, cmdName:"cleartablebackground", exec:function(){ this.execCommand("cleartablebackground"); } }, { label:lang.redandblue, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["red","blue"]}); } }, { label:lang.threecolorgradient, cmdName:"settablebackground", exec:function(){ this.execCommand("settablebackground",{repeat:true,colorList:["#aaa","#bbb","#ccc"]}); } } ] }, { group:lang.aligntd, icon:'aligntd', subMenu:[ { cmdName:'cellalignment', value:{align:'left',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'top'} }, { cmdName:'cellalignment', value:{align:'left',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'middle'} }, { cmdName:'cellalignment', value:{align:'left',vAlign:'bottom'} }, { cmdName:'cellalignment', value:{align:'center',vAlign:'bottom'} }, { cmdName:'cellalignment', value:{align:'right',vAlign:'bottom'} } ] }, { group:lang.aligntable, icon:'aligntable', subMenu:[ { cmdName:'tablealignment', className: 'left', label:lang.tableleft, value:"left" }, { cmdName:'tablealignment', className: 'center', label:lang.tablecenter, value:"center" }, { cmdName:'tablealignment', className: 'right', label:lang.tableright, value:"right" } ] }, '-', { label:lang.insertparagraphbefore, cmdName:'insertparagraph', value:true }, { label:lang.insertparagraphafter, cmdName:'insertparagraph' }, { label:lang['copy'], cmdName:'copy', exec:function () { alert( lang.copymsg ); }, query:function () { return 0; } }, { label:lang['paste'], cmdName:'paste', exec:function () { alert( lang.pastemsg ); }, query:function () { return 0; } },{ label:lang['highlightcode'], cmdName:'highlightcode', exec:function () { if ( UE.ui['highlightcode'] ) { new UE.ui['highlightcode']( this ); } this.ui._dialogs['highlightcodeDialog'].open(); } } ]; if ( !items.length ) { return; } var uiUtils = UE.ui.uiUtils; me.addListener( 'contextmenu', function ( type, evt ) { var offset = uiUtils.getViewportOffsetByEvent( evt ); me.fireEvent( 'beforeselectionchange' ); if ( menu ) { menu.destroy(); } for ( var i = 0, ti, contextItems = []; ti = items[i]; i++ ) { var last; (function ( item ) { if ( item == '-' ) { if ( (last = contextItems[contextItems.length - 1 ] ) && last !== '-' ) { contextItems.push( '-' ); } } else if ( item.hasOwnProperty( "group" ) ) { for ( var j = 0, cj, subMenu = []; cj = item.subMenu[j]; j++ ) { (function ( subItem ) { if ( subItem == '-' ) { if ( (last = subMenu[subMenu.length - 1 ] ) && last !== '-' ) { subMenu.push( '-' ); }else{ subMenu.splice(subMenu.length-1); } } else { if ( (me.commands[subItem.cmdName] || UE.commands[subItem.cmdName] || subItem.query) && (subItem.query ? subItem.query() : me.queryCommandState( subItem.cmdName )) > -1 ) { subMenu.push( { 'label':subItem.label || me.getLang( "contextMenu." + subItem.cmdName + (subItem.value || '') )||"", 'className':'edui-for-' +subItem.cmdName + ( subItem.className ? ( ' edui-for-' + subItem.cmdName + '-' + subItem.className ) : '' ), onclick:subItem.exec ? function () { subItem.exec.call( me ); } : function () { me.execCommand( subItem.cmdName, subItem.value ); } } ); } } })( cj ); } if ( subMenu.length ) { function getLabel(){ switch (item.icon){ case "table": return me.getLang( "contextMenu.table" ); case "justifyjustify": return me.getLang( "contextMenu.paragraph" ); case "aligntd": return me.getLang("contextMenu.aligntd"); case "aligntable": return me.getLang("contextMenu.aligntable"); case "tablesort": return lang.tablesort; case "borderBack": return lang.borderbk; default : return ''; } } contextItems.push( { //todo 修正成自动获取方式 'label':getLabel(), className:'edui-for-' + item.icon, 'subMenu':{ items:subMenu, editor:me } } ); } } else { //有可能commmand没有加载右键不能出来,或者没有command也想能展示出来添加query方法 if ( (me.commands[item.cmdName] || UE.commands[item.cmdName] || item.query) && (item.query ? item.query.call(me) : me.queryCommandState( item.cmdName )) > -1 ) { //highlight todo if ( item.cmdName == 'highlightcode' ) { if(me.queryCommandState( item.cmdName ) == 1 && item.icon != 'deletehighlightcode'){ return; } if(me.queryCommandState( item.cmdName ) != 1 && item.icon == 'deletehighlightcode'){ return; } } contextItems.push( { 'label':item.label || me.getLang( "contextMenu." + item.cmdName ), className:'edui-for-' + (item.icon ? item.icon : item.cmdName + (item.value || '')), onclick:item.exec ? function () { item.exec.call( me ); } : function () { me.execCommand( item.cmdName, item.value ); } } ); } } })( ti ); } if ( contextItems[contextItems.length - 1] == '-' ) { contextItems.pop(); } menu = new UE.ui.Menu( { items:contextItems, className:"edui-contextmenu", editor:me } ); menu.render(); menu.showAt( offset ); me.fireEvent("aftershowcontextmenu",menu); domUtils.preventDefault( evt ); if ( browser.ie ) { var ieRange; try { ieRange = me.selection.getNative().createRange(); } catch ( e ) { return; } if ( ieRange.item ) { var range = new dom.Range( me.document ); range.selectNode( ieRange.item( 0 ) ).select( true, true ); } } } ); }; ///import core ///commands 弹出菜单 // commandsName popupmenu ///commandsTitle 弹出菜单 /** * 弹出菜单 * @function * @name baidu.editor.plugins.popupmenu * @author xuheng */ UE.plugins['shortcutmenu'] = function () { var me = this, menu, items = me.options.shortcutMenu || []; if (!items.length) { return; } me.addListener ('contextmenu mouseup' , function (type , e) { var me = this, customEvt = { type : type , target : e.target || e.srcElement , screenX : e.screenX , screenY : e.screenY , clientX : e.clientX , clientY : e.clientY }; setTimeout (function () { var rng = me.selection.getRange (); if (rng.collapsed === false || type == "contextmenu") { if (!menu) { menu = new baidu.editor.ui.ShortCutMenu ({ editor : me , items : items , theme : me.options.theme , className : 'edui-shortcutmenu' }); menu.render (); me.fireEvent ("afterrendershortcutmenu" , menu); } menu.show (customEvt , !!UE.plugins['contextmenu']); } }); if (type == 'contextmenu') { domUtils.preventDefault (e); if (browser.ie) { var ieRange; try { ieRange = me.selection.getNative ().createRange (); } catch (e) { return; } if (ieRange.item) { var range = new dom.Range (me.document); range.selectNode (ieRange.item (0)).select (true , true); } } } if (type == "keydown") { menu && !menu.isHidden && menu.hide (); } }); me.addListener ('keydown' , function (type) { if (type == "keydown") { menu && !menu.isHidden && menu.hide (); } }); }; ///import core ///commands 加粗,斜体,上标,下标 ///commandsName Bold,Italic,Subscript,Superscript ///commandsTitle 加粗,加斜,下标,上标 /** * b u i等基础功能实现 * @function * @name baidu.editor.execCommands * @param {String} cmdName bold加粗。italic斜体。subscript上标。superscript下标。 */ UE.plugins['basestyle'] = function(){ var basestyles = { 'bold':['strong','b'], 'italic':['em','i'], 'subscript':['sub'], 'superscript':['sup'] }, getObj = function(editor,tagNames){ return domUtils.filterNodeList(editor.selection.getStartElementPath(),tagNames); }, me = this; //添加快捷键 me.addshortcutkey({ "Bold" : "ctrl+66",//^B "Italic" : "ctrl+73", //^I "Underline" : "ctrl+85"//^U }); me.addInputRule(function(root){ utils.each(root.getNodesByTagName('b i'),function(node){ switch (node.tagName){ case 'b': node.tagName = 'strong'; break; case 'i': node.tagName = 'em'; } }); }); for ( var style in basestyles ) { (function( cmd, tagNames ) { me.commands[cmd] = { execCommand : function( cmdName ) { var range = me.selection.getRange(),obj = getObj(this,tagNames); if ( range.collapsed ) { if ( obj ) { var tmpText = me.document.createTextNode(''); range.insertNode( tmpText ).removeInlineStyle( tagNames ); range.setStartBefore(tmpText); domUtils.remove(tmpText); } else { var tmpNode = range.document.createElement( tagNames[0] ); if(cmdName == 'superscript' || cmdName == 'subscript'){ tmpText = me.document.createTextNode(''); range.insertNode(tmpText) .removeInlineStyle(['sub','sup']) .setStartBefore(tmpText) .collapse(true); } range.insertNode( tmpNode ).setStart( tmpNode, 0 ); } range.collapse( true ); } else { if(cmdName == 'superscript' || cmdName == 'subscript'){ if(!obj || obj.tagName.toLowerCase() != cmdName){ range.removeInlineStyle(['sub','sup']); } } obj ? range.removeInlineStyle( tagNames ) : range.applyInlineStyle( tagNames[0] ); } range.select(); }, queryCommandState : function() { return getObj(this,tagNames) ? 1 : 0; } }; })( style, basestyles[style] ); } }; ///import core ///commands 远程图片抓取 ///commandsName catchRemoteImage,catchremoteimageenable ///commandsTitle 远程图片抓取 /** * 远程图片抓取,当开启本插件时所有不符合本地域名的图片都将被抓取成为本地服务器上的图片 * */ UE.plugins['catchremoteimage'] = function () { if (this.options.catchRemoteImageEnable===false){ return; } var me = this; this.setOpt({ localDomain:["127.0.0.1","localhost","img.baidu.com"], separater:'ue_separate_ue', catchFieldName:"upfile", catchRemoteImageEnable:true }); var ajax = UE.ajax, localDomain = me.options.localDomain , catcherUrl = me.options.catcherUrl, separater = me.options.separater; function catchremoteimage(imgs, callbacks) { var submitStr = imgs.join(separater); var tmpOption = { timeout:60000, //单位:毫秒,回调请求超时设置。目标用户如果网速不是很快的话此处建议设置一个较大的数值 onsuccess:callbacks["success"], onerror:callbacks["error"] }; tmpOption[me.options.catchFieldName] = submitStr; ajax.request(catcherUrl, tmpOption); } me.addListener("afterpaste", function () { me.fireEvent("catchRemoteImage"); }); me.addListener("catchRemoteImage", function () { var remoteImages = []; var imgs = domUtils.getElementsByTagName(me.document, "img"); var test = function (src,urls) { for (var j = 0, url; url = urls[j++];) { if (src.indexOf(url) !== -1) { return true; } } return false; }; for (var i = 0, ci; ci = imgs[i++];) { if (ci.getAttribute("word_img")){ continue; } var src = ci.getAttribute("_src") || ci.src || ""; if (/^(https?|ftp):/i.test(src) && !test(src,localDomain)) { remoteImages.push(src); } } if (remoteImages.length) { catchremoteimage(remoteImages, { //成功抓取 success:function (xhr) { try { var info = eval("(" + xhr.responseText + ")"); } catch (e) { return; } var srcUrls = info.srcUrl.split(separater), urls = info.url.split(separater); for (var i = 0, ci; ci = imgs[i++];) { var src = ci.getAttribute("_src") || ci.src || ""; for (var j = 0, cj; cj = srcUrls[j++];) { var url = urls[j - 1]; if (src == cj && url != "error") { //抓取失败时不做替换处理 //地址修正 var newSrc = me.options.catcherPath + url; domUtils.setAttributes(ci, { "src":newSrc, "_src":newSrc }); break; } } } me.fireEvent('catchremotesuccess') }, //回调失败,本次请求超时 error:function () { me.fireEvent("catchremoteerror"); } }); } }); };var baidu = baidu || {}; baidu.editor = baidu.editor || {}; baidu.editor.ui = {};(function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils; var magic = '$EDITORUI'; var root = window[magic] = {}; var uidMagic = 'ID' + magic; var uidCount = 0; var uiUtils = baidu.editor.ui.uiUtils = { uid: function (obj){ return (obj ? obj[uidMagic] || (obj[uidMagic] = ++ uidCount) : ++ uidCount); }, hook: function ( fn, callback ) { var dg; if (fn && fn._callbacks) { dg = fn; } else { dg = function (){ var q; if (fn) { q = fn.apply(this, arguments); } var callbacks = dg._callbacks; var k = callbacks.length; while (k --) { var r = callbacks[k].apply(this, arguments); if (q === undefined) { q = r; } } return q; }; dg._callbacks = []; } dg._callbacks.push(callback); return dg; }, createElementByHtml: function (html){ var el = document.createElement('div'); el.innerHTML = html; el = el.firstChild; el.parentNode.removeChild(el); return el; }, getViewportElement: function (){ return (browser.ie && browser.quirks) ? document.body : document.documentElement; }, getClientRect: function (element){ var bcr; //trace IE6下在控制编辑器显隐时可能会报错,catch一下 try{ bcr = element.getBoundingClientRect(); }catch(e){ bcr={left:0,top:0,height:0,width:0} } var rect = { left: Math.round(bcr.left), top: Math.round(bcr.top), height: Math.round(bcr.bottom - bcr.top), width: Math.round(bcr.right - bcr.left) }; var doc; while ((doc = element.ownerDocument) !== document && (element = domUtils.getWindow(doc).frameElement)) { bcr = element.getBoundingClientRect(); rect.left += bcr.left; rect.top += bcr.top; } rect.bottom = rect.top + rect.height; rect.right = rect.left + rect.width; return rect; }, getViewportRect: function (){ var viewportEl = uiUtils.getViewportElement(); var width = (window.innerWidth || viewportEl.clientWidth) | 0; var height = (window.innerHeight ||viewportEl.clientHeight) | 0; return { left: 0, top: 0, height: height, width: width, bottom: height, right: width }; }, setViewportOffset: function (element, offset){ var rect; var fixedLayer = uiUtils.getFixedLayer(); if (element.parentNode === fixedLayer) { element.style.left = offset.left + 'px'; element.style.top = offset.top + 'px'; } else { domUtils.setViewportOffset(element, offset); } }, getEventOffset: function (evt){ var el = evt.target || evt.srcElement; var rect = uiUtils.getClientRect(el); var offset = uiUtils.getViewportOffsetByEvent(evt); return { left: offset.left - rect.left, top: offset.top - rect.top }; }, getViewportOffsetByEvent: function (evt){ var el = evt.target || evt.srcElement; var frameEl = domUtils.getWindow(el).frameElement; var offset = { left: evt.clientX, top: evt.clientY }; if (frameEl && el.ownerDocument !== document) { var rect = uiUtils.getClientRect(frameEl); offset.left += rect.left; offset.top += rect.top; } return offset; }, setGlobal: function (id, obj){ root[id] = obj; return magic + '["' + id + '"]'; }, unsetGlobal: function (id){ delete root[id]; }, copyAttributes: function (tgt, src){ var attributes = src.attributes; var k = attributes.length; while (k --) { var attrNode = attributes[k]; if ( attrNode.nodeName != 'style' && attrNode.nodeName != 'class' && (!browser.ie || attrNode.specified) ) { tgt.setAttribute(attrNode.nodeName, attrNode.nodeValue); } } if (src.className) { domUtils.addClass(tgt,src.className); } if (src.style.cssText) { tgt.style.cssText += ';' + src.style.cssText; } }, removeStyle: function (el, styleName){ if (el.style.removeProperty) { el.style.removeProperty(styleName); } else if (el.style.removeAttribute) { el.style.removeAttribute(styleName); } else throw ''; }, contains: function (elA, elB){ return elA && elB && (elA === elB ? false : ( elA.contains ? elA.contains(elB) : elA.compareDocumentPosition(elB) & 16 )); }, startDrag: function (evt, callbacks,doc){ var doc = doc || document; var startX = evt.clientX; var startY = evt.clientY; function handleMouseMove(evt){ var x = evt.clientX - startX; var y = evt.clientY - startY; callbacks.ondragmove(x, y,evt); if (evt.stopPropagation) { evt.stopPropagation(); } else { evt.cancelBubble = true; } } if (doc.addEventListener) { function handleMouseUp(evt){ doc.removeEventListener('mousemove', handleMouseMove, true); doc.removeEventListener('mouseup', handleMouseUp, true); window.removeEventListener('mouseup', handleMouseUp, true); callbacks.ondragstop(); } doc.addEventListener('mousemove', handleMouseMove, true); doc.addEventListener('mouseup', handleMouseUp, true); window.addEventListener('mouseup', handleMouseUp, true); evt.preventDefault(); } else { var elm = evt.srcElement; elm.setCapture(); function releaseCaptrue(){ elm.releaseCapture(); elm.detachEvent('onmousemove', handleMouseMove); elm.detachEvent('onmouseup', releaseCaptrue); elm.detachEvent('onlosecaptrue', releaseCaptrue); callbacks.ondragstop(); } elm.attachEvent('onmousemove', handleMouseMove); elm.attachEvent('onmouseup', releaseCaptrue); elm.attachEvent('onlosecaptrue', releaseCaptrue); evt.returnValue = false; } callbacks.ondragstart(); }, getFixedLayer: function (){ var layer = document.getElementById('edui_fixedlayer'); if (layer == null) { layer = document.createElement('div'); layer.id = 'edui_fixedlayer'; document.body.appendChild(layer); if (browser.ie && browser.version <= 8) { layer.style.position = 'absolute'; bindFixedLayer(); setTimeout(updateFixedOffset); } else { layer.style.position = 'fixed'; } layer.style.left = '0'; layer.style.top = '0'; layer.style.width = '0'; layer.style.height = '0'; } return layer; }, makeUnselectable: function (element){ if (browser.opera || (browser.ie && browser.version < 9)) { element.unselectable = 'on'; if (element.hasChildNodes()) { for (var i=0; i<element.childNodes.length; i++) { if (element.childNodes[i].nodeType == 1) { uiUtils.makeUnselectable(element.childNodes[i]); } } } } else { if (element.style.MozUserSelect !== undefined) { element.style.MozUserSelect = 'none'; } else if (element.style.WebkitUserSelect !== undefined) { element.style.WebkitUserSelect = 'none'; } else if (element.style.KhtmlUserSelect !== undefined) { element.style.KhtmlUserSelect = 'none'; } } } }; function updateFixedOffset(){ var layer = document.getElementById('edui_fixedlayer'); uiUtils.setViewportOffset(layer, { left: 0, top: 0 }); // layer.style.display = 'none'; // layer.style.display = 'block'; //#trace: 1354 // setTimeout(updateFixedOffset); } function bindFixedLayer(adjOffset){ domUtils.on(window, 'scroll', updateFixedOffset); domUtils.on(window, 'resize', baidu.editor.utils.defer(updateFixedOffset, 0, true)); } })(); (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, EventBase = baidu.editor.EventBase, UIBase = baidu.editor.ui.UIBase = function () { }; UIBase.prototype = { className:'', uiName:'', initOptions:function (options) { var me = this; for (var k in options) { me[k] = options[k]; } this.id = this.id || 'edui' + uiUtils.uid(); }, initUIBase:function () { this._globalKey = utils.unhtml(uiUtils.setGlobal(this.id, this)); }, render:function (holder) { var html = this.renderHtml(); var el = uiUtils.createElementByHtml(html); //by xuheng 给每个node添加class var list = domUtils.getElementsByTagName(el, "*"); var theme = "edui-" + (this.theme || this.editor.options.theme); var layer = document.getElementById('edui_fixedlayer'); for (var i = 0, node; node = list[i++];) { domUtils.addClass(node, theme); } domUtils.addClass(el, theme); if(layer){ layer.className=""; domUtils.addClass(layer,theme); } var seatEl = this.getDom(); if (seatEl != null) { seatEl.parentNode.replaceChild(el, seatEl); uiUtils.copyAttributes(el, seatEl); } else { if (typeof holder == 'string') { holder = document.getElementById(holder); } holder = holder || uiUtils.getFixedLayer(); domUtils.addClass(holder, theme); holder.appendChild(el); } this.postRender(); }, getDom:function (name) { if (!name) { return document.getElementById(this.id); } else { return document.getElementById(this.id + '_' + name); } }, postRender:function () { this.fireEvent('postrender'); }, getHtmlTpl:function () { return ''; }, formatHtml:function (tpl) { var prefix = 'edui-' + this.uiName; return (tpl .replace(/##/g, this.id) .replace(/%%-/g, this.uiName ? prefix + '-' : '') .replace(/%%/g, (this.uiName ? prefix : '') + ' ' + this.className) .replace(/\$\$/g, this._globalKey)); }, renderHtml:function () { return this.formatHtml(this.getHtmlTpl()); }, dispose:function () { var box = this.getDom(); if (box) baidu.editor.dom.domUtils.remove(box); uiUtils.unsetGlobal(this.id); } }; utils.inherits(UIBase, EventBase); })(); (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Separator = baidu.editor.ui.Separator = function (options){ this.initOptions(options); this.initSeparator(); }; Separator.prototype = { uiName: 'separator', initSeparator: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%"></div>'; } }; utils.inherits(Separator, UIBase); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, uiUtils = baidu.editor.ui.uiUtils; var Mask = baidu.editor.ui.Mask = function (options){ this.initOptions(options); this.initUIBase(); }; Mask.prototype = { getHtmlTpl: function (){ return '<div id="##" class="edui-mask %%" onmousedown="return $$._onMouseDown(event, this);"></div>'; }, postRender: function (){ var me = this; domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me._fill(); } }); }); }, show: function (zIndex){ this._fill(); this.getDom().style.display = ''; this.getDom().style.zIndex = zIndex; }, hide: function (){ this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; }, isHidden: function (){ return this.getDom().style.display == 'none'; }, _onMouseDown: function (){ return false; }, _fill: function (){ var el = this.getDom(); var vpRect = uiUtils.getViewportRect(); el.style.width = vpRect.width + 'px'; el.style.height = vpRect.height + 'px'; } }; utils.inherits(Mask, UIBase); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup = function (options){ this.initOptions(options); this.initPopup(); }; var allPopups = []; function closeAllPopup( evt,el ){ for ( var i = 0; i < allPopups.length; i++ ) { var pop = allPopups[i]; if (!pop.isHidden()) { if (pop.queryAutoHide(el) !== false) { if(evt&&/scroll/ig.test(evt.type)&&pop.className=="edui-wordpastepop") return; pop.hide(); } } } if(allPopups.length) pop.editor.fireEvent("afterhidepop"); } Popup.postHide = closeAllPopup; var ANCHOR_CLASSES = ['edui-anchor-topleft','edui-anchor-topright', 'edui-anchor-bottomleft','edui-anchor-bottomright']; Popup.prototype = { SHADOW_RADIUS: 5, content: null, _hidden: false, autoRender: true, canSideLeft: true, canSideUp: true, initPopup: function (){ this.initUIBase(); allPopups.push( this ); }, getHtmlTpl: function (){ return '<div id="##" class="edui-popup %%" onmousedown="return false;">' + ' <div id="##_body" class="edui-popup-body">' + ' <iframe style="position:absolute;z-index:-1;left:0;top:0;background-color: transparent;" frameborder="0" width="100%" height="100%" src="javascript:"></iframe>' + ' <div class="edui-shadow"></div>' + ' <div id="##_content" class="edui-popup-content">' + this.getContentHtmlTpl() + ' </div>' + ' </div>' + '</div>'; }, getContentHtmlTpl: function (){ if(this.content){ if (typeof this.content == 'string') { return this.content; } return this.content.renderHtml(); }else{ return '' } }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ if (this.content instanceof UIBase) { this.content.postRender(); } //捕获鼠标滚轮 if( this.captureWheel && !this.captured ) { this.captured = true; var winHeight = ( document.documentElement.clientHeight || document.body.clientHeight ) - 80, _height = this.getDom().offsetHeight, _top = domUtils.getXY( this.combox.getDom() ).y, content = this.getDom('content'), me = this; while( _top + _height > winHeight ) { _height -= 30; content.style.height = _height + 'px'; } //阻止在combox上的鼠标滚轮事件, 防止用户的正常操作被误解 if( window.XMLHttpRequest ) { domUtils.on( content, ( 'onmousewheel' in document.body ) ? 'mousewheel' :'DOMMouseScroll' , function(e){ if(e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; } if( e.wheelDelta ) { content.scrollTop -= ( e.wheelDelta / 120 )*60; } else { content.scrollTop -= ( e.detail / -3 )*60; } }); } else { //ie6 domUtils.on( this.getDom(), 'mousewheel' , function(e){ e.returnValue = false; me.getDom('content').scrollTop -= ( e.wheelDelta / 120 )*60; }); } } this.fireEvent('postRenderAfter'); this.hide(true); this._UIBase_postRender(); }, _doAutoRender: function (){ if (!this.getDom() && this.autoRender) { this.render(); } }, mesureSize: function (){ var box = this.getDom('content'); return uiUtils.getClientRect(box); }, fitSize: function (){ if( this.captureWheel && this.sized ) { return this.__size; } this.sized = true; var popBodyEl = this.getDom('body'); popBodyEl.style.width = ''; popBodyEl.style.height = ''; var size = this.mesureSize(); if( this.captureWheel ) { popBodyEl.style.width = -(-20 -size.width) + 'px'; } else { popBodyEl.style.width = size.width + 'px'; } popBodyEl.style.height = size.height + 'px'; this.__size = size; this.captureWheel && (this.getDom('content').style.overflow = 'auto'); return size; }, showAnchor: function ( element, hoz ){ this.showAnchorRect( uiUtils.getClientRect( element ), hoz ); }, showAnchorRect: function ( rect, hoz, adj ){ this._doAutoRender(); var vpRect = uiUtils.getViewportRect(); this._show(); var popSize = this.fitSize(); var sideLeft, sideUp, left, top; if (hoz) { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.left - popSize.width : rect.right); top = (sideUp ? rect.bottom - popSize.height : rect.top); } else { sideLeft = this.canSideLeft && (rect.right + popSize.width > vpRect.right && rect.left > popSize.width); sideUp = this.canSideUp && (rect.top + popSize.height > vpRect.bottom && rect.bottom > popSize.height); left = (sideLeft ? rect.right - popSize.width : rect.left); top = (sideUp ? rect.top - popSize.height : rect.bottom); } var popEl = this.getDom(); uiUtils.setViewportOffset(popEl, { left: left, top: top }); domUtils.removeClasses(popEl, ANCHOR_CLASSES); popEl.className += ' ' + ANCHOR_CLASSES[(sideUp ? 1 : 0) * 2 + (sideLeft ? 1 : 0)]; if(this.editor){ popEl.style.zIndex = this.editor.container.style.zIndex * 1 + 10; baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = popEl.style.zIndex - 1; } }, showAt: function (offset) { var left = offset.left; var top = offset.top; var rect = { left: left, top: top, right: left, bottom: top, height: 0, width: 0 }; this.showAnchorRect(rect, false, true); }, _show: function (){ if (this._hidden) { var box = this.getDom(); box.style.display = ''; this._hidden = false; // if (box.setActive) { // box.setActive(); // } this.fireEvent('show'); } }, isHidden: function (){ return this._hidden; }, show: function (){ this._doAutoRender(); this._show(); }, hide: function (notNofity){ if (!this._hidden && this.getDom()) { this.getDom().style.display = 'none'; this._hidden = true; if (!notNofity) { this.fireEvent('hide'); } } }, queryAutoHide: function (el){ return !el || !uiUtils.contains(this.getDom(), el); } }; utils.inherits(Popup, UIBase); domUtils.on( document, 'mousedown', function ( evt ) { var el = evt.target || evt.srcElement; closeAllPopup( evt,el ); } ); domUtils.on( window, 'scroll', function (evt,el) { closeAllPopup( evt,el ); } ); })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, ColorPicker = baidu.editor.ui.ColorPicker = function (options){ this.initOptions(options); this.noColorText = this.noColorText || this.editor.getLang("clearColor"); this.initUIBase(); }; ColorPicker.prototype = { getHtmlTpl: function (){ return genColorPicker(this.noColorText,this.editor); }, _onTableClick: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.fireEvent('pickcolor', color); } }, _onTableOver: function (evt){ var tgt = evt.target || evt.srcElement; var color = tgt.getAttribute('data-color'); if (color) { this.getDom('preview').style.backgroundColor = color; } }, _onTableOut: function (){ this.getDom('preview').style.backgroundColor = ''; }, _onPickNoColor: function (){ this.fireEvent('picknocolor'); } }; utils.inherits(ColorPicker, UIBase); var COLORS = ( 'ffffff,000000,eeece1,1f497d,4f81bd,c0504d,9bbb59,8064a2,4bacc6,f79646,' + 'f2f2f2,7f7f7f,ddd9c3,c6d9f0,dbe5f1,f2dcdb,ebf1dd,e5e0ec,dbeef3,fdeada,' + 'd8d8d8,595959,c4bd97,8db3e2,b8cce4,e5b9b7,d7e3bc,ccc1d9,b7dde8,fbd5b5,' + 'bfbfbf,3f3f3f,938953,548dd4,95b3d7,d99694,c3d69b,b2a2c7,92cddc,fac08f,' + 'a5a5a5,262626,494429,17365d,366092,953734,76923c,5f497a,31859b,e36c09,' + '7f7f7f,0c0c0c,1d1b10,0f243e,244061,632423,4f6128,3f3151,205867,974806,' + 'c00000,ff0000,ffc000,ffff00,92d050,00b050,00b0f0,0070c0,002060,7030a0,').split(','); function genColorPicker(noColorText,editor){ var html = '<div id="##" class="edui-colorpicker %%">' + '<div class="edui-colorpicker-topbar edui-clearfix">' + '<div unselectable="on" id="##_preview" class="edui-colorpicker-preview"></div>' + '<div unselectable="on" class="edui-colorpicker-nocolor" onclick="$$._onPickNoColor(event, this);">'+ noColorText +'</div>' + '</div>' + '<table class="edui-box" style="border-collapse: collapse;" onmouseover="$$._onTableOver(event, this);" onmouseout="$$._onTableOut(event, this);" onclick="return $$._onTableClick(event, this);" cellspacing="0" cellpadding="0">' + '<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;padding-top: 2px"><td colspan="10">'+editor.getLang("themeColor")+'</td> </tr>'+ '<tr class="edui-colorpicker-tablefirstrow" >'; for (var i=0; i<COLORS.length; i++) { if (i && i%10 === 0) { html += '</tr>'+(i==60?'<tr style="border-bottom: 1px solid #ddd;font-size: 13px;line-height: 25px;color:#39C;"><td colspan="10">'+editor.getLang("standardColor")+'</td></tr>':'')+'<tr'+(i==60?' class="edui-colorpicker-tablefirstrow"':'')+'>'; } html += i<70 ? '<td style="padding: 0 2px;"><a hidefocus title="'+COLORS[i]+'" onclick="return false;" href="javascript:" unselectable="on" class="edui-box edui-colorpicker-colorcell"' + ' data-color="#'+ COLORS[i] +'"'+ ' style="background-color:#'+ COLORS[i] +';border:solid #ccc;'+ (i<10 || i>=60?'border-width:1px;': i>=10&&i<20?'border-width:1px 1px 0 1px;': 'border-width:0 1px 0 1px;')+ '"' + '></a></td>':''; } html += '</tr></table></div>'; return html; } })(); ///import core ///import uicore (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; var TablePicker = baidu.editor.ui.TablePicker = function (options){ this.initOptions(options); this.initTablePicker(); }; TablePicker.prototype = { defaultNumRows: 10, defaultNumCols: 10, maxNumRows: 20, maxNumCols: 20, numRows: 10, numCols: 10, lengthOfCellSide: 22, initTablePicker: function (){ this.initUIBase(); }, getHtmlTpl: function (){ var me = this; return '<div id="##" class="edui-tablepicker %%">' + '<div class="edui-tablepicker-body">' + '<div class="edui-infoarea">' + '<span id="##_label" class="edui-label"></span>' + '</div>' + '<div class="edui-pickarea"' + ' onmousemove="$$._onMouseMove(event, this);"' + ' onmouseover="$$._onMouseOver(event, this);"' + ' onmouseout="$$._onMouseOut(event, this);"' + ' onclick="$$._onClick(event, this);"' + '>' + '<div id="##_overlay" class="edui-overlay"></div>' + '</div>' + '</div>' + '</div>'; }, _UIBase_render: UIBase.prototype.render, render: function (holder){ this._UIBase_render(holder); this.getDom('label').innerHTML = '0'+this.editor.getLang("t_row")+' x 0'+this.editor.getLang("t_col"); }, _track: function (numCols, numRows){ var style = this.getDom('overlay').style; var sideLen = this.lengthOfCellSide; style.width = numCols * sideLen + 'px'; style.height = numRows * sideLen + 'px'; var label = this.getDom('label'); label.innerHTML = numCols +this.editor.getLang("t_col")+' x ' + numRows + this.editor.getLang("t_row"); this.numCols = numCols; this.numRows = numRows; }, _onMouseOver: function (evt, el){ var rel = evt.relatedTarget || evt.fromElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row"); this.getDom('overlay').style.visibility = ''; } }, _onMouseOut: function (evt, el){ var rel = evt.relatedTarget || evt.toElement; if (!uiUtils.contains(el, rel) && el !== rel) { this.getDom('label').innerHTML = '0'+this.editor.getLang("t_col")+' x 0'+this.editor.getLang("t_row"); this.getDom('overlay').style.visibility = 'hidden'; } }, _onMouseMove: function (evt, el){ var style = this.getDom('overlay').style; var offset = uiUtils.getEventOffset(evt); var sideLen = this.lengthOfCellSide; var numCols = Math.ceil(offset.left / sideLen); var numRows = Math.ceil(offset.top / sideLen); this._track(numCols, numRows); }, _onClick: function (){ this.fireEvent('picktable', this.numCols, this.numRows); } }; utils.inherits(TablePicker, UIBase); })(); (function (){ var browser = baidu.editor.browser, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils; var TPL_STATEFUL = 'onmousedown="$$.Stateful_onMouseDown(event, this);"' + ' onmouseup="$$.Stateful_onMouseUp(event, this);"' + ( browser.ie ? ( ' onmouseenter="$$.Stateful_onMouseEnter(event, this);"' + ' onmouseleave="$$.Stateful_onMouseLeave(event, this);"' ) : ( ' onmouseover="$$.Stateful_onMouseOver(event, this);"' + ' onmouseout="$$.Stateful_onMouseOut(event, this);"' )); baidu.editor.ui.Stateful = { alwalysHoverable: false, target:null,//目标元素和this指向dom不一样 Stateful_init: function (){ this._Stateful_dGetHtmlTpl = this.getHtmlTpl; this.getHtmlTpl = this.Stateful_getHtmlTpl; }, Stateful_getHtmlTpl: function (){ var tpl = this._Stateful_dGetHtmlTpl(); // 使用function避免$转义 return tpl.replace(/stateful/g, function (){ return TPL_STATEFUL; }); }, Stateful_onMouseEnter: function (evt, el){ this.target=el; if (!this.isDisabled() || this.alwalysHoverable) { this.addState('hover'); this.fireEvent('over'); } }, Stateful_onMouseLeave: function (evt, el){ if (!this.isDisabled() || this.alwalysHoverable) { this.removeState('hover'); this.removeState('active'); this.fireEvent('out'); } }, Stateful_onMouseOver: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseEnter(evt, el); } }, Stateful_onMouseOut: function (evt, el){ var rel = evt.relatedTarget; if (!uiUtils.contains(el, rel) && el !== rel) { this.Stateful_onMouseLeave(evt, el); } }, Stateful_onMouseDown: function (evt, el){ if (!this.isDisabled()) { this.addState('active'); } }, Stateful_onMouseUp: function (evt, el){ if (!this.isDisabled()) { this.removeState('active'); } }, Stateful_postRender: function (){ if (this.disabled && !this.hasState('disabled')) { this.addState('disabled'); } }, hasState: function (state){ return domUtils.hasClass(this.getStateDom(), 'edui-state-' + state); }, addState: function (state){ if (!this.hasState(state)) { this.getStateDom().className += ' edui-state-' + state; } }, removeState: function (state){ if (this.hasState(state)) { domUtils.removeClasses(this.getStateDom(), ['edui-state-' + state]); } }, getStateDom: function (){ return this.getDom('state'); }, isChecked: function (){ return this.hasState('checked'); }, setChecked: function (checked){ if (!this.isDisabled() && checked) { this.addState('checked'); } else { this.removeState('checked'); } }, isDisabled: function (){ return this.hasState('disabled'); }, setDisabled: function (disabled){ if (disabled) { this.removeState('hover'); this.removeState('checked'); this.removeState('active'); this.addState('disabled'); } else { this.removeState('disabled'); } } }; })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, Button = baidu.editor.ui.Button = function (options){ this.initOptions(options); this.initButton(); }; Button.prototype = { uiName: 'button', label: '', title: '', showIcon: true, showText: true, initButton: function (){ this.initUIBase(); this.Stateful_init(); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div id="##_state" stateful>' + '<div class="%%-wrap"><div id="##_body" unselectable="on" ' + (this.title ? 'title="' + this.title + '"' : '') + ' class="%%-body" onmousedown="return false;" onclick="return $$._onClick();">' + (this.showIcon ? '<div class="edui-box edui-icon"></div>' : '') + (this.showText ? '<div class="edui-box edui-label">' + this.label + '</div>' : '') + '</div>' + '</div>' + '</div></div>'; }, postRender: function (){ this.Stateful_postRender(); this.setDisabled(this.disabled) }, _onClick: function (){ if (!this.isDisabled()) { this.fireEvent('click'); } } }; utils.inherits(Button, UIBase); utils.extend(Button.prototype, Stateful); })(); ///import core ///import uicore ///import ui/stateful.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, domUtils = baidu.editor.dom.domUtils, UIBase = baidu.editor.ui.UIBase, Stateful = baidu.editor.ui.Stateful, SplitButton = baidu.editor.ui.SplitButton = function (options){ this.initOptions(options); this.initSplitButton(); }; SplitButton.prototype = { popup: null, uiName: 'splitbutton', title: '', initSplitButton: function (){ this.initUIBase(); this.Stateful_init(); var me = this; if (this.popup != null) { var popup = this.popup; this.popup = null; this.setPopup(popup); } }, _UIBase_postRender: UIBase.prototype.postRender, postRender: function (){ this.Stateful_postRender(); this._UIBase_postRender(); }, setPopup: function (popup){ if (this.popup === popup) return; if (this.popup != null) { this.popup.dispose(); } popup.addListener('show', utils.bind(this._onPopupShow, this)); popup.addListener('hide', utils.bind(this._onPopupHide, this)); popup.addListener('postrender', utils.bind(function (){ popup.getDom('body').appendChild( uiUtils.createElementByHtml('<div id="' + this.popup.id + '_bordereraser" class="edui-bordereraser edui-background" style="width:' + (uiUtils.getClientRect(this.getDom()).width + 20) + 'px"></div>') ); popup.getDom().className += ' ' + this.className; }, this)); this.popup = popup; }, _onPopupShow: function (){ this.addState('opened'); }, _onPopupHide: function (){ this.removeState('opened'); }, getHtmlTpl: function (){ return '<div id="##" class="edui-box %%">' + '<div '+ (this.title ? 'title="' + this.title + '"' : '') +' id="##_state" stateful><div class="%%-body">' + '<div id="##_button_body" class="edui-box edui-button-body" onclick="$$._onButtonClick(event, this);">' + '<div class="edui-box edui-icon"></div>' + '</div>' + '<div class="edui-box edui-splitborder"></div>' + '<div class="edui-box edui-arrow" onclick="$$._onArrowClick();"></div>' + '</div></div></div>'; }, showPopup: function (){ // 当popup往上弹出的时候,做特殊处理 var rect = uiUtils.getClientRect(this.getDom()); rect.top -= this.popup.SHADOW_RADIUS; rect.height += this.popup.SHADOW_RADIUS; this.popup.showAnchorRect(rect); }, _onArrowClick: function (event, el){ if (!this.isDisabled()) { this.showPopup(); } }, _onButtonClick: function (){ if (!this.isDisabled()) { this.fireEvent('buttonclick'); } } }; utils.inherits(SplitButton, UIBase); utils.extend(SplitButton.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/colorpicker.js ///import ui/popup.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, ColorPicker = baidu.editor.ui.ColorPicker, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, ColorButton = baidu.editor.ui.ColorButton = function (options){ this.initOptions(options); this.initColorButton(); }; ColorButton.prototype = { initColorButton: function (){ var me = this; this.popup = new Popup({ content: new ColorPicker({ noColorText: me.editor.getLang("clearColor"), editor:me.editor, onpickcolor: function (t, color){ me._onPickColor(color); }, onpicknocolor: function (t, color){ me._onPickNoColor(color); } }), editor:me.editor }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.getDom('button_body').appendChild( uiUtils.createElementByHtml('<div id="' + this.id + '_colorlump" class="edui-colorlump"></div>') ); this.getDom().className += ' edui-colorbutton'; }, setColor: function (color){ this.getDom('colorlump').style.backgroundColor = color; this.color = color; }, _onPickColor: function (color){ if (this.fireEvent('pickcolor', color) !== false) { this.setColor(color); this.popup.hide(); } }, _onPickNoColor: function (color){ if (this.fireEvent('picknocolor') !== false) { this.popup.hide(); } } }; utils.inherits(ColorButton, SplitButton); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/tablepicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, TablePicker = baidu.editor.ui.TablePicker, SplitButton = baidu.editor.ui.SplitButton, TableButton = baidu.editor.ui.TableButton = function (options){ this.initOptions(options); this.initTableButton(); }; TableButton.prototype = { initTableButton: function (){ var me = this; this.popup = new Popup({ content: new TablePicker({ editor:me.editor, onpicktable: function (t, numCols, numRows){ me._onPickTable(numCols, numRows); } }), 'editor':me.editor }); this.initSplitButton(); }, _onPickTable: function (numCols, numRows){ if (this.fireEvent('picktable', numCols, numRows) !== false) { this.popup.hide(); } } }; utils.inherits(TableButton, SplitButton); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase; var AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker = function (options) { this.initOptions(options); this.initAutoTypeSetPicker(); }; AutoTypeSetPicker.prototype = { initAutoTypeSetPicker:function () { this.initUIBase(); }, getHtmlTpl:function () { var me = this.editor, opt = me.options.autotypeset, lang = me.getLang("autoTypeSet"); var textAlignInputName = 'textAlignValue' + me.uid, imageBlockInputName = 'imageBlockLineValue' + me.uid; return '<div id="##" class="edui-autotypesetpicker %%">' + '<div class="edui-autotypesetpicker-body">' + '<table >' + '<tr><td nowrap colspan="2"><input type="checkbox" name="mergeEmptyline" ' + (opt["mergeEmptyline"] ? "checked" : "" ) + '>' + lang.mergeLine + '</td><td colspan="2"><input type="checkbox" name="removeEmptyline" ' + (opt["removeEmptyline"] ? "checked" : "" ) + '>' + lang.delLine + '</td></tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="removeClass" ' + (opt["removeClass"] ? "checked" : "" ) + '>' + lang.removeFormat + '</td><td colspan="2"><input type="checkbox" name="indent" ' + (opt["indent"] ? "checked" : "" ) + '>' + lang.indent + '</td></tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="textAlign" ' + (opt["textAlign"] ? "checked" : "" ) + '>' + lang.alignment + '</td><td colspan="2" id="' + textAlignInputName + '"><input type="radio" name="'+ textAlignInputName +'" value="left" ' + ((opt["textAlign"] && opt["textAlign"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ textAlignInputName +'" value="center" ' + ((opt["textAlign"] && opt["textAlign"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ textAlignInputName +'" value="right" ' + ((opt["textAlign"] && opt["textAlign"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + ' </tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="imageBlockLine" ' + (opt["imageBlockLine"] ? "checked" : "" ) + '>' + lang.imageFloat + '</td>' + '<td nowrap colspan="2" id="'+ imageBlockInputName +'">' + '<input type="radio" name="'+ imageBlockInputName +'" value="none" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "none") ? "checked" : "") + '>' + me.getLang("default") + '<input type="radio" name="'+ imageBlockInputName +'" value="left" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "left") ? "checked" : "") + '>' + me.getLang("justifyleft") + '<input type="radio" name="'+ imageBlockInputName +'" value="center" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "center") ? "checked" : "") + '>' + me.getLang("justifycenter") + '<input type="radio" name="'+ imageBlockInputName +'" value="right" ' + ((opt["imageBlockLine"] && opt["imageBlockLine"] == "right") ? "checked" : "") + '>' + me.getLang("justifyright") + '</tr>' + '<tr><td nowrap colspan="2"><input type="checkbox" name="clearFontSize" ' + (opt["clearFontSize"] ? "checked" : "" ) + '>' + lang.removeFontsize + '</td><td colspan="2"><input type="checkbox" name="clearFontFamily" ' + (opt["clearFontFamily"] ? "checked" : "" ) + '>' + lang.removeFontFamily + '</td></tr>' + '<tr><td nowrap colspan="4"><input type="checkbox" name="removeEmptyNode" ' + (opt["removeEmptyNode"] ? "checked" : "" ) + '>' + lang.removeHtml + '</td></tr>' + '<tr><td nowrap colspan="4"><input type="checkbox" name="pasteFilter" ' + (opt["pasteFilter"] ? "checked" : "" ) + '>' + lang.pasteFilter + '</td></tr>' + '<tr><td nowrap colspan="4" align="right"><button >' + lang.run + '</button></td></tr>' + '</table>' + '</div>' + '</div>'; }, _UIBase_render:UIBase.prototype.render }; utils.inherits(AutoTypeSetPicker, UIBase); })(); ///import core ///import uicore ///import ui/popup.js ///import ui/autotypesetpicker.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, AutoTypeSetPicker = baidu.editor.ui.AutoTypeSetPicker, SplitButton = baidu.editor.ui.SplitButton, AutoTypeSetButton = baidu.editor.ui.AutoTypeSetButton = function (options){ this.initOptions(options); this.initAutoTypeSetButton(); }; function getPara(me){ var opt = me.editor.options.autotypeset, cont = me.getDom(), editorId = me.editor.uid, inputType = null, attrName = null, ipts = domUtils.getElementsByTagName(cont,"input"); for(var i=ipts.length-1,ipt;ipt=ipts[i--];){ inputType = ipt.getAttribute("type"); if(inputType=="checkbox"){ attrName = ipt.getAttribute("name"); opt[attrName] && delete opt[attrName]; if(ipt.checked){ var attrValue = document.getElementById( attrName+"Value" + editorId ); if(attrValue){ if(/input/ig.test(attrValue.tagName)){ opt[attrName] = attrValue.value; }else{ var iptChilds = attrValue.getElementsByTagName("input"); for(var j=iptChilds.length-1,iptchild;iptchild=iptChilds[j--];){ if(iptchild.checked){ opt[attrName] = iptchild.value; break; } } } }else{ opt[attrName] = true; } } } } var selects = domUtils.getElementsByTagName(cont,"select"); for(var i=0,si;si=selects[i++];){ var attr = si.getAttribute('name'); opt[attr] = opt[attr] ? si.value : ''; } me.editor.options.autotypeset = opt; } AutoTypeSetButton.prototype = { initAutoTypeSetButton: function (){ var me = this; this.popup = new Popup({ //传入配置参数 content: new AutoTypeSetPicker({editor:me.editor}), 'editor':me.editor, hide : function(){ if (!this._hidden && this.getDom()) { getPara(this); this.getDom().style.display = 'none'; this._hidden = true; this.fireEvent('hide'); } } }); var flag = 0; this.popup.addListener('postRenderAfter',function(){ var popupUI = this; if(flag)return; var cont = this.getDom(), btn = cont.getElementsByTagName('button')[0]; btn.onclick = function(){ getPara(popupUI); me.editor.execCommand('autotypeset'); popupUI.hide() }; flag = 1; }); this.initSplitButton(); } }; utils.inherits(AutoTypeSetButton, SplitButton); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, Stateful = baidu.editor.ui.Stateful, UIBase = baidu.editor.ui.UIBase; /** * 该参数将新增一个参数: selected, 参数类型为一个Object, 形如{ 'align': 'center', 'valign': 'top' }, 表示单元格的初始 * 对齐状态为: 竖直居上,水平居中; 其中 align的取值为:'center', 'left', 'right'; valign的取值为: 'top', 'middle', 'bottom' * @update 2013/4/2 [email protected] */ var CellAlignPicker = baidu.editor.ui.CellAlignPicker = function (options) { this.initOptions(options); this.initSelected(); this.initCellAlignPicker(); }; CellAlignPicker.prototype = { //初始化选中状态, 该方法将根据传递进来的参数获取到应该选中的对齐方式图标的索引 initSelected: function(){ var status = { valign: { top: 0, middle: 1, bottom: 2 }, align: { left: 0, center: 1, right: 2 }, count: 3 }, result = -1; if( this.selected ) { this.selectedIndex = status.valign[ this.selected.valign ] * status.count + status.align[ this.selected.align ]; } }, initCellAlignPicker:function () { this.initUIBase(); this.Stateful_init(); }, getHtmlTpl:function () { var alignType = [ 'left', 'center', 'right' ], COUNT = 9, tempClassName = null, tempIndex = -1, tmpl = []; for( var i= 0; i<COUNT; i++ ) { tempClassName = this.selectedIndex === i ? ' class="edui-cellalign-selected" ' : ''; tempIndex = i % 3; tempIndex === 0 && tmpl.push('<tr>'); tmpl.push( '<td index="'+ i +'" ' + tempClassName + ' stateful><div class="edui-icon edui-'+ alignType[ tempIndex ] +'"></div></td>' ); tempIndex === 2 && tmpl.push('</tr>'); } return '<div id="##" class="edui-cellalignpicker %%">' + '<div class="edui-cellalignpicker-body">' + '<table onclick="$$._onClick(event);">' + tmpl.join('') + '</table>' + '</div>' + '</div>'; }, getStateDom: function (){ return this.target; }, _onClick: function (evt){ var target= evt.target || evt.srcElement; if(/icon/.test(target.className)){ this.items[target.parentNode.getAttribute("index")].onclick(); Popup.postHide(evt); } }, _UIBase_render:UIBase.prototype.render }; utils.inherits(CellAlignPicker, UIBase); utils.extend(CellAlignPicker.prototype, Stateful,true); })(); ///import core ///import uicore (function () { var utils = baidu.editor.utils, Stateful = baidu.editor.ui.Stateful, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase; var PastePicker = baidu.editor.ui.PastePicker = function (options) { this.initOptions(options); this.initPastePicker(); }; PastePicker.prototype = { initPastePicker:function () { this.initUIBase(); this.Stateful_init(); }, getHtmlTpl:function () { return '<div class="edui-pasteicon" onclick="$$._onClick(this)"></div>' + '<div class="edui-pastecontainer">' + '<div class="edui-title">' + this.editor.getLang("pasteOpt") + '</div>' + '<div class="edui-button">' + '<div title="' + this.editor.getLang("pasteSourceFormat") + '" onclick="$$.format(false)" stateful>' + '<div class="edui-richtxticon"></div></div>' + '<div title="' + this.editor.getLang("tagFormat") + '" onclick="$$.format(2)" stateful>' + '<div class="edui-tagicon"></div></div>' + '<div title="' + this.editor.getLang("pasteTextFormat") + '" onclick="$$.format(true)" stateful>' + '<div class="edui-plaintxticon"></div></div>' + '</div>' + '</div>' + '</div>' }, getStateDom:function () { return this.target; }, format:function (param) { this.editor.ui._isTransfer = true; this.editor.fireEvent('pasteTransfer', param); }, _onClick:function (cur) { var node = domUtils.getNextDomNode(cur), screenHt = uiUtils.getViewportRect().height, subPop = uiUtils.getClientRect(node); if ((subPop.top + subPop.height) > screenHt) node.style.top = (-subPop.height - cur.offsetHeight) + "px"; else node.style.top = ""; if (/hidden/ig.test(domUtils.getComputedStyle(node, "visibility"))) { node.style.visibility = "visible"; domUtils.addClass(cur, "edui-state-opened"); } else { node.style.visibility = "hidden"; domUtils.removeClasses(cur, "edui-state-opened") } }, _UIBase_render:UIBase.prototype.render }; utils.inherits(PastePicker, UIBase); utils.extend(PastePicker.prototype, Stateful, true); })(); (function (){ var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Toolbar = baidu.editor.ui.Toolbar = function (options){ this.initOptions(options); this.initToolbar(); }; Toolbar.prototype = { items: null, initToolbar: function (){ this.items = this.items || []; this.initUIBase(); }, add: function (item){ this.items.push(item); }, getHtmlTpl: function (){ var buff = []; for (var i=0; i<this.items.length; i++) { buff[i] = this.items[i].renderHtml(); } return '<div id="##" class="edui-toolbar %%" onselectstart="return false;" onmousedown="return $$._onMouseDown(event, this);">' + buff.join('') + '</div>' }, postRender: function (){ var box = this.getDom(); for (var i=0; i<this.items.length; i++) { this.items[i].postRender(); } uiUtils.makeUnselectable(box); }, _onMouseDown: function (){ return false; } }; utils.inherits(Toolbar, UIBase); })(); ///import core ///import uicore ///import ui\popup.js ///import ui\stateful.js (function () { var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, Popup = baidu.editor.ui.Popup, Stateful = baidu.editor.ui.Stateful, CellAlignPicker = baidu.editor.ui.CellAlignPicker, Menu = baidu.editor.ui.Menu = function (options) { this.initOptions(options); this.initMenu(); }; var menuSeparator = { renderHtml:function () { return '<div class="edui-menuitem edui-menuseparator"><div class="edui-menuseparator-inner"></div></div>'; }, postRender:function () { }, queryAutoHide:function () { return true; } }; Menu.prototype = { items:null, uiName:'menu', initMenu:function () { this.items = this.items || []; this.initPopup(); this.initItems(); }, initItems:function () { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item == '-') { this.items[i] = this.getSeparator(); } else if (!(item instanceof MenuItem)) { item.editor = this.editor; item.theme = this.editor.options.theme; this.items[i] = this.createItem(item); } } }, getSeparator:function () { return menuSeparator; }, createItem:function (item) { //新增一个参数menu, 该参数存储了menuItem所对应的menu引用 item.menu = this; return new MenuItem(item); }, _Popup_getContentHtmlTpl:Popup.prototype.getContentHtmlTpl, getContentHtmlTpl:function () { if (this.items.length == 0) { return this._Popup_getContentHtmlTpl(); } var buff = []; for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; buff[i] = item.renderHtml(); } return ('<div class="%%-body">' + buff.join('') + '</div>'); }, _Popup_postRender:Popup.prototype.postRender, postRender:function () { var me = this; for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; item.ownerMenu = this; item.postRender(); } domUtils.on(this.getDom(), 'mouseover', function (evt) { evt = evt || event; var rel = evt.relatedTarget || evt.fromElement; var el = me.getDom(); if (!uiUtils.contains(el, rel) && el !== rel) { me.fireEvent('over'); } }); this._Popup_postRender(); }, queryAutoHide:function (el) { if (el) { if (uiUtils.contains(this.getDom(), el)) { return false; } for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; if (item.queryAutoHide(el) === false) { return false; } } } }, clearItems:function () { for (var i = 0; i < this.items.length; i++) { var item = this.items[i]; clearTimeout(item._showingTimer); clearTimeout(item._closingTimer); if (item.subMenu) { item.subMenu.destroy(); } } this.items = []; }, destroy:function () { if (this.getDom()) { domUtils.remove(this.getDom()); } this.clearItems(); }, dispose:function () { this.destroy(); } }; utils.inherits(Menu, Popup); /** * @update 2013/04/03 hancong03 新增一个参数menu, 该参数存储了menuItem所对应的menu引用 * @type {Function} */ var MenuItem = baidu.editor.ui.MenuItem = function (options) { this.initOptions(options); this.initUIBase(); this.Stateful_init(); if (this.subMenu && !(this.subMenu instanceof Menu)) { if (options.className && options.className.indexOf("aligntd") != -1) { var me = this; //获取单元格对齐初始状态 this.subMenu.selected = this.editor.queryCommandValue( 'cellalignment' ); this.subMenu = new Popup({ content:new CellAlignPicker(this.subMenu), parentMenu:me, editor:me.editor, destroy:function () { if (this.getDom()) { domUtils.remove(this.getDom()); } } }); this.subMenu.addListener("postRenderAfter", function () { domUtils.on(this.getDom(), "mouseover", function () { me.addState('opened'); }); }); } else { this.subMenu = new Menu(this.subMenu); } } }; MenuItem.prototype = { label:'', subMenu:null, ownerMenu:null, uiName:'menuitem', alwalysHoverable:true, getHtmlTpl:function () { return '<div id="##" class="%%" stateful onclick="$$._onClick(event, this);">' + '<div class="%%-body">' + this.renderLabelHtml() + '</div>' + '</div>'; }, postRender:function () { var me = this; this.addListener('over', function () { me.ownerMenu.fireEvent('submenuover', me); if (me.subMenu) { me.delayShowSubMenu(); } }); if (this.subMenu) { this.getDom().className += ' edui-hassubmenu'; this.subMenu.render(); this.addListener('out', function () { me.delayHideSubMenu(); }); this.subMenu.addListener('over', function () { clearTimeout(me._closingTimer); me._closingTimer = null; me.addState('opened'); }); this.ownerMenu.addListener('hide', function () { me.hideSubMenu(); }); this.ownerMenu.addListener('submenuover', function (t, subMenu) { if (subMenu !== me) { me.delayHideSubMenu(); } }); this.subMenu._bakQueryAutoHide = this.subMenu.queryAutoHide; this.subMenu.queryAutoHide = function (el) { if (el && uiUtils.contains(me.getDom(), el)) { return false; } return this._bakQueryAutoHide(el); }; } this.getDom().style.tabIndex = '-1'; uiUtils.makeUnselectable(this.getDom()); this.Stateful_postRender(); }, delayShowSubMenu:function () { var me = this; if (!me.isDisabled()) { me.addState('opened'); clearTimeout(me._showingTimer); clearTimeout(me._closingTimer); me._closingTimer = null; me._showingTimer = setTimeout(function () { me.showSubMenu(); }, 250); } }, delayHideSubMenu:function () { var me = this; if (!me.isDisabled()) { me.removeState('opened'); clearTimeout(me._showingTimer); if (!me._closingTimer) { me._closingTimer = setTimeout(function () { if (!me.hasState('opened')) { me.hideSubMenu(); } me._closingTimer = null; }, 400); } } }, renderLabelHtml:function () { return '<div class="edui-arrow"></div>' + '<div class="edui-box edui-icon"></div>' + '<div class="edui-box edui-label %%-label">' + (this.label || '') + '</div>'; }, getStateDom:function () { return this.getDom(); }, queryAutoHide:function (el) { if (this.subMenu && this.hasState('opened')) { return this.subMenu.queryAutoHide(el); } }, _onClick:function (event, this_) { if (this.hasState('disabled')) return; if (this.fireEvent('click', event, this_) !== false) { if (this.subMenu) { this.showSubMenu(); } else { Popup.postHide(event); } } }, showSubMenu:function () { var rect = uiUtils.getClientRect(this.getDom()); rect.right -= 5; rect.left += 2; rect.width -= 7; rect.top -= 4; rect.bottom += 4; rect.height += 8; this.subMenu.showAnchorRect(rect, true, true); }, hideSubMenu:function () { this.subMenu.hide(); } }; utils.inherits(MenuItem, UIBase); utils.extend(MenuItem.prototype, Stateful, true); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ // todo: menu和item提成通用list var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, Combox = baidu.editor.ui.Combox = function (options){ this.initOptions(options); this.initCombox(); }; Combox.prototype = { uiName: 'combox', initCombox: function (){ var me = this; this.items = this.items || []; for (var i=0; i<this.items.length; i++) { var item = this.items[i]; item.uiName = 'listitem'; item.index = i; item.onclick = function (){ me.selectByIndex(this.index); }; } this.popup = new Menu({ items: this.items, uiName: 'list', editor:this.editor, captureWheel: true, combox: this }); this.initSplitButton(); }, _SplitButton_postRender: SplitButton.prototype.postRender, postRender: function (){ this._SplitButton_postRender(); this.setLabel(this.label || ''); this.setValue(this.initValue || ''); }, showPopup: function (){ var rect = uiUtils.getClientRect(this.getDom()); rect.top += 1; rect.bottom -= 1; rect.height -= 2; this.popup.showAnchorRect(rect); }, getValue: function (){ return this.value; }, setValue: function (value){ var index = this.indexByValue(value); if (index != -1) { this.selectedIndex = index; this.setLabel(this.items[index].label); this.value = this.items[index].value; } else { this.selectedIndex = -1; this.setLabel(this.getLabelForUnknowValue(value)); this.value = value; } }, setLabel: function (label){ this.getDom('button_body').innerHTML = label; this.label = label; }, getLabelForUnknowValue: function (value){ return value; }, indexByValue: function (value){ for (var i=0; i<this.items.length; i++) { if (value == this.items[i].value) { return i; } } return -1; }, getItem: function (index){ return this.items[index]; }, selectByIndex: function (index){ if (index < this.items.length && this.fireEvent('select', index) !== false) { this.selectedIndex = index; this.value = this.items[index].value; this.setLabel(this.items[index].label); } } }; utils.inherits(Combox, SplitButton); })(); ///import core ///import uicore ///import ui/mask.js ///import ui/button.js (function (){ var utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils, uiUtils = baidu.editor.ui.uiUtils, Mask = baidu.editor.ui.Mask, UIBase = baidu.editor.ui.UIBase, Button = baidu.editor.ui.Button, Dialog = baidu.editor.ui.Dialog = function (options){ this.initOptions(utils.extend({ autoReset: true, draggable: true, onok: function (){}, oncancel: function (){}, onclose: function (t, ok){ return ok ? this.onok() : this.oncancel(); }, //是否控制dialog中的scroll事件, 默认为不阻止 holdScroll: false },options)); this.initDialog(); }; var modalMask; var dragMask; Dialog.prototype = { draggable: false, uiName: 'dialog', initDialog: function (){ var me = this, theme=this.editor.options.theme; this.initUIBase(); this.modalMask = (modalMask || (modalMask = new Mask({ className: 'edui-dialog-modalmask', theme:theme }))); this.dragMask = (dragMask || (dragMask = new Mask({ className: 'edui-dialog-dragmask', theme:theme }))); this.closeButton = new Button({ className: 'edui-dialog-closebutton', title: me.closeDialog, theme:theme, onclick: function (){ me.close(false); } }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { if (!(this.buttons[i] instanceof Button)) { this.buttons[i] = new Button(this.buttons[i]); } } } }, fitSize: function (){ var popBodyEl = this.getDom('body'); // if (!(baidu.editor.browser.ie && baidu.editor.browser.version == 7)) { // uiUtils.removeStyle(popBodyEl, 'width'); // uiUtils.removeStyle(popBodyEl, 'height'); // } var size = this.mesureSize(); popBodyEl.style.width = size.width + 'px'; popBodyEl.style.height = size.height + 'px'; return size; }, safeSetOffset: function (offset){ var me = this; var el = me.getDom(); var vpRect = uiUtils.getViewportRect(); var rect = uiUtils.getClientRect(el); var left = offset.left; if (left + rect.width > vpRect.right) { left = vpRect.right - rect.width; } var top = offset.top; if (top + rect.height > vpRect.bottom) { top = vpRect.bottom - rect.height; } el.style.left = Math.max(left, 0) + 'px'; el.style.top = Math.max(top, 0) + 'px'; }, showAtCenter: function (){ this.getDom().style.display = ''; var vpRect = uiUtils.getViewportRect(); var popSize = this.fitSize(); var titleHeight = this.getDom('titlebar').offsetHeight | 0; var left = vpRect.width / 2 - popSize.width / 2; var top = vpRect.height / 2 - (popSize.height - titleHeight) / 2 - titleHeight; var popEl = this.getDom(); this.safeSetOffset({ left: Math.max(left | 0, 0), top: Math.max(top | 0, 0) }); if (!domUtils.hasClass(popEl, 'edui-state-centered')) { popEl.className += ' edui-state-centered'; } this._show(); }, getContentHtml: function (){ var contentHtml = ''; if (typeof this.content == 'string') { contentHtml = this.content; } else if (this.iframeUrl) { contentHtml = '<span id="'+ this.id +'_contmask" class="dialogcontmask"></span><iframe id="'+ this.id + '_iframe" class="%%-iframe" height="100%" width="100%" frameborder="0" src="'+ this.iframeUrl +'"></iframe>'; } return contentHtml; }, getHtmlTpl: function (){ var footHtml = ''; if (this.buttons) { var buff = []; for (var i=0; i<this.buttons.length; i++) { buff[i] = this.buttons[i].renderHtml(); } footHtml = '<div class="%%-foot">' + '<div id="##_buttons" class="%%-buttons">' + buff.join('') + '</div>' + '</div>'; } return '<div id="##" class="%%"><div class="%%-wrap"><div id="##_body" class="%%-body">' + '<div class="%%-shadow"></div>' + '<div id="##_titlebar" class="%%-titlebar">' + '<div class="%%-draghandle" onmousedown="$$._onTitlebarMouseDown(event, this);">' + '<span class="%%-caption">' + (this.title || '') + '</span>' + '</div>' + this.closeButton.renderHtml() + '</div>' + '<div id="##_content" class="%%-content">'+ ( this.autoReset ? '' : this.getContentHtml()) +'</div>' + footHtml + '</div></div></div>'; }, postRender: function (){ // todo: 保持居中/记住上次关闭位置选项 if (!this.modalMask.getDom()) { this.modalMask.render(); this.modalMask.hide(); } if (!this.dragMask.getDom()) { this.dragMask.render(); this.dragMask.hide(); } var me = this; this.addListener('show', function (){ me.modalMask.show(this.getDom().style.zIndex - 2); }); this.addListener('hide', function (){ me.modalMask.hide(); }); if (this.buttons) { for (var i=0; i<this.buttons.length; i++) { this.buttons[i].postRender(); } } domUtils.on(window, 'resize', function (){ setTimeout(function (){ if (!me.isHidden()) { me.safeSetOffset(uiUtils.getClientRect(me.getDom())); } }); }); //hold住scroll事件,防止dialog的滚动影响页面 if( this.holdScroll ) { if( !me.iframeUrl ) { domUtils.on( document.getElementById( me.id + "_iframe"), !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } else { me.addListener('dialogafterreset', function(){ window.setTimeout(function(){ var iframeWindow = document.getElementById( me.id + "_iframe").contentWindow; if( browser.ie ) { var timer = window.setInterval(function(){ if( iframeWindow.document && iframeWindow.document.body ) { window.clearInterval( timer ); timer = null; domUtils.on( iframeWindow.document.body, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } }, 100); } else { domUtils.on( iframeWindow, !browser.gecko ? "mousewheel" : "DOMMouseScroll", function(e){ domUtils.preventDefault(e); } ); } }, 1); }); } } this._hide(); }, mesureSize: function (){ var body = this.getDom('body'); var width = uiUtils.getClientRect(this.getDom('content')).width; var dialogBodyStyle = body.style; dialogBodyStyle.width = width; return uiUtils.getClientRect(body); }, _onTitlebarMouseDown: function (evt, el){ if (this.draggable) { var rect; var vpRect = uiUtils.getViewportRect(); var me = this; uiUtils.startDrag(evt, { ondragstart: function (){ rect = uiUtils.getClientRect(me.getDom()); me.getDom('contmask').style.visibility = 'visible'; me.dragMask.show(me.getDom().style.zIndex - 1); }, ondragmove: function (x, y){ var left = rect.left + x; var top = rect.top + y; me.safeSetOffset({ left: left, top: top }); }, ondragstop: function (){ me.getDom('contmask').style.visibility = 'hidden'; domUtils.removeClasses(me.getDom(), ['edui-state-centered']); me.dragMask.hide(); } }); } }, reset: function (){ this.getDom('content').innerHTML = this.getContentHtml(); this.fireEvent('dialogafterreset'); }, _show: function (){ if (this._hidden) { this.getDom().style.display = ''; //要高过编辑器的zindxe this.editor.container.style.zIndex && (this.getDom().style.zIndex = this.editor.container.style.zIndex * 1 + 10); this._hidden = false; this.fireEvent('show'); baidu.editor.ui.uiUtils.getFixedLayer().style.zIndex = this.getDom().style.zIndex - 4; } }, isHidden: function (){ return this._hidden; }, _hide: function (){ if (!this._hidden) { this.getDom().style.display = 'none'; this.getDom().style.zIndex = ''; this._hidden = true; this.fireEvent('hide'); } }, open: function (){ if (this.autoReset) { //有可能还没有渲染 try{ this.reset(); }catch(e){ this.render(); this.open() } } this.showAtCenter(); if (this.iframeUrl) { try { this.getDom('iframe').focus(); } catch(ex){} } }, _onCloseButtonClick: function (evt, el){ this.close(false); }, close: function (ok){ if (this.fireEvent('close', ok) !== false) { this._hide(); } } }; utils.inherits(Dialog, UIBase); })(); ///import core ///import uicore ///import ui/menu.js ///import ui/splitbutton.js (function (){ var utils = baidu.editor.utils, Menu = baidu.editor.ui.Menu, SplitButton = baidu.editor.ui.SplitButton, MenuButton = baidu.editor.ui.MenuButton = function (options){ this.initOptions(options); this.initMenuButton(); }; MenuButton.prototype = { initMenuButton: function (){ var me = this; this.uiName = "menubutton"; this.popup = new Menu({ items: me.items, className: me.className, editor:me.editor }); this.popup.addListener('show', function (){ var list = this; for (var i=0; i<list.items.length; i++) { list.items[i].removeState('checked'); if (list.items[i].value == me._value) { list.items[i].addState('checked'); this.value = me._value; } } }); this.initSplitButton(); }, setValue : function(value){ this._value = value; } }; utils.inherits(MenuButton, SplitButton); })();//ui跟编辑器的适配層 //那个按钮弹出是dialog,是下拉筐等都是在这个js中配置 //自己写的ui也要在这里配置,放到baidu.editor.ui下边,当编辑器实例化的时候会根据ueditor.config中的toolbars找到相应的进行实例化 (function () { var utils = baidu.editor.utils; var editorui = baidu.editor.ui; var _Dialog = editorui.Dialog; editorui.buttons = {}; editorui.Dialog = function (options) { var dialog = new _Dialog(options); dialog.addListener('hide', function () { if (dialog.editor) { var editor = dialog.editor; try { if (browser.gecko) { var y = editor.window.scrollY, x = editor.window.scrollX; editor.body.focus(); editor.window.scrollTo(x, y); } else { editor.focus(); } } catch (ex) { } } }); return dialog; }; var iframeUrlMap = { 'anchor':'~/dialogs/anchor/anchor.html', 'insertimage':'~/dialogs/image/image.html', 'link':'~/dialogs/link/link.html', 'spechars':'~/dialogs/spechars/spechars.html', 'searchreplace':'~/dialogs/searchreplace/searchreplace.html', 'map':'~/dialogs/map/map.html', 'gmap':'~/dialogs/gmap/gmap.html', 'insertvideo':'~/dialogs/video/video.html', 'help':'~/dialogs/help/help.html', //'highlightcode':'~/dialogs/highlightcode/highlightcode.html', 'emotion':'~/dialogs/emotion/emotion.html', 'wordimage':'~/dialogs/wordimage/wordimage.html', 'attachment':'~/dialogs/attachment/attachment.html', 'insertframe':'~/dialogs/insertframe/insertframe.html', 'edittip':'~/dialogs/table/edittip.html', 'edittable':'~/dialogs/table/edittable.html', 'edittd':'~/dialogs/table/edittd.html', 'webapp':'~/dialogs/webapp/webapp.html', 'snapscreen':'~/dialogs/snapscreen/snapscreen.html', 'scrawl':'~/dialogs/scrawl/scrawl.html', 'music':'~/dialogs/music/music.html', 'template':'~/dialogs/template/template.html', 'background':'~/dialogs/background/background.html' }; //为工具栏添加按钮,以下都是统一的按钮触发命令,所以写在一起 var btnCmds = ['undo', 'redo', 'formatmatch', 'bold', 'italic', 'underline', 'fontborder', 'touppercase', 'tolowercase', 'strikethrough', 'subscript', 'superscript', 'source', 'indent', 'outdent', 'blockquote', 'pasteplain', 'pagebreak', 'selectall', 'print', 'preview', 'horizontal', 'removeformat', 'time', 'date', 'unlink', 'insertparagraphbeforetable', 'insertrow', 'insertcol', 'mergeright', 'mergedown', 'deleterow', 'deletecol', 'splittorows', 'splittocols', 'splittocells', 'mergecells', 'deletetable']; for (var i = 0, ci; ci = btnCmds[i++];) { ci = ci.toLowerCase(); editorui[ci] = function (cmd) { return function (editor) { var ui = new editorui.Button({ className:'edui-for-' + cmd, title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '', onclick:function () { editor.execCommand(cmd); }, theme:editor.options.theme, showText:false }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); ui.setChecked(false); } else { if (!uiReady) { ui.setDisabled(false); ui.setChecked(state); } } }); return ui; }; }(ci); } //清除文档 editorui.cleardoc = function (editor) { var ui = new editorui.Button({ className:'edui-for-cleardoc', title:editor.options.labelMap.cleardoc || editor.getLang("labelMap.cleardoc") || '', theme:editor.options.theme, onclick:function () { if (confirm(editor.getLang("confirmClear"))) { editor.execCommand('cleardoc'); } } }); editorui.buttons["cleardoc"] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('cleardoc') == -1); }); return ui; }; //排版,图片排版,文字方向 var typeset = { 'justify':['left', 'right', 'center', 'justify'], 'imagefloat':['none', 'left', 'center', 'right'], 'directionality':['ltr', 'rtl'] }; for (var p in typeset) { (function (cmd, val) { for (var i = 0, ci; ci = val[i++];) { (function (cmd2) { editorui[cmd.replace('float', '') + cmd2] = function (editor) { var ui = new editorui.Button({ className:'edui-for-' + cmd.replace('float', '') + cmd2, title:editor.options.labelMap[cmd.replace('float', '') + cmd2] || editor.getLang("labelMap." + cmd.replace('float', '') + cmd2) || '', theme:editor.options.theme, onclick:function () { editor.execCommand(cmd, cmd2); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { ui.setDisabled(editor.queryCommandState(cmd) == -1); ui.setChecked(editor.queryCommandValue(cmd) == cmd2 && !uiReady); }); return ui; }; })(ci) } })(p, typeset[p]) } //字体颜色和背景颜色 for (var i = 0, ci; ci = ['backcolor', 'forecolor'][i++];) { editorui[ci] = function (cmd) { return function (editor) { var ui = new editorui.ColorButton({ className:'edui-for-' + cmd, color:'default', title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || '', editor:editor, onpickcolor:function (t, color) { editor.execCommand(cmd, color); }, onpicknocolor:function () { editor.execCommand(cmd, 'default'); this.setColor('transparent'); this.color = 'default'; }, onbuttonclick:function () { editor.execCommand(cmd, this.color); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState(cmd) == -1); }); return ui; }; }(ci); } var dialogBtns = { noOk:['searchreplace', 'help', 'spechars', 'webapp'], ok:['attachment', 'anchor', 'link', 'insertimage', 'map', 'gmap', 'insertframe', 'wordimage', 'insertvideo', 'insertframe', 'edittip', 'edittable', 'edittd', 'scrawl', 'template', 'music', 'background'] }; for (var p in dialogBtns) { (function (type, vals) { for (var i = 0, ci; ci = vals[i++];) { //todo opera下存在问题 if (browser.opera && ci === "searchreplace") { continue; } (function (cmd) { editorui[cmd] = function (editor, iframeUrl, title) { iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd]; title = editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd) || ''; var dialog; //没有iframeUrl不创建dialog if (iframeUrl) { dialog = new editorui.Dialog(utils.extend({ iframeUrl:editor.ui.mapUrl(iframeUrl), editor:editor, className:'edui-for-' + cmd, title:title, holdScroll: cmd === 'insertimage', closeDialog:editor.getLang("closeDialog") }, type == 'ok' ? { buttons:[ { className:'edui-okbutton', label:editor.getLang("ok"), editor:editor, onclick:function () { dialog.close(true); } }, { className:'edui-cancelbutton', label:editor.getLang("cancel"), editor:editor, onclick:function () { dialog.close(false); } } ] } : {})); editor.ui._dialogs[cmd + "Dialog"] = dialog; } var ui = new editorui.Button({ className:'edui-for-' + cmd, title:title, onclick:function () { if (dialog) { switch (cmd) { case "wordimage": editor.execCommand("wordimage", "word_img"); if (editor.word_img) { dialog.render(); dialog.open(); } break; case "scrawl": if (editor.queryCommandState("scrawl") != -1) { dialog.render(); dialog.open(); } break; default: dialog.render(); dialog.open(); } } }, theme:editor.options.theme, disabled:cmd == 'scrawl' && editor.queryCommandState("scrawl") == -1 }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { //只存在于右键菜单而无工具栏按钮的ui不需要检测状态 var unNeedCheckState = {'edittable':1}; if (cmd in unNeedCheckState)return; var state = editor.queryCommandState(cmd); if (ui.getDom()) { ui.setDisabled(state == -1); ui.setChecked(state); } }); return ui; }; })(ci.toLowerCase()) } })(p, dialogBtns[p]) } editorui.snapscreen = function (editor, iframeUrl, title) { title = editor.options.labelMap['snapscreen'] || editor.getLang("labelMap.snapscreen") || ''; var ui = new editorui.Button({ className:'edui-for-snapscreen', title:title, onclick:function () { editor.execCommand("snapscreen"); }, theme:editor.options.theme }); editorui.buttons['snapscreen'] = ui; iframeUrl = iframeUrl || (editor.options.iframeUrlMap || {})["snapscreen"] || iframeUrlMap["snapscreen"]; if (iframeUrl) { var dialog = new editorui.Dialog({ iframeUrl:editor.ui.mapUrl(iframeUrl), editor:editor, className:'edui-for-snapscreen', title:title, buttons:[ { className:'edui-okbutton', label:editor.getLang("ok"), editor:editor, onclick:function () { dialog.close(true); } }, { className:'edui-cancelbutton', label:editor.getLang("cancel"), editor:editor, onclick:function () { dialog.close(false); } } ] }); dialog.render(); editor.ui._dialogs["snapscreenDialog"] = dialog; } editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('snapscreen') == -1); }); return ui; }; editorui.insertcode = function (editor, list, title) { list = editor.options['insertcode'] || []; title = editor.options.labelMap['insertcode'] || editor.getLang("labelMap.insertcode") || ''; // if (!list.length) return; var items = []; utils.each(list,function(key,val){ items.push({ label:key, value:val, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" >' + (this.label || '') + '</div>'; } }); }); var ui = new editorui.Combox({ editor:editor, items:items, onselect:function (t, index) { editor.execCommand('insertcode', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, title:title, initValue:title, className:'edui-for-insertcode', indexByValue:function (value) { if (value) { for (var i = 0, ci; ci = this.items[i]; i++) { if (ci.value.indexOf(value) != -1) return i; } } return -1; } }); editorui.buttons['insertcode'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('insertcode'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('insertcode'); if(!value){ ui.setValue(title); return; } //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号 value && (value = value.replace(/['"]/g, '').split(',')[0]); ui.setValue(value); } } }); return ui; }; editorui.fontfamily = function (editor, list, title) { list = editor.options['fontfamily'] || []; title = editor.options.labelMap['fontfamily'] || editor.getLang("labelMap.fontfamily") || ''; if (!list.length) return; for (var i = 0, ci, items = []; ci = list[i]; i++) { var langLabel = editor.getLang('fontfamily')[ci.name] || ""; (function (key, val) { items.push({ label:key, value:val, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" style="font-family:' + utils.unhtml(this.value) + '">' + (this.label || '') + '</div>'; } }); })(ci.label || langLabel, ci.val) } var ui = new editorui.Combox({ editor:editor, items:items, onselect:function (t, index) { editor.execCommand('FontFamily', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, title:title, initValue:title, className:'edui-for-fontfamily', indexByValue:function (value) { if (value) { for (var i = 0, ci; ci = this.items[i]; i++) { if (ci.value.indexOf(value) != -1) return i; } } return -1; } }); editorui.buttons['fontfamily'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('FontFamily'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('FontFamily'); //trace:1871 ie下从源码模式切换回来时,字体会带单引号,而且会有逗号 value && (value = value.replace(/['"]/g, '').split(',')[0]); ui.setValue(value); } } }); return ui; }; editorui.fontsize = function (editor, list, title) { title = editor.options.labelMap['fontsize'] || editor.getLang("labelMap.fontsize") || ''; list = list || editor.options['fontsize'] || []; if (!list.length) return; var items = []; for (var i = 0; i < list.length; i++) { var size = list[i] + 'px'; items.push({ label:size, value:size, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label" style="line-height:1;font-size:' + this.value + '">' + (this.label || '') + '</div>'; } }); } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, onselect:function (t, index) { editor.execCommand('FontSize', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, className:'edui-for-fontsize' }); editorui.buttons['fontsize'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('FontSize'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); ui.setValue(editor.queryCommandValue('FontSize')); } } }); return ui; }; editorui.paragraph = function (editor, list, title) { title = editor.options.labelMap['paragraph'] || editor.getLang("labelMap.paragraph") || ''; list = editor.options['paragraph'] || []; if (utils.isEmptyObject(list)) return; var items = []; for (var i in list) { items.push({ value:i, label:list[i] || editor.getLang("paragraph")[i], theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label"><span class="edui-for-' + this.value + '">' + (this.label || '') + '</span></div>'; } }) } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, className:'edui-for-paragraph', onselect:function (t, index) { editor.execCommand('Paragraph', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); } }); editorui.buttons['paragraph'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('Paragraph'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('Paragraph'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; //自定义标题 editorui.customstyle = function (editor) { var list = editor.options['customstyle'] || [], title = editor.options.labelMap['customstyle'] || editor.getLang("labelMap.customstyle") || ''; if (!list.length)return; var langCs = editor.getLang('customstyle'); for (var i = 0, items = [], t; t = list[i++];) { (function (t) { var ck = {}; ck.label = t.label ? t.label : langCs[t.name]; ck.style = t.style; ck.className = t.className; ck.tag = t.tag; items.push({ label:ck.label, value:ck, theme:editor.options.theme, renderLabelHtml:function () { return '<div class="edui-label %%-label">' + '<' + ck.tag + ' ' + (ck.className ? ' class="' + ck.className + '"' : "") + (ck.style ? ' style="' + ck.style + '"' : "") + '>' + ck.label + "<\/" + ck.tag + ">" + '</div>'; } }); })(t); } var ui = new editorui.Combox({ editor:editor, items:items, title:title, initValue:title, className:'edui-for-customstyle', onselect:function (t, index) { editor.execCommand('customstyle', this.items[index].value); }, onbuttonclick:function () { this.showPopup(); }, indexByValue:function (value) { for (var i = 0, ti; ti = this.items[i++];) { if (ti.label == value) { return i - 1 } } return -1; } }); editorui.buttons['customstyle'] = ui; editor.addListener('selectionchange', function (type, causeByUi, uiReady) { if (!uiReady) { var state = editor.queryCommandState('customstyle'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('customstyle'); var index = ui.indexByValue(value); if (index != -1) { ui.setValue(value); } else { ui.setValue(ui.initValue); } } } }); return ui; }; editorui.inserttable = function (editor, iframeUrl, title) { title = editor.options.labelMap['inserttable'] || editor.getLang("labelMap.inserttable") || ''; var ui = new editorui.TableButton({ editor:editor, title:title, className:'edui-for-inserttable', onpicktable:function (t, numCols, numRows) { editor.execCommand('InsertTable', {numRows:numRows, numCols:numCols, border:1}); }, onbuttonclick:function () { this.showPopup(); } }); editorui.buttons['inserttable'] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('inserttable') == -1); }); return ui; }; editorui.lineheight = function (editor) { var val = editor.options.lineheight || []; if (!val.length)return; for (var i = 0, ci, items = []; ci = val[i++];) { items.push({ //todo:写死了 label:ci, value:ci, theme:editor.options.theme, onclick:function () { editor.execCommand("lineheight", this.value); } }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-lineheight', title:editor.options.labelMap['lineheight'] || editor.getLang("labelMap.lineheight") || '', items:items, onbuttonclick:function () { var value = editor.queryCommandValue('LineHeight') || this.value; editor.execCommand("LineHeight", value); } }); editorui.buttons['lineheight'] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('LineHeight'); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('LineHeight'); value && ui.setValue((value + '').replace(/cm/, '')); ui.setChecked(state) } }); return ui; }; var rowspacings = ['top', 'bottom']; for (var r = 0, ri; ri = rowspacings[r++];) { (function (cmd) { editorui['rowspacing' + cmd] = function (editor) { var val = editor.options['rowspacing' + cmd] || []; if (!val.length) return null; for (var i = 0, ci, items = []; ci = val[i++];) { items.push({ label:ci, value:ci, theme:editor.options.theme, onclick:function () { editor.execCommand("rowspacing", this.value, cmd); } }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-rowspacing' + cmd, title:editor.options.labelMap['rowspacing' + cmd] || editor.getLang("labelMap.rowspacing" + cmd) || '', items:items, onbuttonclick:function () { var value = editor.queryCommandValue('rowspacing', cmd) || this.value; editor.execCommand("rowspacing", value, cmd); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('rowspacing', cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue('rowspacing', cmd); value && ui.setValue((value + '').replace(/%/, '')); ui.setChecked(state) } }); return ui; } })(ri) } //有序,无序列表 var lists = ['insertorderedlist', 'insertunorderedlist']; for (var l = 0, cl; cl = lists[l++];) { (function (cmd) { editorui[cmd] = function (editor) { var vals = editor.options[cmd], _onMenuClick = function () { editor.execCommand(cmd, this.value); }, items = []; for (var i in vals) { items.push({ label:vals[i] || editor.getLang()[cmd][i] || "", value:i, theme:editor.options.theme, onclick:_onMenuClick }) } var ui = new editorui.MenuButton({ editor:editor, className:'edui-for-' + cmd, title:editor.getLang("labelMap." + cmd) || '', 'items':items, onbuttonclick:function () { var value = editor.queryCommandValue(cmd) || this.value; editor.execCommand(cmd, value); } }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState(cmd); if (state == -1) { ui.setDisabled(true); } else { ui.setDisabled(false); var value = editor.queryCommandValue(cmd); ui.setValue(value); ui.setChecked(state) } }); return ui; }; })(cl) } editorui.fullscreen = function (editor, title) { title = editor.options.labelMap['fullscreen'] || editor.getLang("labelMap.fullscreen") || ''; var ui = new editorui.Button({ className:'edui-for-fullscreen', title:title, theme:editor.options.theme, onclick:function () { if (editor.ui) { editor.ui.setFullScreen(!editor.ui.isFullScreen()); } this.setChecked(editor.ui.isFullScreen()); } }); editorui.buttons['fullscreen'] = ui; editor.addListener('selectionchange', function () { var state = editor.queryCommandState('fullscreen'); ui.setDisabled(state == -1); ui.setChecked(editor.ui.isFullScreen()); }); return ui; }; // 表情 editorui["emotion"] = function (editor, iframeUrl) { var cmd = "emotion"; var ui = new editorui.MultiMenuPop({ title:editor.options.labelMap[cmd] || editor.getLang("labelMap." + cmd + "") || '', editor:editor, className:'edui-for-' + cmd, iframeUrl:editor.ui.mapUrl(iframeUrl || (editor.options.iframeUrlMap || {})[cmd] || iframeUrlMap[cmd]) }); editorui.buttons[cmd] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState(cmd) == -1) }); return ui; }; editorui.autotypeset = function (editor) { var ui = new editorui.AutoTypeSetButton({ editor:editor, title:editor.options.labelMap['autotypeset'] || editor.getLang("labelMap.autotypeset") || '', className:'edui-for-autotypeset', onbuttonclick:function () { editor.execCommand('autotypeset') } }); editorui.buttons['autotypeset'] = ui; editor.addListener('selectionchange', function () { ui.setDisabled(editor.queryCommandState('autotypeset') == -1); }); return ui; }; })(); ///import core ///commands 全屏 ///commandsName FullScreen ///commandsTitle 全屏 (function () { var utils = baidu.editor.utils, uiUtils = baidu.editor.ui.uiUtils, UIBase = baidu.editor.ui.UIBase, domUtils = baidu.editor.dom.domUtils; var nodeStack = []; function EditorUI(options) { this.initOptions(options); this.initEditorUI(); } EditorUI.prototype = { uiName:'editor', initEditorUI:function () { this.editor.ui = this; this._dialogs = {}; this.initUIBase(); this._initToolbars(); var editor = this.editor, me = this; editor.addListener('ready', function () { //提供getDialog方法 editor.getDialog = function (name) { return editor.ui._dialogs[name + "Dialog"]; }; domUtils.on(editor.window, 'scroll', function (evt) { baidu.editor.ui.Popup.postHide(evt); }); //提供编辑器实时宽高(全屏时宽高不变化) editor.ui._actualFrameWidth = editor.options.initialFrameWidth; //display bottom-bar label based on config if (editor.options.elementPathEnabled) { editor.ui.getDom('elementpath').innerHTML = '<div class="edui-editor-breadcrumb">' + editor.getLang("elementPathTip") + ':</div>'; } if (editor.options.wordCount) { function countFn() { setCount(editor,me); domUtils.un(editor.document, "click", arguments.callee); } domUtils.on(editor.document, "click", countFn); editor.ui.getDom('wordcount').innerHTML = editor.getLang("wordCountTip"); } editor.ui._scale(); if (editor.options.scaleEnabled) { if (editor.autoHeightEnabled) { editor.disableAutoHeight(); } me.enableScale(); } else { me.disableScale(); } if (!editor.options.elementPathEnabled && !editor.options.wordCount && !editor.options.scaleEnabled) { editor.ui.getDom('elementpath').style.display = "none"; editor.ui.getDom('wordcount').style.display = "none"; editor.ui.getDom('scale').style.display = "none"; } if (!editor.selection.isFocus())return; editor.fireEvent('selectionchange', false, true); }); editor.addListener('mousedown', function (t, evt) { var el = evt.target || evt.srcElement; baidu.editor.ui.Popup.postHide(evt, el); baidu.editor.ui.ShortCutMenu.postHide(evt); }); editor.addListener("delcells", function () { if (UE.ui['edittip']) { new UE.ui['edittip'](editor); } editor.getDialog('edittip').open(); }); var pastePop, isPaste = false, timer; editor.addListener("afterpaste", function () { if(editor.queryCommandState('pasteplain')) return; if(baidu.editor.ui.PastePicker){ pastePop = new baidu.editor.ui.Popup({ content:new baidu.editor.ui.PastePicker({editor:editor}), editor:editor, className:'edui-wordpastepop' }); pastePop.render(); } isPaste = true; }); editor.addListener("afterinserthtml", function () { clearTimeout(timer); timer = setTimeout(function () { if (pastePop && (isPaste || editor.ui._isTransfer)) { if(pastePop.isHidden()){ var span = domUtils.createElement(editor.document, 'span', { 'style':"line-height:0px;", 'innerHTML':'\ufeff' }), range = editor.selection.getRange(); range.insertNode(span); var tmp= getDomNode(span, 'firstChild', 'previousSibling'); pastePop.showAnchor(tmp.nodeType == 3 ? tmp.parentNode : tmp); domUtils.remove(span); }else{ pastePop.show(); } delete editor.ui._isTransfer; isPaste = false; } }, 200) }); editor.addListener('contextmenu', function (t, evt) { baidu.editor.ui.Popup.postHide(evt); }); editor.addListener('keydown', function (t, evt) { if (pastePop) pastePop.dispose(evt); var keyCode = evt.keyCode || evt.which; if(evt.altKey&&keyCode==90){ UE.ui.buttons['fullscreen'].onclick(); } }); editor.addListener('wordcount', function (type) { setCount(this,me); }); function setCount(editor,ui) { editor.setOpt({ wordCount:true, maximumWords:10000, wordCountMsg:editor.options.wordCountMsg || editor.getLang("wordCountMsg"), wordOverFlowMsg:editor.options.wordOverFlowMsg || editor.getLang("wordOverFlowMsg") }); var opt = editor.options, max = opt.maximumWords, msg = opt.wordCountMsg , errMsg = opt.wordOverFlowMsg, countDom = ui.getDom('wordcount'); if (!opt.wordCount) { return; } var count = editor.getContentLength(true); if (count > max) { countDom.innerHTML = errMsg; editor.fireEvent("wordcountoverflow"); } else { countDom.innerHTML = msg.replace("{#leave}", max - count).replace("{#count}", count); } } editor.addListener('selectionchange', function () { if (editor.options.elementPathEnabled) { me[(editor.queryCommandState('elementpath') == -1 ? 'dis' : 'en') + 'ableElementPath']() } if (editor.options.scaleEnabled) { me[(editor.queryCommandState('scale') == -1 ? 'dis' : 'en') + 'ableScale'](); } }); var popup = new baidu.editor.ui.Popup({ editor:editor, content:'', className:'edui-bubble', _onEditButtonClick:function () { this.hide(); editor.ui._dialogs.linkDialog.open(); }, _onImgEditButtonClick:function (name) { this.hide(); editor.ui._dialogs[name] && editor.ui._dialogs[name].open(); }, _onImgSetFloat:function (value) { this.hide(); editor.execCommand("imagefloat", value); }, _setIframeAlign:function (value) { var frame = popup.anchorEl; var newFrame = frame.cloneNode(true); switch (value) { case -2: newFrame.setAttribute("align", ""); break; case -1: newFrame.setAttribute("align", "left"); break; case 1: newFrame.setAttribute("align", "right"); break; } frame.parentNode.insertBefore(newFrame, frame); domUtils.remove(frame); popup.anchorEl = newFrame; popup.showAnchor(popup.anchorEl); }, _updateIframe:function () { editor._iframe = popup.anchorEl; editor.ui._dialogs.insertframeDialog.open(); popup.hide(); }, _onRemoveButtonClick:function (cmdName) { editor.execCommand(cmdName); this.hide(); }, queryAutoHide:function (el) { if (el && el.ownerDocument == editor.document) { if (el.tagName.toLowerCase() == 'img' || domUtils.findParentByTagName(el, 'a', true)) { return el !== popup.anchorEl; } } return baidu.editor.ui.Popup.prototype.queryAutoHide.call(this, el); } }); popup.render(); if (editor.options.imagePopup) { editor.addListener('mouseover', function (t, evt) { evt = evt || window.event; var el = evt.target || evt.srcElement; if (editor.ui._dialogs.insertframeDialog && /iframe/ig.test(el.tagName)) { var html = popup.formatHtml( '<nobr>' + editor.getLang("property") + ': <span onclick=$$._setIframeAlign(-2) class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(-1) class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;<span onclick=$$._setIframeAlign(1) class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' + ' <span onclick="$$._updateIframe( this);" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>'); if (html) { popup.getDom('content').innerHTML = html; popup.anchorEl = el; popup.showAnchor(popup.anchorEl); } else { popup.hide(); } } }); editor.addListener('selectionchange', function (t, causeByUi) { if (!causeByUi) return; var html = '', str = "", img = editor.selection.getRange().getClosedNode(), dialogs = editor.ui._dialogs; if (img && img.tagName == 'IMG') { var dialogName = 'insertimageDialog'; if (img.className.indexOf("edui-faked-video") != -1) { dialogName = "insertvideoDialog" } if (img.className.indexOf("edui-faked-webapp") != -1) { dialogName = "webappDialog" } if (img.src.indexOf("http://api.map.baidu.com") != -1) { dialogName = "mapDialog" } if (img.className.indexOf("edui-faked-music") != -1) { dialogName = "musicDialog" } if (img.src.indexOf("http://maps.google.com/maps/api/staticmap") != -1) { dialogName = "gmapDialog" } if (img.getAttribute("anchorname")) { dialogName = "anchorDialog"; html = popup.formatHtml( '<nobr>' + editor.getLang("property") + ': <span onclick=$$._onImgEditButtonClick("anchorDialog") class="edui-clickable">' + editor.getLang("modify") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onRemoveButtonClick(\'anchor\') class="edui-clickable">' + editor.getLang("delete") + '</span></nobr>'); } if (img.getAttribute("word_img")) { //todo 放到dialog去做查询 editor.word_img = [img.getAttribute("word_img")]; dialogName = "wordimageDialog" } if (!dialogs[dialogName]) { return; } str = '<nobr>' + editor.getLang("property") + ': '+ '<span onclick=$$._onImgSetFloat("none") class="edui-clickable">' + editor.getLang("default") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("left") class="edui-clickable">' + editor.getLang("justifyleft") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("right") class="edui-clickable">' + editor.getLang("justifyright") + '</span>&nbsp;&nbsp;' + '<span onclick=$$._onImgSetFloat("center") class="edui-clickable">' + editor.getLang("justifycenter") + '</span>&nbsp;&nbsp;'+ '<span onclick="$$._onImgEditButtonClick(\'' + dialogName + '\');" class="edui-clickable">' + editor.getLang("modify") + '</span></nobr>'; !html && (html = popup.formatHtml(str)) } if (editor.ui._dialogs.linkDialog) { var link = editor.queryCommandValue('link'); var url; if (link && (url = (link.getAttribute('_href') || link.getAttribute('href', 2)))) { var txt = url; if (url.length > 30) { txt = url.substring(0, 20) + "..."; } if (html) { html += '<div style="height:5px;"></div>' } html += popup.formatHtml( '<nobr>' + editor.getLang("anthorMsg") + ': <a target="_blank" href="' + url + '" title="' + url + '" >' + txt + '</a>' + ' <span class="edui-clickable" onclick="$$._onEditButtonClick();">' + editor.getLang("modify") + '</span>' + ' <span class="edui-clickable" onclick="$$._onRemoveButtonClick(\'unlink\');"> ' + editor.getLang("clear") + '</span></nobr>'); popup.showAnchor(link); } } if (html) { popup.getDom('content').innerHTML = html; popup.anchorEl = img || link; popup.showAnchor(popup.anchorEl); } else { popup.hide(); } }); } }, _initToolbars:function () { var editor = this.editor; var toolbars = this.toolbars || []; var toolbarUis = []; for (var i = 0; i < toolbars.length; i++) { var toolbar = toolbars[i]; var toolbarUi = new baidu.editor.ui.Toolbar({theme:editor.options.theme}); for (var j = 0; j < toolbar.length; j++) { var toolbarItem = toolbar[j]; var toolbarItemUi = null; if (typeof toolbarItem == 'string') { toolbarItem = toolbarItem.toLowerCase(); if (toolbarItem == '|') { toolbarItem = 'Separator'; } if(toolbarItem == '||'){ toolbarItem = 'Breakline'; } if (baidu.editor.ui[toolbarItem]) { toolbarItemUi = new baidu.editor.ui[toolbarItem](editor); } //fullscreen这里单独处理一下,放到首行去 if (toolbarItem == 'fullscreen') { if (toolbarUis && toolbarUis[0]) { toolbarUis[0].items.splice(0, 0, toolbarItemUi); } else { toolbarItemUi && toolbarUi.items.splice(0, 0, toolbarItemUi); } continue; } } else { toolbarItemUi = toolbarItem; } if (toolbarItemUi && toolbarItemUi.id) { toolbarUi.add(toolbarItemUi); } } toolbarUis[i] = toolbarUi; } this.toolbars = toolbarUis; }, getHtmlTpl:function () { return '<div id="##" class="%%">' + '<div id="##_toolbarbox" class="%%-toolbarbox">' + (this.toolbars.length ? '<div id="##_toolbarboxouter" class="%%-toolbarboxouter"><div class="%%-toolbarboxinner">' + this.renderToolbarBoxHtml() + '</div></div>' : '') + '<div id="##_toolbarmsg" class="%%-toolbarmsg" style="display:none;">' + '<div id = "##_upload_dialog" class="%%-toolbarmsg-upload" onclick="$$.showWordImageDialog();">' + this.editor.getLang("clickToUpload") + '</div>' + '<div class="%%-toolbarmsg-close" onclick="$$.hideToolbarMsg();">x</div>' + '<div id="##_toolbarmsg_label" class="%%-toolbarmsg-label"></div>' + '<div style="height:0;overflow:hidden;clear:both;"></div>' + '</div>' + '</div>' + '<div id="##_iframeholder" class="%%-iframeholder"></div>' + //modify wdcount by matao '<div id="##_bottombar" class="%%-bottomContainer"><table><tr>' + '<td id="##_elementpath" class="%%-bottombar"></td>' + '<td id="##_wordcount" class="%%-wordcount"></td>' + '<td id="##_scale" class="%%-scale"><div class="%%-icon"></div></td>' + '</tr></table></div>' + '<div id="##_scalelayer"></div>' + '</div>'; }, showWordImageDialog:function () { this.editor.execCommand("wordimage", "word_img"); this._dialogs['wordimageDialog'].open(); }, renderToolbarBoxHtml:function () { var buff = []; for (var i = 0; i < this.toolbars.length; i++) { buff.push(this.toolbars[i].renderHtml()); } return buff.join(''); }, setFullScreen:function (fullscreen) { var editor = this.editor, container = editor.container.parentNode.parentNode; if (this._fullscreen != fullscreen) { this._fullscreen = fullscreen; this.editor.fireEvent('beforefullscreenchange', fullscreen); if (baidu.editor.browser.gecko) { var bk = editor.selection.getRange().createBookmark(); } if (fullscreen) { while (container.tagName != "BODY") { var position = baidu.editor.dom.domUtils.getComputedStyle(container, "position"); nodeStack.push(position); container.style.position = "static"; container = container.parentNode; } this._bakHtmlOverflow = document.documentElement.style.overflow; this._bakBodyOverflow = document.body.style.overflow; this._bakAutoHeight = this.editor.autoHeightEnabled; this._bakScrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop); this._bakEditorContaninerWidth = editor.iframe.parentNode.offsetWidth; if (this._bakAutoHeight) { //当全屏时不能执行自动长高 editor.autoHeightEnabled = false; this.editor.disableAutoHeight(); } document.documentElement.style.overflow = 'hidden'; document.body.style.overflow = 'hidden'; this._bakCssText = this.getDom().style.cssText; this._bakCssText1 = this.getDom('iframeholder').style.cssText; editor.iframe.parentNode.style.width = ''; this._updateFullScreen(); } else { while (container.tagName != "BODY") { container.style.position = nodeStack.shift(); container = container.parentNode; } this.getDom().style.cssText = this._bakCssText; this.getDom('iframeholder').style.cssText = this._bakCssText1; if (this._bakAutoHeight) { editor.autoHeightEnabled = true; this.editor.enableAutoHeight(); } document.documentElement.style.overflow = this._bakHtmlOverflow; document.body.style.overflow = this._bakBodyOverflow; editor.iframe.parentNode.style.width = this._bakEditorContaninerWidth + 'px'; window.scrollTo(0, this._bakScrollTop); } if (browser.gecko && editor.body.contentEditable === 'true') { var input = document.createElement('input'); document.body.appendChild(input); editor.body.contentEditable = false; setTimeout(function () { input.focus(); setTimeout(function () { editor.body.contentEditable = true; editor.fireEvent('fullscreenchanged', fullscreen); editor.selection.getRange().moveToBookmark(bk).select(true); baidu.editor.dom.domUtils.remove(input); fullscreen && window.scroll(0, 0); }, 0) }, 0) } if(editor.body.contentEditable === 'true'){ this.editor.fireEvent('fullscreenchanged', fullscreen); this.triggerLayout(); } } }, _updateFullScreen:function () { if (this._fullscreen) { var vpRect = uiUtils.getViewportRect(); this.getDom().style.cssText = 'border:0;position:absolute;left:0;top:' + (this.editor.options.topOffset || 0) + 'px;width:' + vpRect.width + 'px;height:' + vpRect.height + 'px;z-index:' + (this.getDom().style.zIndex * 1 + 100); uiUtils.setViewportOffset(this.getDom(), { left:0, top:this.editor.options.topOffset || 0 }); this.editor.setHeight(vpRect.height - this.getDom('toolbarbox').offsetHeight - this.getDom('bottombar').offsetHeight - (this.editor.options.topOffset || 0)); //不手动调一下,会导致全屏失效 if(browser.gecko){ try{ window.onresize(); }catch(e){ } } } }, _updateElementPath:function () { var bottom = this.getDom('elementpath'), list; if (this.elementPathEnabled && (list = this.editor.queryCommandValue('elementpath'))) { var buff = []; for (var i = 0, ci; ci = list[i]; i++) { buff[i] = this.formatHtml('<span unselectable="on" onclick="$$.editor.execCommand(&quot;elementpath&quot;, &quot;' + i + '&quot;);">' + ci + '</span>'); } bottom.innerHTML = '<div class="edui-editor-breadcrumb" onmousedown="return false;">' + this.editor.getLang("elementPathTip") + ': ' + buff.join(' &gt; ') + '</div>'; } else { bottom.style.display = 'none' } }, disableElementPath:function () { var bottom = this.getDom('elementpath'); bottom.innerHTML = ''; bottom.style.display = 'none'; this.elementPathEnabled = false; }, enableElementPath:function () { var bottom = this.getDom('elementpath'); bottom.style.display = ''; this.elementPathEnabled = true; this._updateElementPath(); }, _scale:function () { var doc = document, editor = this.editor, editorHolder = editor.container, editorDocument = editor.document, toolbarBox = this.getDom("toolbarbox"), bottombar = this.getDom("bottombar"), scale = this.getDom("scale"), scalelayer = this.getDom("scalelayer"); var isMouseMove = false, position = null, minEditorHeight = 0, minEditorWidth = editor.options.minFrameWidth, pageX = 0, pageY = 0, scaleWidth = 0, scaleHeight = 0; function down() { position = domUtils.getXY(editorHolder); if (!minEditorHeight) { minEditorHeight = editor.options.minFrameHeight + toolbarBox.offsetHeight + bottombar.offsetHeight; } scalelayer.style.cssText = "position:absolute;left:0;display:;top:0;background-color:#41ABFF;opacity:0.4;filter: Alpha(opacity=40);width:" + editorHolder.offsetWidth + "px;height:" + editorHolder.offsetHeight + "px;z-index:" + (editor.options.zIndex + 1); domUtils.on(doc, "mousemove", move); domUtils.on(editorDocument, "mouseup", up); domUtils.on(doc, "mouseup", up); } var me = this; //by xuheng 全屏时关掉缩放 this.editor.addListener('fullscreenchanged', function (e, fullScreen) { if (fullScreen) { me.disableScale(); } else { if (me.editor.options.scaleEnabled) { me.enableScale(); var tmpNode = me.editor.document.createElement('span'); me.editor.body.appendChild(tmpNode); me.editor.body.style.height = Math.max(domUtils.getXY(tmpNode).y, me.editor.iframe.offsetHeight - 20) + 'px'; domUtils.remove(tmpNode) } } }); function move(event) { clearSelection(); var e = event || window.event; pageX = e.pageX || (doc.documentElement.scrollLeft + e.clientX); pageY = e.pageY || (doc.documentElement.scrollTop + e.clientY); scaleWidth = pageX - position.x; scaleHeight = pageY - position.y; if (scaleWidth >= minEditorWidth) { isMouseMove = true; scalelayer.style.width = scaleWidth + 'px'; } if (scaleHeight >= minEditorHeight) { isMouseMove = true; scalelayer.style.height = scaleHeight + "px"; } } function up() { if (isMouseMove) { isMouseMove = false; editor.ui._actualFrameWidth = scalelayer.offsetWidth - 2; editorHolder.style.width = editor.ui._actualFrameWidth + 'px'; editor.setHeight(scalelayer.offsetHeight - bottombar.offsetHeight - toolbarBox.offsetHeight - 2); } if (scalelayer) { scalelayer.style.display = "none"; } clearSelection(); domUtils.un(doc, "mousemove", move); domUtils.un(editorDocument, "mouseup", up); domUtils.un(doc, "mouseup", up); } function clearSelection() { if (browser.ie) doc.selection.clear(); else window.getSelection().removeAllRanges(); } this.enableScale = function () { //trace:2868 if (editor.queryCommandState("source") == 1) return; scale.style.display = ""; this.scaleEnabled = true; domUtils.on(scale, "mousedown", down); }; this.disableScale = function () { scale.style.display = "none"; this.scaleEnabled = false; domUtils.un(scale, "mousedown", down); }; }, isFullScreen:function () { return this._fullscreen; }, postRender:function () { UIBase.prototype.postRender.call(this); for (var i = 0; i < this.toolbars.length; i++) { this.toolbars[i].postRender(); } var me = this; var timerId, domUtils = baidu.editor.dom.domUtils, updateFullScreenTime = function () { clearTimeout(timerId); timerId = setTimeout(function () { me._updateFullScreen(); }); }; domUtils.on(window, 'resize', updateFullScreenTime); me.addListener('destroy', function () { domUtils.un(window, 'resize', updateFullScreenTime); clearTimeout(timerId); }) }, showToolbarMsg:function (msg, flag) { this.getDom('toolbarmsg_label').innerHTML = msg; this.getDom('toolbarmsg').style.display = ''; // if (!flag) { var w = this.getDom('upload_dialog'); w.style.display = 'none'; } }, hideToolbarMsg:function () { this.getDom('toolbarmsg').style.display = 'none'; }, mapUrl:function (url) { return url ? url.replace('~/', this.editor.options.UEDITOR_HOME_URL || '') : '' }, triggerLayout:function () { var dom = this.getDom(); if (dom.style.zoom == '1') { dom.style.zoom = '100%'; } else { dom.style.zoom = '1'; } } }; utils.inherits(EditorUI, baidu.editor.ui.UIBase); var instances = {}; UE.ui.Editor = function (options) { var editor = new UE.Editor(options); editor.options.editor = editor; utils.loadFile(document, { href:editor.options.themePath + editor.options.theme + "/css/ueditor.css", tag:"link", type:"text/css", rel:"stylesheet" }); var oldRender = editor.render; editor.render = function (holder) { if (holder.constructor === String) { editor.key = holder; instances[holder] = editor; } utils.domReady(function () { editor.langIsReady ? renderUI() : editor.addListener("langReady", renderUI); function renderUI() { editor.setOpt({ labelMap:editor.options.labelMap || editor.getLang('labelMap') }); new EditorUI(editor.options); if (holder) { if (holder.constructor === String) { holder = document.getElementById(holder); } holder && holder.getAttribute('name') && ( editor.options.textarea = holder.getAttribute('name')); if (holder && /script|textarea/ig.test(holder.tagName)) { var newDiv = document.createElement('div'); holder.parentNode.insertBefore(newDiv, holder); var cont = holder.value || holder.innerHTML; editor.options.initialContent = /^[\t\r\n ]*$/.test(cont) ? editor.options.initialContent : cont.replace(/>[\n\r\t]+([ ]{4})+/g, '>') .replace(/[\n\r\t]+([ ]{4})+</g, '<') .replace(/>[\n\r\t]+</g, '><'); holder.className && (newDiv.className = holder.className); holder.style.cssText && (newDiv.style.cssText = holder.style.cssText); if (/textarea/i.test(holder.tagName)) { editor.textarea = holder; editor.textarea.style.display = 'none'; } else { holder.parentNode.removeChild(holder); holder.id && (newDiv.id = holder.id); } holder = newDiv; holder.innerHTML = ''; } } domUtils.addClass(holder, "edui-" + editor.options.theme); editor.ui.render(holder); var opt = editor.options; //给实例添加一个编辑器的容器引用 editor.container = editor.ui.getDom(); var parents = domUtils.findParents(holder,true); var displays = []; for(var i = 0 ,ci;ci=parents[i];i++){ displays[i] = ci.style.display; ci.style.display = 'block' } if (opt.initialFrameWidth) { opt.minFrameWidth = opt.initialFrameWidth; } else { opt.minFrameWidth = opt.initialFrameWidth = holder.offsetWidth; } if (opt.initialFrameHeight) { opt.minFrameHeight = opt.initialFrameHeight; } else { opt.initialFrameHeight = opt.minFrameHeight = holder.offsetHeight; } for(var i = 0 ,ci;ci=parents[i];i++){ ci.style.display = displays[i] } //编辑器最外容器设置了高度,会导致,编辑器不占位 //todo 先去掉,没有找到原因 if(holder.style.height){ holder.style.height = '' } editor.container.style.width = opt.initialFrameWidth + (/%$/.test(opt.initialFrameWidth) ? '' : 'px'); editor.container.style.zIndex = opt.zIndex; oldRender.call(editor, editor.ui.getDom('iframeholder')); } }) }; return editor; }; /** * @file * @name UE * @short UE * @desc UEditor的顶部命名空间 */ /** * @name getEditor * @since 1.2.4+ * @grammar UE.getEditor(id,[opt]) => Editor实例 * @desc 提供一个全局的方法得到编辑器实例 * * * ''id'' 放置编辑器的容器id, 如果容器下的编辑器已经存在,就直接返回 * * ''opt'' 编辑器的可选参数 * @example * UE.getEditor('containerId',{onready:function(){//创建一个编辑器实例 * this.setContent('hello') * }}); * UE.getEditor('containerId'); //返回刚创建的实例 * */ UE.getEditor = function (id, opt) { var editor = instances[id]; if (!editor) { editor = instances[id] = new UE.ui.Editor(opt); editor.render(id); } return editor; }; UE.delEditor = function (id) { var editor; if (editor = instances[id]) { editor.key && editor.destroy(); delete instances[id] } } })();///import core ///import uicore ///commands 表情 (function(){ var utils = baidu.editor.utils, Popup = baidu.editor.ui.Popup, SplitButton = baidu.editor.ui.SplitButton, MultiMenuPop = baidu.editor.ui.MultiMenuPop = function(options){ this.initOptions(options); this.initMultiMenu(); }; MultiMenuPop.prototype = { initMultiMenu: function (){ var me = this; this.popup = new Popup({ content: '', editor : me.editor, iframe_rendered: false, onshow: function (){ if (!this.iframe_rendered) { this.iframe_rendered = true; this.getDom('content').innerHTML = '<iframe id="'+me.id+'_iframe" src="'+ me.iframeUrl +'" frameborder="0"></iframe>'; me.editor.container.style.zIndex && (this.getDom().style.zIndex = me.editor.container.style.zIndex * 1 + 1); } } // canSideUp:false, // canSideLeft:false }); this.onbuttonclick = function(){ this.showPopup(); }; this.initSplitButton(); } }; utils.inherits(MultiMenuPop, SplitButton); })(); (function () { var UI = baidu.editor.ui, UIBase = UI.UIBase, uiUtils = UI.uiUtils, utils = baidu.editor.utils, domUtils = baidu.editor.dom.domUtils; var allMenus = [],//存储所有快捷菜单 timeID, isSubMenuShow = false;//是否有子pop显示 var ShortCutMenu = UI.ShortCutMenu = function (options) { this.initOptions (options); this.initShortCutMenu (); }; ShortCutMenu.postHide = hideAllMenu; ShortCutMenu.prototype = { isHidden : true , SPACE : 5 , initShortCutMenu : function () { this.items = this.items || []; this.initUIBase (); this.initItems (); this.initEvent (); allMenus.push (this); } , initEvent : function () { var me = this, doc = me.editor.document; domUtils.on (doc , "mousemove" , function (e) { if (me.isHidden === false) { //有pop显示就不隐藏快捷菜单 if (me.getSubMenuMark () || me.eventType == "contextmenu") return; var flag = true, el = me.getDom (), wt = el.offsetWidth, ht = el.offsetHeight, distanceX = wt / 2 + me.SPACE,//距离中心X标准 distanceY = ht / 2,//距离中心Y标准 x = Math.abs (e.screenX - me.left),//离中心距离横坐标 y = Math.abs (e.screenY - me.top);//离中心距离纵坐标 clearTimeout (timeID); timeID = setTimeout (function () { if (y > 0 && y < distanceY) { me.setOpacity (el , "1"); } else if (y > distanceY && y < distanceY + 70) { me.setOpacity (el , "0.5"); flag = false; } else if (y > distanceY + 70 && y < distanceY + 140) { me.hide (); } if (flag && x > 0 && x < distanceX) { me.setOpacity (el , "1") } else if (x > distanceX && x < distanceX + 70) { me.setOpacity (el , "0.5") } else if (x > distanceX + 70 && x < distanceX + 140) { me.hide (); } }); } }); //ie\ff下 mouseout不准 if (browser.chrome) { domUtils.on (doc , "mouseout" , function (e) { var relatedTgt = e.relatedTarget || e.toElement; if (relatedTgt == null || relatedTgt.tagName == "HTML") { me.hide (); } }); } me.editor.addListener ("afterhidepop" , function () { if (!me.isHidden) { isSubMenuShow = true; } }); } , initItems : function () { if (utils.isArray (this.items)) { for (var i = 0, len = this.items.length ; i < len ; i++) { var item = this.items[i].toLowerCase (); if (UI[item]) { this.items[i] = new UI[item] (this.editor); this.items[i].className += " edui-shortcutsubmenu "; } } } } , setOpacity : function (el , value) { if (browser.ie && browser.version < 9) { el.style.filter = "alpha(opacity = " + parseFloat (value) * 100 + ");" } else { el.style.opacity = value; } } , getSubMenuMark : function () { isSubMenuShow = false; var layerEle = uiUtils.getFixedLayer (); var list = domUtils.getElementsByTagName (layerEle , "div" , function (node) { return domUtils.hasClass (node , "edui-shortcutsubmenu edui-popup") }); for (var i = 0, node ; node = list[i++] ;) { if (node.style.display != "none") { isSubMenuShow = true; } } return isSubMenuShow; } , show : function (e , hasContextmenu) { var me = this, offset = {}, el = this.getDom (), fixedlayer = uiUtils.getFixedLayer (); function setPos (offset) { if (offset.left < 0) { offset.left = 0; } if (offset.top < 0) { offset.top = 0; } el.style.cssText = "position:absolute;left:" + offset.left + "px;top:" + offset.top + "px;"; } function setPosByCxtMenu (menu) { if (!menu.tagName) { menu = menu.getDom (); } offset.left = parseInt (menu.style.left); offset.top = parseInt (menu.style.top); offset.top -= el.offsetHeight + 15; setPos (offset); } me.eventType = e.type; el.style.cssText = "display:block;left:-9999px"; if (e.type == "contextmenu" && hasContextmenu) { var menu = domUtils.getElementsByTagName (fixedlayer , "div" , "edui-contextmenu")[0]; if (menu) { setPosByCxtMenu (menu) } else { me.editor.addListener ("aftershowcontextmenu" , function (type , menu) { setPosByCxtMenu (menu); }); } } else { offset = uiUtils.getViewportOffsetByEvent (e); offset.top -= el.offsetHeight + me.SPACE; offset.left += me.SPACE + 20; setPos (offset); me.setOpacity (el , 0.2); } me.isHidden = false; me.left = e.screenX + el.offsetWidth / 2 - me.SPACE; me.top = e.screenY - (el.offsetHeight / 2) - me.SPACE; if (me.editor) { el.style.zIndex = me.editor.container.style.zIndex * 1 + 10; fixedlayer.style.zIndex = el.style.zIndex - 1; } } , hide : function () { if (this.getDom ()) { this.getDom ().style.display = "none"; } this.isHidden = true; } , postRender : function () { if (utils.isArray (this.items)) { for (var i = 0, item ; item = this.items[i++] ;) { item.postRender (); } } } , getHtmlTpl : function () { var buff; if (utils.isArray (this.items)) { buff = []; for (var i = 0 ; i < this.items.length ; i++) { buff[i] = this.items[i].renderHtml (); } buff = buff.join (""); } else { buff = this.items; } return '<div id="##" class="%% edui-toolbar" data-src="shortcutmenu" onmousedown="return false;" onselectstart="return false;" >' + buff + '</div>'; } }; utils.inherits (ShortCutMenu , UIBase); function hideAllMenu (e) { var tgt = e.target || e.srcElement, cur = domUtils.findParent (tgt , function (node) { return domUtils.hasClass (node , "edui-shortcutmenu") || domUtils.hasClass (node , "edui-popup"); } , true); if (!cur) { for (var i = 0, menu ; menu = allMenus[i++] ;) { menu.hide () } } } domUtils.on (document , 'mousedown' , function (e) { hideAllMenu (e); }); domUtils.on (window , 'scroll' , function (e) { hideAllMenu (e); }); }) (); (function (){ var utils = baidu.editor.utils, UIBase = baidu.editor.ui.UIBase, Breakline = baidu.editor.ui.Breakline = function (options){ this.initOptions(options); this.initSeparator(); }; Breakline.prototype = { uiName: 'Breakline', initSeparator: function (){ this.initUIBase(); }, getHtmlTpl: function (){ return '<br/>'; } }; utils.inherits(Breakline, UIBase); })(); })();
{ "content_hash": "1dee92cee172b69b04179517f1546f91", "timestamp": "", "source": "github", "line_count": 14890, "max_line_length": 744, "avg_line_length": 38.26447280053727, "alnum_prop": 0.4411329020391113, "repo_name": "cyrilzhao/qa-ueditor", "id": "673d320cc8f8b169eacc42caa70fcf487f8dc38f", "size": "587616", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "ueditor.all.js", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "45932" }, { "name": "JavaScript", "bytes": "800858" }, { "name": "PHP", "bytes": "24536" } ], "symlink_target": "" }
using System; using Microsoft.Protocols.TestTools.StackSdk; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbNoAndxCommand Request /// </summary> public class SmbNoAndxCommandRequestPacket : SmbSingleRequestPacket { #region Fields // none #endregion #region Properties // none #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbNoAndxCommandRequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbNoAndxCommandRequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbNoAndxCommandRequestPacket(SmbNoAndxCommandRequestPacket packet) : base(packet) { this.InitDefaultValue(); } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbNoAndxCommandRequestPacket(this); } /// <summary> /// encode the SmbParameters /// </summary> protected override void EncodeParameters() { this.smbParametersBlock.WordCount = 0; this.smbParametersBlock.Words = new ushort[0]; } /// <summary> /// decode the SmbData /// </summary> protected override void EncodeData() { this.smbDataBlock.ByteCount = 0; this.smbDataBlock.Bytes = new byte[0]; } /// <summary> /// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters. /// </summary> protected override void DecodeParameters() { } /// <summary> /// to decode the smb data: from the general SmbDada to the concrete Smb Data. /// </summary> protected override void DecodeData() { } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }
{ "content_hash": "e0b8187fe7198d1a77f00e9b22c185bb", "timestamp": "", "source": "github", "line_count": 119, "max_line_length": 105, "avg_line_length": 22.714285714285715, "alnum_prop": 0.5434702182759896, "repo_name": "JessieF/WindowsProtocolTestSuites", "id": "bcc27afe73d788047fcfcb3ad53c7af91c924cef", "size": "2855", "binary": false, "copies": "7", "ref": "refs/heads/master", "path": "ProtoSDK/MS-CIFS/Messages/Com/SmbNoAndxCommandRequestPacket.cs", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "19882" }, { "name": "C#", "bytes": "260589552" }, { "name": "HTML", "bytes": "37511" }, { "name": "PowerShell", "bytes": "73385" } ], "symlink_target": "" }
package org.apache.calcite.rex; import org.apache.calcite.avatica.util.DateTimeUtils; import org.apache.calcite.avatica.util.TimeUnit; import org.apache.calcite.avatica.util.TimeUnitRange; import org.apache.calcite.rel.metadata.NullSentinel; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.util.NlsString; import org.apache.calcite.util.Util; import com.google.common.collect.ImmutableMap; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Comparator; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.function.IntPredicate; /** * Evaluates {@link RexNode} expressions. * * <p>Caveats: * <ul> * <li>It uses interpretation, so it is not very efficient. * <li>It is intended for testing, so does not cover very many functions and * operators. (Feel free to contribute more!) * <li>It is not well tested. * </ul> */ public class RexInterpreter implements RexVisitor<Comparable> { private static final NullSentinel N = NullSentinel.INSTANCE; public static final EnumSet<SqlKind> SUPPORTED_SQL_KIND = EnumSet.of(SqlKind.IS_NOT_DISTINCT_FROM, SqlKind.EQUALS, SqlKind.IS_DISTINCT_FROM, SqlKind.NOT_EQUALS, SqlKind.GREATER_THAN, SqlKind.GREATER_THAN_OR_EQUAL, SqlKind.LESS_THAN, SqlKind.LESS_THAN_OR_EQUAL, SqlKind.AND, SqlKind.OR, SqlKind.NOT, SqlKind.CASE, SqlKind.IS_TRUE, SqlKind.IS_NOT_TRUE, SqlKind.IS_FALSE, SqlKind.IS_NOT_FALSE, SqlKind.PLUS_PREFIX, SqlKind.MINUS_PREFIX, SqlKind.PLUS, SqlKind.MINUS, SqlKind.TIMES, SqlKind.DIVIDE, SqlKind.COALESCE, SqlKind.CEIL, SqlKind.FLOOR, SqlKind.EXTRACT); private final Map<RexNode, Comparable> environment; /** Creates an interpreter. * * @param environment Values of certain expressions (usually * {@link RexInputRef}s) */ private RexInterpreter(Map<RexNode, Comparable> environment) { this.environment = ImmutableMap.copyOf(environment); } /** Evaluates an expression in an environment. */ public static Comparable evaluate(RexNode e, Map<RexNode, Comparable> map) { final Comparable v = e.accept(new RexInterpreter(map)); if (false) { System.out.println("evaluate " + e + " on " + map + " returns " + v); } return v; } private IllegalArgumentException unbound(RexNode e) { return new IllegalArgumentException("unbound: " + e); } private Comparable getOrUnbound(RexNode e) { final Comparable comparable = environment.get(e); if (comparable != null) { return comparable; } throw unbound(e); } public Comparable visitInputRef(RexInputRef inputRef) { return getOrUnbound(inputRef); } public Comparable visitLocalRef(RexLocalRef localRef) { throw unbound(localRef); } public Comparable visitLiteral(RexLiteral literal) { return Util.first(literal.getValue4(), N); } public Comparable visitOver(RexOver over) { throw unbound(over); } public Comparable visitCorrelVariable(RexCorrelVariable correlVariable) { return getOrUnbound(correlVariable); } public Comparable visitDynamicParam(RexDynamicParam dynamicParam) { return getOrUnbound(dynamicParam); } public Comparable visitRangeRef(RexRangeRef rangeRef) { throw unbound(rangeRef); } public Comparable visitFieldAccess(RexFieldAccess fieldAccess) { return getOrUnbound(fieldAccess); } public Comparable visitSubQuery(RexSubQuery subQuery) { throw unbound(subQuery); } public Comparable visitTableInputRef(RexTableInputRef fieldRef) { throw unbound(fieldRef); } public Comparable visitPatternFieldRef(RexPatternFieldRef fieldRef) { throw unbound(fieldRef); } public Comparable visitCall(RexCall call) { final List<Comparable> values = visitList(call.operands); switch (call.getKind()) { case IS_NOT_DISTINCT_FROM: if (containsNull(values)) { return values.get(0).equals(values.get(1)); } // falls through EQUALS case EQUALS: return compare(values, c -> c == 0); case IS_DISTINCT_FROM: if (containsNull(values)) { return !values.get(0).equals(values.get(1)); } // falls through NOT_EQUALS case NOT_EQUALS: return compare(values, c -> c != 0); case GREATER_THAN: return compare(values, c -> c > 0); case GREATER_THAN_OR_EQUAL: return compare(values, c -> c >= 0); case LESS_THAN: return compare(values, c -> c < 0); case LESS_THAN_OR_EQUAL: return compare(values, c -> c <= 0); case AND: return values.stream().map(Truthy::of).min(Comparator.naturalOrder()) .get().toComparable(); case OR: return values.stream().map(Truthy::of).max(Comparator.naturalOrder()) .get().toComparable(); case NOT: return not(values.get(0)); case CASE: return case_(values); case IS_TRUE: return values.get(0).equals(true); case IS_NOT_TRUE: return !values.get(0).equals(true); case IS_NULL: return values.get(0).equals(N); case IS_NOT_NULL: return !values.get(0).equals(N); case IS_FALSE: return values.get(0).equals(false); case IS_NOT_FALSE: return !values.get(0).equals(false); case PLUS_PREFIX: return values.get(0); case MINUS_PREFIX: return containsNull(values) ? N : number(values.get(0)).negate(); case PLUS: return containsNull(values) ? N : number(values.get(0)).add(number(values.get(1))); case MINUS: return containsNull(values) ? N : number(values.get(0)).subtract(number(values.get(1))); case TIMES: return containsNull(values) ? N : number(values.get(0)).multiply(number(values.get(1))); case DIVIDE: return containsNull(values) ? N : number(values.get(0)).divide(number(values.get(1))); case CAST: return cast(call, values); case COALESCE: return coalesce(call, values); case CEIL: case FLOOR: return ceil(call, values); case EXTRACT: return extract(call, values); default: throw unbound(call); } } private Comparable extract(RexCall call, List<Comparable> values) { final Comparable v = values.get(1); if (v == N) { return N; } final TimeUnitRange timeUnitRange = (TimeUnitRange) values.get(0); final int v2; if (v instanceof Long) { // TIMESTAMP v2 = (int) (((Long) v) / TimeUnit.DAY.multiplier.longValue()); } else { // DATE v2 = (Integer) v; } return DateTimeUtils.unixDateExtract(timeUnitRange, v2); } private Comparable coalesce(RexCall call, List<Comparable> values) { for (Comparable value : values) { if (value != N) { return value; } } return N; } private Comparable ceil(RexCall call, List<Comparable> values) { if (values.get(0) == N) { return N; } final Long v = (Long) values.get(0); final TimeUnitRange unit = (TimeUnitRange) values.get(1); switch (unit) { case YEAR: case MONTH: switch (call.getKind()) { case FLOOR: return DateTimeUtils.unixTimestampFloor(unit, v); default: return DateTimeUtils.unixTimestampCeil(unit, v); } } final TimeUnitRange subUnit = subUnit(unit); for (long v2 = v;;) { final int e = DateTimeUtils.unixTimestampExtract(subUnit, v2); if (e == 0) { return v2; } v2 -= unit.startUnit.multiplier.longValue(); } } private TimeUnitRange subUnit(TimeUnitRange unit) { switch (unit) { case QUARTER: return TimeUnitRange.MONTH; default: return TimeUnitRange.DAY; } } private Comparable cast(RexCall call, List<Comparable> values) { if (values.get(0) == N) { return N; } return values.get(0); } private Comparable not(Comparable value) { if (value.equals(true)) { return false; } else if (value.equals(false)) { return true; } else { return N; } } private Comparable case_(List<Comparable> values) { final int size; final Comparable elseValue; if (values.size() % 2 == 0) { size = values.size(); elseValue = N; } else { size = values.size() - 1; elseValue = Util.last(values); } for (int i = 0; i < size; i += 2) { if (values.get(i).equals(true)) { return values.get(i + 1); } } return elseValue; } private BigDecimal number(Comparable comparable) { return comparable instanceof BigDecimal ? (BigDecimal) comparable : comparable instanceof BigInteger ? new BigDecimal((BigInteger) comparable) : comparable instanceof Long || comparable instanceof Integer || comparable instanceof Short ? new BigDecimal(((Number) comparable).longValue()) : new BigDecimal(((Number) comparable).doubleValue()); } private Comparable compare(List<Comparable> values, IntPredicate p) { if (containsNull(values)) { return N; } Comparable v0 = values.get(0); Comparable v1 = values.get(1); if (v0 instanceof Number && v1 instanceof NlsString) { try { v1 = new BigDecimal(((NlsString) v1).getValue()); } catch (NumberFormatException e) { return false; } } if (v1 instanceof Number && v0 instanceof NlsString) { try { v0 = new BigDecimal(((NlsString) v0).getValue()); } catch (NumberFormatException e) { return false; } } if (v0 instanceof Number) { v0 = number(v0); } if (v1 instanceof Number) { v1 = number(v1); } //noinspection unchecked final int c = v0.compareTo(v1); return p.test(c); } private boolean containsNull(List<Comparable> values) { for (Comparable value : values) { if (value == N) { return true; } } return false; } /** An enum that wraps boolean and unknown values and makes them * comparable. */ enum Truthy { // Order is important; AND returns the min, OR returns the max FALSE, UNKNOWN, TRUE; static Truthy of(Comparable c) { return c.equals(true) ? TRUE : c.equals(false) ? FALSE : UNKNOWN; } Comparable toComparable() { switch (this) { case TRUE: return true; case FALSE: return false; case UNKNOWN: return N; default: throw new AssertionError(); } } } }
{ "content_hash": "3d917bd324389c4a208bf2b5818cbde3", "timestamp": "", "source": "github", "line_count": 369, "max_line_length": 88, "avg_line_length": 28.585365853658537, "alnum_prop": 0.6403109594235874, "repo_name": "vlsi/calcite", "id": "11d91ae2764f61098cb739a848995cec0c5fee33", "size": "11345", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "core/src/main/java/org/apache/calcite/rex/RexInterpreter.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "3674" }, { "name": "CSS", "bytes": "36583" }, { "name": "FreeMarker", "bytes": "17870" }, { "name": "HTML", "bytes": "28312" }, { "name": "Java", "bytes": "18311171" }, { "name": "Kotlin", "bytes": "126692" }, { "name": "PigLatin", "bytes": "1419" }, { "name": "Python", "bytes": "1610" }, { "name": "Ruby", "bytes": "1807" }, { "name": "Shell", "bytes": "7078" }, { "name": "TSQL", "bytes": "1761" } ], "symlink_target": "" }
package org.keycloak.saml.processing.core.saml.v2.writers; import org.keycloak.saml.common.constants.JBossSAMLConstants; import org.keycloak.saml.common.exceptions.ProcessingException; import org.keycloak.saml.common.util.StaxUtil; import org.keycloak.saml.common.util.StringUtil; import org.keycloak.dom.saml.v2.assertion.AssertionType; import org.keycloak.dom.saml.v2.assertion.EncryptedAssertionType; import org.keycloak.dom.saml.v2.assertion.NameIDType; import org.keycloak.dom.saml.v2.protocol.ArtifactResponseType; import org.keycloak.dom.saml.v2.protocol.AuthnRequestType; import org.keycloak.dom.saml.v2.protocol.ResponseType; import org.keycloak.dom.saml.v2.protocol.StatusCodeType; import org.keycloak.dom.saml.v2.protocol.StatusDetailType; import org.keycloak.dom.saml.v2.protocol.StatusResponseType; import org.keycloak.dom.saml.v2.protocol.StatusType; import org.keycloak.saml.common.constants.JBossSAMLURIConstants; import org.w3c.dom.Element; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamWriter; import java.net.URI; import java.util.List; /** * Write a SAML Response to stream * * @author [email protected] * @since Nov 2, 2010 */ public class SAMLResponseWriter extends BaseWriter { private final SAMLAssertionWriter assertionWriter; public SAMLResponseWriter(XMLStreamWriter writer) { super(writer); this.assertionWriter = new SAMLAssertionWriter(writer); } /** * Write a {@code ResponseType} to stream * * @param response * @param out * * @throws org.keycloak.saml.common.exceptions.ProcessingException */ public void write(ResponseType response) throws ProcessingException { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.RESPONSE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeNameSpace(writer, PROTOCOL_PREFIX, JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, JBossSAMLURIConstants.ASSERTION_NSURI.get()); writeBaseAttributes(response); NameIDType issuer = response.getIssuer(); if (issuer != null) { write(issuer, new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX)); } Element sig = response.getSignature(); if (sig != null) { StaxUtil.writeDOMElement(writer, sig); } StatusType status = response.getStatus(); write(status); List<ResponseType.RTChoiceType> choiceTypes = response.getAssertions(); if (choiceTypes != null) { for (ResponseType.RTChoiceType choiceType : choiceTypes) { AssertionType assertion = choiceType.getAssertion(); if (assertion != null) { assertionWriter.write(assertion); } EncryptedAssertionType encryptedAssertion = choiceType.getEncryptedAssertion(); if (encryptedAssertion != null) { Element encElement = encryptedAssertion.getEncryptedElement(); StaxUtil.writeDOMElement(writer, encElement); } } } StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } public void write(ArtifactResponseType response) throws ProcessingException { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.ARTIFACT_RESPONSE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeNameSpace(writer, PROTOCOL_PREFIX, JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeNameSpace(writer, ASSERTION_PREFIX, JBossSAMLURIConstants.ASSERTION_NSURI.get()); StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.ASSERTION_NSURI.get()); writeBaseAttributes(response); NameIDType issuer = response.getIssuer(); if (issuer != null) { write(issuer, new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX)); } Element sig = response.getSignature(); if (sig != null) { StaxUtil.writeDOMElement(writer, sig); } StatusType status = response.getStatus(); if (status != null) { write(status); } Object anyObj = response.getAny(); if (anyObj instanceof AuthnRequestType) { AuthnRequestType authn = (AuthnRequestType) anyObj; SAMLRequestWriter requestWriter = new SAMLRequestWriter(writer); requestWriter.write(authn); } else if (anyObj instanceof ResponseType) { ResponseType rt = (ResponseType) anyObj; write(rt); } StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } /** * Write a {@code StatusResponseType} * * @param response * @param qname QName of the starting element * @param out * * @throws ProcessingException */ public void write(StatusResponseType response, QName qname) throws ProcessingException { if (qname == null) { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS_RESPONSE_TYPE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); } else { StaxUtil.writeStartElement(writer, qname.getPrefix(), qname.getLocalPart(), qname.getNamespaceURI()); } StaxUtil.writeNameSpace(writer, PROTOCOL_PREFIX, JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeDefaultNameSpace(writer, JBossSAMLURIConstants.ASSERTION_NSURI.get()); writeBaseAttributes(response); NameIDType issuer = response.getIssuer(); write(issuer, new QName(JBossSAMLURIConstants.ASSERTION_NSURI.get(), JBossSAMLConstants.ISSUER.get(), ASSERTION_PREFIX)); StatusType status = response.getStatus(); write(status); StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } /** * Write a {@code StatusType} to stream * * @param status * @param out * * @throws ProcessingException */ public void write(StatusType status) throws ProcessingException { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StatusCodeType statusCodeType = status.getStatusCode(); write(statusCodeType); String statusMessage = status.getStatusMessage(); if (StringUtil.isNotNull(statusMessage)) { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS_MESSAGE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeEndElement(writer); } StatusDetailType statusDetail = status.getStatusDetail(); if (statusDetail != null) write(statusDetail); StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } /** * Write a {@code StatusCodeType} to stream * * @param statusCodeType * @param out * * @throws ProcessingException */ public void write(StatusCodeType statusCodeType) throws ProcessingException { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS_CODE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); URI value = statusCodeType.getValue(); if (value != null) { StaxUtil.writeAttribute(writer, JBossSAMLConstants.VALUE.get(), value.toASCIIString()); } StatusCodeType subStatusCode = statusCodeType.getStatusCode(); if (subStatusCode != null) write(subStatusCode); StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } /** * Write a {@code StatusDetailType} to stream * * @param statusDetailType * @param out * * @throws ProcessingException */ public void write(StatusDetailType statusDetailType) throws ProcessingException { StaxUtil.writeStartElement(writer, PROTOCOL_PREFIX, JBossSAMLConstants.STATUS_CODE.get(), JBossSAMLURIConstants.PROTOCOL_NSURI.get()); StaxUtil.writeEndElement(writer); StaxUtil.flush(writer); } /** * Write the common attributes for all response types * * @param statusResponse * * @throws ProcessingException */ private void writeBaseAttributes(StatusResponseType statusResponse) throws ProcessingException { // Attributes StaxUtil.writeAttribute(writer, JBossSAMLConstants.ID.get(), statusResponse.getID()); StaxUtil.writeAttribute(writer, JBossSAMLConstants.VERSION.get(), statusResponse.getVersion()); StaxUtil.writeAttribute(writer, JBossSAMLConstants.ISSUE_INSTANT.get(), statusResponse.getIssueInstant().toString()); String destination = statusResponse.getDestination(); if (StringUtil.isNotNull(destination)) StaxUtil.writeAttribute(writer, JBossSAMLConstants.DESTINATION.get(), destination); String consent = statusResponse.getConsent(); if (StringUtil.isNotNull(consent)) StaxUtil.writeAttribute(writer, JBossSAMLConstants.CONSENT.get(), consent); String inResponseTo = statusResponse.getInResponseTo(); if (StringUtil.isNotNull(inResponseTo)) StaxUtil.writeAttribute(writer, JBossSAMLConstants.IN_RESPONSE_TO.get(), inResponseTo); } }
{ "content_hash": "82c1366fbfb0aa602d0ff073cdba7baa", "timestamp": "", "source": "github", "line_count": 248, "max_line_length": 149, "avg_line_length": 38.44758064516129, "alnum_prop": 0.6842160461457787, "repo_name": "eugene-chow/keycloak", "id": "1c4d3a605e5cd27b6540f491864c30fb6c220806", "size": "10200", "binary": false, "copies": "15", "ref": "refs/heads/master", "path": "saml/saml-core/src/main/java/org/keycloak/saml/processing/core/saml/v2/writers/SAMLResponseWriter.java", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "AMPL", "bytes": "164" }, { "name": "ApacheConf", "bytes": "22819" }, { "name": "CSS", "bytes": "343703" }, { "name": "HTML", "bytes": "350588" }, { "name": "Java", "bytes": "8319733" }, { "name": "JavaScript", "bytes": "645026" }, { "name": "Shell", "bytes": "8846" }, { "name": "XSLT", "bytes": "63455" } ], "symlink_target": "" }
using System; using System.IO; namespace DiscUtils.Common { public class CommandLineSwitch { private string[] _shortSwitches; private string _fullSwitch; private string _paramName; private string _description; private bool _isPresent; private string _paramValue; public CommandLineSwitch(string fullSwitch, string paramName, string description) { _shortSwitches = new string[0]; _fullSwitch = fullSwitch; _paramName = paramName; _description = description; } public CommandLineSwitch(string shortSwitch, string fullSwitch, string paramName, string description) { _shortSwitches = new string[] { shortSwitch }; _fullSwitch = fullSwitch; _paramName = paramName; _description = description; } public CommandLineSwitch(string[] shortSwitches, string fullSwitch, string paramName, string description) { _shortSwitches = shortSwitches; _fullSwitch = fullSwitch; _paramName = paramName; _description = description; } public string ParameterName { get { return _paramName; } } public string FullSwitchName { get { return _fullSwitch; } } public virtual string FullDescription { get { return _description; } } public bool IsPresent { get { return _isPresent; } } public string Value { get { return _paramValue; } } internal void WriteDescription(TextWriter writer, string lineTemplate, int perLineDescWidth) { string[] switches; int ignore; switches = BuildSwitchInfo(_shortSwitches, _fullSwitch, _paramName, out ignore); string[] text = Utilities.WordWrap(FullDescription, perLineDescWidth); for (int i = 0; i < Math.Max(switches.Length, text.Length); ++i) { writer.WriteLine(lineTemplate, ((i < switches.Length) ? switches[i] : ""), ((i < text.Length) ? text[i] : "")); } } internal int SwitchDisplayLength { get { int maxLen; BuildSwitchInfo(_shortSwitches, _fullSwitch, _paramName, out maxLen); return maxLen; } } private static string[] BuildSwitchInfo(string[] shortSwitches, string fullSwitch, string param, out int maxLen) { maxLen = 0; string[] result = new string[shortSwitches.Length + 1]; for (int i = 0; i < shortSwitches.Length; ++i) { result[i] = "-" + shortSwitches[i]; if (param != null) { result[i] += " <" + param + ">"; } maxLen = Math.Max(result[i].Length, maxLen); } result[result.Length - 1] = "-" + fullSwitch; if (param != null) { result[result.Length - 1] += " <" + param + ">"; } maxLen = Math.Max(result[result.Length - 1].Length, maxLen); return result; } internal bool Matches(string switchName) { if (switchName == _fullSwitch) { return true; } foreach (string sw in _shortSwitches) { if (sw == switchName) { return true; } } return false; } internal virtual int Process(string[] args, int pos) { _isPresent = true; if (!string.IsNullOrEmpty(_paramName)) { if (pos >= args.Length) { throw new Exception(string.Format("Command-line switch {0} is missing value", _fullSwitch)); } _paramValue = args[pos]; ++pos; } return pos; } } }
{ "content_hash": "5b0f66d9f678eee5e899c8bf4d318db3", "timestamp": "", "source": "github", "line_count": 152, "max_line_length": 127, "avg_line_length": 28.730263157894736, "alnum_prop": 0.4762995191206778, "repo_name": "bplu4t2f/EzIso", "id": "8eb5b7dcfee88d8c448134c1e50eedf0f28f126d", "size": "5510", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "EzIso/discutils/utils/DiscUtils.Common/CommandLineSwitch.cs", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Batchfile", "bytes": "684" }, { "name": "C#", "bytes": "4776499" }, { "name": "PowerShell", "bytes": "22059" } ], "symlink_target": "" }
FactoryBot.define do factory :user do end end
{ "content_hash": "3e24651d555fd0616bbe9651cee0a2eb", "timestamp": "", "source": "github", "line_count": 4, "max_line_length": 20, "avg_line_length": 12.5, "alnum_prop": 0.74, "repo_name": "hiveer/daily_plan", "id": "94432bf9ed0420a552faf4261ae4389e5ac43c75", "size": "120", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "spec/factories/users.rb", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "3279" }, { "name": "CoffeeScript", "bytes": "1999" }, { "name": "HTML", "bytes": "11211" }, { "name": "JavaScript", "bytes": "5273" }, { "name": "Ruby", "bytes": "60607" } ], "symlink_target": "" }
% get root of current file root = fullfile(fileparts(mfilename('fullpath')),'../'); p_generated = genpath([root '/Core']); addpath(p_generated); addpath([root '/IO']); addpath([root '/Data']); addpath([root '/Scripts']); p_generated = genpath([root '/ThirdParty/tetgen1.4.3/bin']); addpath(p_generated); p_generated = genpath([root '/ThirdParty/maslib/bin']); addpath(p_generated); clear p_generated;
{ "content_hash": "81c97ff9b6a3f45fd28b2fd533c3a5bf", "timestamp": "", "source": "github", "line_count": 16, "max_line_length": 60, "avg_line_length": 25.3125, "alnum_prop": 0.6864197530864198, "repo_name": "siavashk/GMM-FEM", "id": "96770015495e84e120342582ab8d07c142dba254", "size": "405", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "Scripts/add_bcpd_paths.m", "mode": "33188", "license": "bsd-2-clause", "language": [ { "name": "C", "bytes": "94" }, { "name": "C++", "bytes": "2046372" }, { "name": "CMake", "bytes": "10558" }, { "name": "Makefile", "bytes": "3869" }, { "name": "Matlab", "bytes": "168332" }, { "name": "Shell", "bytes": "2371" } ], "symlink_target": "" }
<?xml version="1.0" encoding="utf-8"?> <strings xml:lang="ms-my"> <!-- Malay --> <!-- various labels (not author controlled) --> <str name="Figure">Rajah</str> <str name="Table">Jadual</str> <str name="Next topic">Tajuk seterusnya</str> <str name="Previous topic">Tajuk sebelumnya</str> <str name="Parent topic">Tajuk induk</str> <str name="Required cleanup">Pembersihan diperlukan</str> <str name="Draft comment">Komen draf</str> <str name="Option">Opsyen</str> <str name="Description">Deskripsi</str> <str name="Optional">Opsyenal</str> <str name="Required">Diperlukan</str> <str name="Skip visual syntax diagram">Langkau rajah sintaks visual</str> <str name="Read syntax diagram">Baca rajah sintaks</str> <str name="Start of change">Mula perubahan</str> <str name="End of change">Hujung perubahan</str> <str name="Index">Indeks</str> <str name="Special characters">Aksara khas</str> <str name="Numerics">Angka</str> <str name="End notes">Nota akhir</str> <str name="Artwork">Kerja seni</str> <str name="Syntax">Sintaks</str> <str name="Type">Jenis</str> <str name="Value">Nilai</str> <!-- Text that goes before a link to a topic --> <str name="intro-to-topic-link"></str> <!-- peril notice labels --> <str name="Note">Nota</str> <str name="Notes">Nota</str> <str name="Tip">Petua</str> <str name="Fastpath">Laluan pantas</str> <str name="Important">Penting</str> <str name="Attention">Perhatian</str> <str name="Caution">AWAS</str> <str name="Danger">BAHAYA</str> <str name="Remember">Ingat</str> <str name="Warning">Amaran</str> <str name="Restriction">Sekatan</str> <!-- default title text for section level generated sections --> <str name="Contents">Kandungan</str> <str name="Related concepts">Konsep berkaitan</str> <str name="Related tasks">Tugas berkaitan</str> <str name="Related reference">Rujukan berkaitan</str> <str name="Related information">Maklumat berkaitan</str> <str name="Prerequisite">Prasyarat</str> <str name="Prerequisites">Prasyarat</str> <str name="or">atau</str> <str name="figure-number-separator"> </str> <!--Task section labels --> <str name="task_context">Mengenai tugas ini</str> <str name="task_example">Contoh</str> <str name="task_postreq">Apa perlu dilakukan seterusnya</str> <str name="task_prereq">Sebelum anda bermula</str> <str name="task_procedure">Prosedur</str> <str name="task_results">Hasil</str> <str name="Copyright">Hak Cipta</str> <!-- Symbols --> <str name="OpenQuote">"</str> <str name="CloseQuote">"</str> <str name="ColonSymbol">:</str> </strings>
{ "content_hash": "b29bb4bec58fe844bc7b05971883d8b5", "timestamp": "", "source": "github", "line_count": 71, "max_line_length": 73, "avg_line_length": 35.478873239436616, "alnum_prop": 0.7062326319968242, "repo_name": "jelovirt/muuntaja", "id": "0ff9af90b73414618e564d2dd4f24be9bb21f8d7", "size": "2519", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "src/main/xsl/common/strings-ms-my.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "79929" }, { "name": "Java", "bytes": "1615903" }, { "name": "JavaScript", "bytes": "89417" }, { "name": "Scala", "bytes": "122431" }, { "name": "Shell", "bytes": "13911" }, { "name": "XSLT", "bytes": "3101956" } ], "symlink_target": "" }
extern crate clap; extern crate time; extern crate clog; extern crate semver; #[cfg(feature = "color")] extern crate ansi_term; use clap::{App, Arg, ArgGroup, ArgMatches}; use clog::{LinkStyle, Clog}; use clog::fmt::ChangelogFormat; #[macro_use] mod macros; mod error; mod fmt; use error::CliError; pub type CliResult<T> = Result<T, CliError>; const CLOG_CONFIG_FILE: &'static str = ".clog.toml"; fn main() { let styles = LinkStyle::variants(); let matches = App::new("clog") // Pull version from Cargo.toml .version(crate_version!()) .about("a conventional changelog for the rest of us") .args_from_usage("-r, --repository [URL] 'Repository used for generating commit and issue links \ (without the .git, e.g. https://github.com/thoughtram/clog)' -f, --from [HASH] 'e.g. 12a8546' -T, --format [FORMAT] 'The output format, defaults to markdown \ (valid values: markdown, json)' -M, --major 'Increment major version by one (Sets minor and patch to 0)' -g, --git-dir [PATH] 'Local .git directory (defaults to current dir + \'.git\')*' -w, --work-tree [PATH] 'Local working tree of the git project \ (defaults to current dir)*' -m, --minor 'Increment minor version by one (Sets patch to 0)' -p, --patch 'Increment patch version by one' -s, --subtitle [TITLE] 'e.g. \"Crazy Release Title\"' -t, --to [HASH] 'e.g. 8057684 (Defaults to HEAD when omitted)' -o, --outfile [FILE] 'Where to write the changelog (Defaults to stdout when omitted)' -c, --config [FILE] 'The Clog Configuration TOML file to use (Defaults to \ \'.clog.toml\')**' -i, --infile [FILE] 'A changelog to append to, but *NOT* write to (Useful in \ conjunction with --outfile)' --setversion [VER] 'e.g. 1.0.1'") // Because --from-latest-tag can't be used with --from, we add it seperately so we can // specify a .conflicts_with() .arg(Arg::from_usage("-F, --from-latest-tag 'use latest tag as start (instead of --from)'") .conflicts_with("from")) // Because we may want to add more "flavors" at a later date, we can automate the process // of enumerating all possible values with clap .arg(Arg::from_usage("-l, --link-style [STYLE] 'The style of repository link to generate (Defaults to github)'") .possible_values(&styles)) // Because no one should use --changelog and either an --infile or --outfile, we add those // to conflicting lists .arg(Arg::from_usage("-C, --changelog [FILE] 'A previous changelog to prepend new changes to (this is like \ using the same file for both --infile and --outfile and \ should not be used in conjuction with either)'") .conflicts_with("infile") .conflicts_with("outfile")) // Since --setversion shouldn't be used with any of the --major, --minor, or --match, we // set those as exclusions .group(ArgGroup::with_name("setver") .args(&["major", "minor", "patch", "setversion"])) .after_help("\ * If your .git directory is a child of your project directory (most common, such as \ /myproject/.git) AND not in the current working directory (i.e you need to use --work-tree or \ --git-dir) you only need to specify either the --work-tree (i.e. /myproject) OR --git-dir (i.e. \ /myproject/.git), you don't need to use both.\n\n\ ** If using the --config to specify a clog configuration TOML file NOT in the current working \ directory (meaning you need to use --work-tree or --git-dir) AND the TOML file is inside your \ project directory (i.e. /myproject/.clog.toml) you do not need to use --work-tree or --git-dir.") .get_matches(); let start_nsec = time::get_time().nsec; let clog = from_matches(&matches).unwrap_or_else(|e| e.exit()); if let Some(ref file) = clog.outfile { clog.write_changelog_to(file).unwrap_or_else(|e| e.exit()); let end_nsec = time::get_time().nsec; let elapsed_mssec = (end_nsec - start_nsec) / 1000000; println!("changelog written. (took {} ms)", elapsed_mssec); } else { clog.write_changelog().unwrap_or_else(|e| e.exit()); } } /// Creates a `Clog` struct from command line `clap::ArgMatches` /// /// # Example /// /// ```ignore /// # use clog::Clog; /// /// let matches = // clap settings... /// /// let clog = Clog::from_matches(matches).unwrap_or_else(|e| { /// e.exit(); /// }); /// ``` pub fn from_matches(matches: &ArgMatches) -> CliResult<Clog> { debugln!("Creating clog from matches"); let mut clog = if let Some(cfg) = matches.value_of("config") { debugln!("User passed in config file: {:?}", cfg); if matches.is_present("work-dir") && matches.is_present("gitdir") { debugln!("User passed in both\n\tworking dir: {:?}\n\tgit dir: {:?}", matches.value_of("work-dir"), matches.value_of("git-dir")); // use --config --work-tree --git-dir try!(Clog::with_all(matches.value_of("git-dir").unwrap(), matches.value_of("work-dir").unwrap(), cfg)) } else if let Some(dir) = matches.value_of("work-dir") { debugln!("User passed in working dir: {:?}", dir); // use --config --work-tree try!(Clog::with_dir_and_file(dir, cfg)) } else if let Some(dir) = matches.value_of("git-dir") { debugln!("User passed in git dir: {:?}", dir); // use --config --git-dir try!(Clog::with_dir_and_file(dir, cfg)) } else { debugln!("User only passed config"); // use --config only try!(Clog::from_file(cfg)) } } else { debugln!("User didn't pass in a config"); if matches.is_present("git-dir") && matches.is_present("work-dir") { let wdir = matches.value_of("work-dir").unwrap(); let gdir = matches.value_of("git-dir").unwrap(); debugln!("User passed in both\n\tworking dir: {:?}\n\tgit dir: {:?}", wdir, gdir); try!(Clog::with_dirs(gdir, wdir)) } else if let Some(dir) = matches.value_of("git-dir") { debugln!("User passed in git dir: {:?}", dir); try!(Clog::with_dir(dir)) } else if let Some(dir) = matches.value_of("work-dir") { debugln!("User passed in working dir: {:?}", dir); try!(Clog::with_dir(dir)) } else { debugln!("Trying the default config file"); try!(Clog::from_file(CLOG_CONFIG_FILE)) } }; // compute version early, so we can exit on error clog.version = { // less typing later... let (major, minor, patch) = (matches.is_present("major"), matches.is_present("minor"), matches.is_present("patch")); if matches.is_present("setversion") { matches.value_of("setversion").unwrap().to_owned() } else if major || minor || patch { let mut had_v = false; let v_string = clog.get_latest_tag_ver(); let first_char = v_string.chars().nth(0).unwrap_or(' '); let v_slice = if first_char == 'v' || first_char == 'V' { had_v = true; v_string.trim_left_matches(|c| c == 'v' || c == 'V') } else { &v_string[..] }; match semver::Version::parse(v_slice) { Ok(ref mut v) => { // if-else may be quicker, but it's longer mentally, and this isn't slow match (major, minor, patch) { (true,_,_) => { v.major += 1; v.minor = 0; v.patch = 0; } (_,true,_) => { v.minor += 1; v.patch = 0; } (_,_,true) => { v.patch += 1; clog.patch_ver = true; } _ => unreachable!(), } format!("{}{}", if had_v { "v" } else { "" }, v) } Err(e) => { return Err(CliError::Semver(Box::new(e), String::from("Failed to parse version into \ valid SemVer. Ensure the version \ is in the X.Y.Z format."))); } } } else { clog.version } }; if let Some(from) = matches.value_of("from") { clog.from = from.to_owned(); } else if matches.is_present("from-latest-tag") { clog.from = clog.get_latest_tag(); } if let Some(to) = matches.value_of("to") { clog.to = to.to_owned(); } if let Some(repo) = matches.value_of("repository") { clog.repo = repo.to_owned(); } if matches.is_present("link-style") { clog.link_style = value_t!(matches.value_of("link-style"), LinkStyle) .unwrap_or(LinkStyle::Github); } if let Some(subtitle) = matches.value_of("subtitle") { clog.subtitle = subtitle.to_owned(); } if let Some(file) = matches.value_of("outfile") { clog.outfile = Some(file.to_owned()); } if let Some(file) = matches.value_of("infile") { clog.infile = Some(file.to_owned()); } if let Some(file) = matches.value_of("changelog") { clog.infile = Some(file.to_owned()); clog.outfile = Some(file.to_owned()); } if matches.is_present("format") { clog.out_format = value_t_or_exit!(matches.value_of("format"), ChangelogFormat); } debugln!("Returning clog:\n{:?}", clog); Ok(clog) }
{ "content_hash": "23a56068f016c9b5103390cea7c4bf85", "timestamp": "", "source": "github", "line_count": 252, "max_line_length": 124, "avg_line_length": 44.07142857142857, "alnum_prop": 0.48199171618944714, "repo_name": "clog-tool/clog-cli", "id": "67070ba1cad5f38abb5f0ae3342b6315976a0d31", "size": "11119", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "src/main.rs", "mode": "33188", "license": "mit", "language": [ { "name": "Makefile", "bytes": "701" }, { "name": "Rust", "bytes": "15309" }, { "name": "Shell", "bytes": "4469" } ], "symlink_target": "" }
package org.apache.camel.impl.validator; import org.apache.camel.CamelExecutionException; import org.apache.camel.ContextTestSupport; import org.apache.camel.ValidationException; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Test; public class ValidatorXmlSchemaTest extends ContextTestSupport { @Test public void shouldPass() throws Exception { final String body = "<user><name>Jan</name></user>"; MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived(body); template.sendBody("direct:in", body); assertMockEndpointsSatisfied(); } @Test public void shouldThrowException() throws Exception { final String body = "<fail/>"; MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); try { template.sendBody("direct:in", body); fail("Should throw exception"); } catch (CamelExecutionException e) { assertIsInstanceOf(ValidationException.class, e.getCause()); } assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() throws Exception { validator().type("xml").withUri("validator:org/apache/camel/impl/validate.xsd"); from("direct:in").inputTypeWithValidate("xml").to("mock:result"); } }; } }
{ "content_hash": "e035710718d9a566d9e5f63e3fe0b87b", "timestamp": "", "source": "github", "line_count": 54, "max_line_length": 96, "avg_line_length": 29.77777777777778, "alnum_prop": 0.6560945273631841, "repo_name": "ullgren/camel", "id": "de7621ca1ae39dd68f8e91b629787a3cadfef040", "size": "2410", "binary": false, "copies": "5", "ref": "refs/heads/master", "path": "core/camel-core/src/test/java/org/apache/camel/impl/validator/ValidatorXmlSchemaTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Apex", "bytes": "6519" }, { "name": "Batchfile", "bytes": "1518" }, { "name": "CSS", "bytes": "16394" }, { "name": "Elm", "bytes": "10852" }, { "name": "FreeMarker", "bytes": "11410" }, { "name": "Groovy", "bytes": "14490" }, { "name": "HTML", "bytes": "896075" }, { "name": "Java", "bytes": "69929414" }, { "name": "JavaScript", "bytes": "90399" }, { "name": "Makefile", "bytes": "513" }, { "name": "Shell", "bytes": "17108" }, { "name": "Tcl", "bytes": "4974" }, { "name": "Thrift", "bytes": "6979" }, { "name": "XQuery", "bytes": "546" }, { "name": "XSLT", "bytes": "270186" } ], "symlink_target": "" }
myApp.controller('contactDetail', function ($scope, contact) { $scope.contact = contact.data; });
{ "content_hash": "7c739d3e7ebd9481d1f8fccf191a96e4", "timestamp": "", "source": "github", "line_count": 3, "max_line_length": 62, "avg_line_length": 33.333333333333336, "alnum_prop": 0.71, "repo_name": "caio000/project_angular", "id": "361536161fa62c5226d9cd6a751fcf3e981d4904", "size": "100", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "js/controller/contactDetailController.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "159247" }, { "name": "HTML", "bytes": "9031" }, { "name": "JavaScript", "bytes": "9991" }, { "name": "PHP", "bytes": "2552" } ], "symlink_target": "" }
[![Documentation](https://img.shields.io/badge/godoc-reference-blue.svg?style=flat-square)](https://godoc.org/github.com/miekg/coredns) [![Build Status](https://img.shields.io/travis/miekg/coredns.svg?style=flat-square&label=build)](https://travis-ci.org/miekg/coredns) CoreDNS is a DNS server that started as a fork of [Caddy](https://github.com/mholt/caddy/). It has the same model: it chains middleware. In fact it's so similar that CoreDNS is now a server type plugin for Caddy. CoreDNS is the successor to [SkyDNS](https://github.com/skynetservices/skydns). SkyDNS is a thin layer that exposes services in etcd in the DNS. CoreDNS builds on this idea and is a generic DNS server that can talk to multiple backends (etcd, kubernetes, etc.). CoreDNS aims to be a fast and flexible DNS server. The keyword here is *flexible*: with CoreDNS you are able to do what you want with your DNS data. And if not: write some middleware! Currently CoreDNS is able to: * Serve zone data from a file; both DNSSEC (NSEC only) and DNS are supported (*file*). * Retrieve zone data from primaries, i.e., act as a secondary server (AXFR only) (*secondary*). * Sign zone data on-the-fly (*dnssec*). * Load balancing of responses (*loadbalance*). * Allow for zone transfers, i.e., act as a primary server (*file*). * Automatically load zone files from disk (*auto*) * Caching (*cache*). * Health checking endpoint (*health*). * Use etcd as a backend, i.e., a 101.5% replacement for [SkyDNS](https://github.com/skynetservices/skydns) (*etcd*). * Use k8s (kubernetes) as a backend (*kubernetes*). * Serve as a proxy to forward queries to some other (recursive) nameserver (*proxy*). * Provide metrics (by using Prometheus) (*metrics*). * Provide query (*log*) and error (*error*) logging. * Support the CH class: `version.bind` and friends (*chaos*). * Profiling support (*pprof*). * Rewrite queries (qtype, qclass and qname) (*rewrite*). * Echo back the IP address, transport and port number used (*whoami*). Each of the middlewares has a README.md of its own. ## Status CoreDNS can be used as a authoritative nameserver for your domains, and should be stable enough to provide you with good DNS(SEC) service. There are still few [issues](https://github.com/miekg/coredns/issues), and work is ongoing on making things fast and to reduce the memory usage. All in all, CoreDNS should be able to provide you with enough functionality to replace parts of BIND 9, Knot, NSD or PowerDNS and SkyDNS. Most documentation is in the source and some blog articles can be [found here](https://blog.coredns.io). If you do want to use CoreDNS in production, please let us know and how we can help. <https://caddyserver.com/> is also full of examples on how to structure a Corefile (renamed from Caddyfile when forked). ## Compilation CoreDNS (as a servertype plugin for Caddy) has a dependency on Caddy, but this is not different than any other Go dependency. If you have the source of CoreDNS, get all dependencies: go get ./... And then `go build` as you would normally do: go build This should yield a `coredns` binary. ## Examples When starting CoreDNS without any configuration, it loads the `whoami` middleware and starts listening on port 53 (override with `-dns.port`), it should show the following: ~~~ txt .:53 2016/09/18 09:20:50 [INFO] CoreDNS-001 CoreDNS-001 ~~~ Any query send to port 53 should return some information; your sending address, port and protocol used. If you have a Corefile without a port number specified it will, by default, use port 53, but you can override the port with the `-dns.port` flag: ~~~ txt .: { proxy . 8.8.8.8:53 log stdout } ~~~ `./coredns -dns.port 1053`, runs the server on port 1053. Start a simple proxy, you'll need to be root to start listening on port 53. `Corefile` contains: ~~~ txt .:53 { proxy . 8.8.8.8:53 log stdout } ~~~ Just start CoreDNS: `./coredns`. And then just query on that port (53). The query should be forwarded to 8.8.8.8 and the response will be returned. Each query should also show up in the log. Serve the (NSEC) DNSSEC-signed `example.org` on port 1053, with errors and logging sent to stdout. Allow zone transfers to everybody, but specically mention 1 IP address so that CoreDNS can send notifies to it. ~~~ txt example.org:1053 { file /var/lib/coredns/example.org.signed { transfer to * transfer to 2001:500:8f::53 } errors stdout log stdout } ~~~ Serve `example.org` on port 1053, but forward everything that does *not* match `example.org` to a recursive nameserver *and* rewrite ANY queries to HINFO. ~~~ txt .:1053 { rewrite ANY HINFO proxy . 8.8.8.8:53 file /var/lib/coredns/example.org.signed example.org { transfer to * transfer to 2001:500:8f::53 } errors stdout log stdout } ~~~ ## What Remains To Be Done * Optimizations. * Load testing. * The [issues](https://github.com/miekg/coredns/issues). ## Blog and Contact Website: <https://coredns.io> Twitter: [@corednsio](https://twitter.com/corednsio) Docs: <https://miek.nl/tags/coredns/> Github: <https://github.com/miekg/coredns> ## Systemd Service File Use this as a systemd service file. It defaults to a coredns with a homedir of /home/coredns and the binary lives in /opt/bin and the config in `/etc/coredns/Corefile`: ~~~ txt [Unit] Description=CoreDNS DNS server Documentation=https://coredns.io After=network.target [Service] PermissionsStartOnly=true LimitNOFILE=8192 User=coredns WorkingDirectory=/home/coredns ExecStartPre=/sbin/setcap cap_net_bind_service=+ep /opt/bin/coredns ExecStart=/opt/bin/coredns -conf=/etc/coredns/Corefile ExecReload=/bin/kill -SIGUSR1 $MAINPID Restart=on-failure [Install] WantedBy=multi-user.target ~~~
{ "content_hash": "e713c566f8ae0bd65937b97b562916b3", "timestamp": "", "source": "github", "line_count": 179, "max_line_length": 136, "avg_line_length": 32.35195530726257, "alnum_prop": 0.7299257468485582, "repo_name": "abutcher/origin", "id": "761e59061744336f42172074f73a753ffc9ca7d7", "size": "5802", "binary": false, "copies": "9", "ref": "refs/heads/master", "path": "vendor/github.com/miekg/coredns/README.md", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Awk", "bytes": "1842" }, { "name": "DIGITAL Command Language", "bytes": "117" }, { "name": "Go", "bytes": "19889017" }, { "name": "Groovy", "bytes": "5285" }, { "name": "HTML", "bytes": "74732" }, { "name": "Makefile", "bytes": "23563" }, { "name": "Python", "bytes": "34596" }, { "name": "Ruby", "bytes": "484" }, { "name": "Shell", "bytes": "2214024" }, { "name": "Smarty", "bytes": "1010" } ], "symlink_target": "" }
package utils import ( "fmt" "strings" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Utils", func() { Describe("FormatChainName", func() { It("must format a short name", func() { chain := FormatChainName("test", "1234") Expect(len(chain)).To(Equal(maxChainLength)) Expect(chain).To(Equal("CNI-2bbe0c48b91a7d1b8a6753a8")) }) It("must truncate a long name", func() { chain := FormatChainName("testalongnamethatdoesnotmakesense", "1234") Expect(len(chain)).To(Equal(maxChainLength)) Expect(chain).To(Equal("CNI-374f33fe84ab0ed84dcdebe3")) }) It("must be predictable", func() { chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234") chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1234") Expect(len(chain1)).To(Equal(maxChainLength)) Expect(len(chain2)).To(Equal(maxChainLength)) Expect(chain1).To(Equal(chain2)) }) It("must change when a character changes", func() { chain1 := FormatChainName("testalongnamethatdoesnotmakesense", "1234") chain2 := FormatChainName("testalongnamethatdoesnotmakesense", "1235") Expect(len(chain1)).To(Equal(maxChainLength)) Expect(len(chain2)).To(Equal(maxChainLength)) Expect(chain1).To(Equal("CNI-374f33fe84ab0ed84dcdebe3")) Expect(chain1).NotTo(Equal(chain2)) }) }) Describe("MustFormatChainNameWithPrefix", func() { It("generates a chain name with a prefix", func() { chain := MustFormatChainNameWithPrefix("test", "1234", "PREFIX-") Expect(len(chain)).To(Equal(maxChainLength)) Expect(chain).To(Equal("CNI-PREFIX-2bbe0c48b91a7d1b8")) }) It("must format a short name", func() { chain := MustFormatChainNameWithPrefix("test", "1234", "PREFIX-") Expect(len(chain)).To(Equal(maxChainLength)) Expect(chain).To(Equal("CNI-PREFIX-2bbe0c48b91a7d1b8")) }) It("must truncate a long name", func() { chain := MustFormatChainNameWithPrefix("testalongnamethatdoesnotmakesense", "1234", "PREFIX-") Expect(len(chain)).To(Equal(maxChainLength)) Expect(chain).To(Equal("CNI-PREFIX-374f33fe84ab0ed84")) }) It("must be predictable", func() { chain1 := MustFormatChainNameWithPrefix("testalongnamethatdoesnotmakesense", "1234", "PREFIX-") chain2 := MustFormatChainNameWithPrefix("testalongnamethatdoesnotmakesense", "1234", "PREFIX-") Expect(len(chain1)).To(Equal(maxChainLength)) Expect(len(chain2)).To(Equal(maxChainLength)) Expect(chain1).To(Equal(chain2)) }) It("must change when a character changes", func() { chain1 := MustFormatChainNameWithPrefix("testalongnamethatdoesnotmakesense", "1234", "PREFIX-") chain2 := MustFormatChainNameWithPrefix("testalongnamethatdoesnotmakesense", "1235", "PREFIX-") Expect(len(chain1)).To(Equal(maxChainLength)) Expect(len(chain2)).To(Equal(maxChainLength)) Expect(chain1).To(Equal("CNI-PREFIX-374f33fe84ab0ed84")) Expect(chain1).NotTo(Equal(chain2)) }) It("panics when prefix is too large", func() { longPrefix := strings.Repeat("PREFIX-", 4) Expect(func() { MustFormatChainNameWithPrefix("test", "1234", longPrefix) }).To(Panic()) }) }) Describe("MustFormatHashWithPrefix", func() { It("always returns a string with the given prefix", func() { Expect(MustFormatHashWithPrefix(10, "AAA", "some string")).To(HavePrefix("AAA")) Expect(MustFormatHashWithPrefix(10, "foo", "some string")).To(HavePrefix("foo")) Expect(MustFormatHashWithPrefix(10, "bar", "some string")).To(HavePrefix("bar")) }) It("always returns a string of the given length", func() { Expect(MustFormatHashWithPrefix(10, "AAA", "some string")).To(HaveLen(10)) Expect(MustFormatHashWithPrefix(15, "AAA", "some string")).To(HaveLen(15)) Expect(MustFormatHashWithPrefix(5, "AAA", "some string")).To(HaveLen(5)) }) It("is deterministic", func() { val1 := MustFormatHashWithPrefix(10, "AAA", "some string") val2 := MustFormatHashWithPrefix(10, "AAA", "some string") val3 := MustFormatHashWithPrefix(10, "AAA", "some string") Expect(val1).To(Equal(val2)) Expect(val1).To(Equal(val3)) }) It("is (nearly) perfect (injective function)", func() { hashes := map[string]int{} for i := 0; i < 1000; i++ { name := fmt.Sprintf("string %d", i) hashes[MustFormatHashWithPrefix(8, "", name)]++ } for key, count := range hashes { Expect(count).To(Equal(1), "for key "+key+" got non-unique correspondence") } }) assertPanicWith := func(f func(), expectedErrorMessage string) { defer func() { Expect(recover()).To(Equal(expectedErrorMessage)) }() f() Fail("function should have panicked but did not") } It("panics when prefix is longer than the length", func() { assertPanicWith( func() { MustFormatHashWithPrefix(3, "AAA", "some string") }, "invalid length", ) }) It("panics when length is not positive", func() { assertPanicWith( func() { MustFormatHashWithPrefix(0, "", "some string") }, "invalid length", ) }) It("panics when length is larger than MaxLen", func() { assertPanicWith( func() { MustFormatHashWithPrefix(MaxHashLen+1, "", "some string") }, "invalid length", ) }) }) })
{ "content_hash": "f6941675a589cd5bb8c8246af5266f44", "timestamp": "", "source": "github", "line_count": 151, "max_line_length": 98, "avg_line_length": 34.37748344370861, "alnum_prop": 0.6852244268926989, "repo_name": "containernetworking/plugins", "id": "0182c6d41ee695761a95a9fefdfc99fba5dd0dab", "size": "5780", "binary": false, "copies": "1", "ref": "refs/heads/main", "path": "pkg/utils/utils_test.go", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "Go", "bytes": "936897" }, { "name": "Shell", "bytes": "4292" } ], "symlink_target": "" }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="generator" content="rustdoc"> <meta name="description" content="API documentation for the Rust `Sample` trait in crate `rand`."> <meta name="keywords" content="rust, rustlang, rust-lang, Sample"> <title>rand::distributions::Sample - Rust</title> <link rel="stylesheet" type="text/css" href="../../main.css"> <link rel="shortcut icon" href="http://www.rust-lang.org/favicon.ico"> </head> <body class="rustdoc"> <!--[if lte IE 8]> <div class="warning"> This old browser is unsupported and will most likely display funky things. </div> <![endif]--> <nav class="sidebar"> <a href='../../rand/index.html'><img src='http://www.rust-lang.org/logos/rust-logo-128x128-blk.png' alt='' width='100'></a> <p class='location'><a href='../index.html'>rand</a>::<wbr><a href='index.html'>distributions</a></p><script>window.sidebarCurrent = {name: 'Sample', ty: 'trait', relpath: ''};</script><script defer src="sidebar-items.js"></script> </nav> <nav class="sub"> <form class="search-form js-only"> <div class="search-container"> <input class="search-input" name="search" autocomplete="off" placeholder="Click or press ‘S’ to search, ‘?’ for more options…" type="search"> </div> </form> </nav> <section id='main' class="content trait"> <h1 class='fqn'><span class='in-band'>Trait <a href='../index.html'>rand</a>::<wbr><a href='index.html'>distributions</a>::<wbr><a class='trait' href=''>Sample</a></span><span class='out-of-band'><span id='render-detail'> <a id="toggle-all-docs" href="javascript:void(0)" title="collapse all docs"> [<span class='inner'>&#x2212;</span>] </a> </span><a id='src-510' class='srclink' href='../../src/rand/distributions/mod.rs.html#35-39' title='goto source code'>[src]</a></span></h1> <pre class='rust trait'>pub trait Sample&lt;Support&gt; { fn <a href='#tymethod.sample' class='fnname'>sample</a>&lt;R: <a class='trait' href='../../rand/trait.Rng.html' title='rand::Rng'>Rng</a>&gt;(&amp;mut self, rng: &amp;mut R) -&gt; Support; }</pre><div class='docblock'><p>Types that can be used to create a random instance of <code>Support</code>.</p> </div> <h2 id='required-methods'>Required Methods</h2> <div class='methods'> <h3 id='tymethod.sample' class='method stab '><code>fn <a href='#tymethod.sample' class='fnname'>sample</a>&lt;R: <a class='trait' href='../../rand/trait.Rng.html' title='rand::Rng'>Rng</a>&gt;(&amp;mut self, rng: &amp;mut R) -&gt; Support</code></h3><div class='docblock'><p>Generate a random value of <code>Support</code>, using <code>rng</code> as the source of randomness.</p> </div></div> <h2 id='implementors'>Implementors</h2> <ul class='item-list' id='implementors-list'> <li><code>impl&lt;Sup: <a class='trait' href='../../rand/distributions/range/trait.SampleRange.html' title='rand::distributions::range::SampleRange'>SampleRange</a>&gt; <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;Sup&gt; for <a class='struct' href='../../rand/distributions/range/struct.Range.html' title='rand::distributions::range::Range'>Range</a>&lt;Sup&gt;</code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/gamma/struct.Gamma.html' title='rand::distributions::gamma::Gamma'>Gamma</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/gamma/struct.ChiSquared.html' title='rand::distributions::gamma::ChiSquared'>ChiSquared</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/gamma/struct.FisherF.html' title='rand::distributions::gamma::FisherF'>FisherF</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/gamma/struct.StudentT.html' title='rand::distributions::gamma::StudentT'>StudentT</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/normal/struct.Normal.html' title='rand::distributions::normal::Normal'>Normal</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/normal/struct.LogNormal.html' title='rand::distributions::normal::LogNormal'>LogNormal</a></code></li> <li><code>impl <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;<a class='primitive' href='https://doc.rust-lang.org/nightly/std/primitive.f64.html'>f64</a>&gt; for <a class='struct' href='../../rand/distributions/exponential/struct.Exp.html' title='rand::distributions::exponential::Exp'>Exp</a></code></li> <li><code>impl&lt;Sup: <a class='trait' href='../../rand/trait.Rand.html' title='rand::Rand'>Rand</a>&gt; <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;Sup&gt; for <a class='struct' href='../../rand/distributions/struct.RandSample.html' title='rand::distributions::RandSample'>RandSample</a>&lt;Sup&gt;</code></li> <li><code>impl&lt;'a, T: <a class='trait' href='https://doc.rust-lang.org/nightly/core/clone/trait.Clone.html' title='core::clone::Clone'>Clone</a>&gt; <a class='trait' href='../../rand/distributions/trait.Sample.html' title='rand::distributions::Sample'>Sample</a>&lt;T&gt; for <a class='struct' href='../../rand/distributions/struct.WeightedChoice.html' title='rand::distributions::WeightedChoice'>WeightedChoice</a>&lt;'a, T&gt;</code></li> </ul><script type="text/javascript" async src="../../implementors/rand/distributions/trait.Sample.js"> </script></section> <section id='search' class="content hidden"></section> <section class="footer"></section> <aside id="help" class="hidden"> <div> <h1 class="hidden">Help</h1> <div class="shortcuts"> <h2>Keyboard Shortcuts</h2> <dl> <dt>?</dt> <dd>Show this help dialog</dd> <dt>S</dt> <dd>Focus the search field</dd> <dt>&larrb;</dt> <dd>Move up in search results</dd> <dt>&rarrb;</dt> <dd>Move down in search results</dd> <dt>&#9166;</dt> <dd>Go to active search result</dd> </dl> </div> <div class="infos"> <h2>Search Tricks</h2> <p> Prefix searches with a type followed by a colon (e.g. <code>fn:</code>) to restrict the search to a given type. </p> <p> Accepted types are: <code>fn</code>, <code>mod</code>, <code>struct</code>, <code>enum</code>, <code>trait</code>, <code>type</code>, <code>macro</code>, and <code>const</code>. </p> <p> Search functions by type signature (e.g. <code>vec -> usize</code>) </p> </div> </div> </aside> <script> window.rootPath = "../../"; window.currentCrate = "rand"; window.playgroundUrl = ""; </script> <script src="../../jquery.js"></script> <script src="../../main.js"></script> <script async src="../../search-index.js"></script> </body> </html>
{ "content_hash": "b05ec9fac64d0d4d4c59ca10d7f14cae", "timestamp": "", "source": "github", "line_count": 133, "max_line_length": 450, "avg_line_length": 68.14285714285714, "alnum_prop": 0.610062893081761, "repo_name": "pegasos1/numbers", "id": "ddce6697d928f6ffd8a1197cfd7b94acc8127d0c", "size": "9073", "binary": false, "copies": "2", "ref": "refs/heads/master", "path": "target/doc/rand/distributions/trait.Sample.html", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "131093" }, { "name": "C++", "bytes": "1072731" }, { "name": "CMake", "bytes": "137" }, { "name": "CSS", "bytes": "15103" }, { "name": "HTML", "bytes": "39670398" }, { "name": "JavaScript", "bytes": "83160" }, { "name": "Makefile", "bytes": "31497" }, { "name": "Python", "bytes": "421" }, { "name": "Rust", "bytes": "39623" } ], "symlink_target": "" }
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>4096</title> <link href="style/main.css" rel="stylesheet" type="text/css"> <link rel="shortcut icon" href="favicon.ico"> <link rel="apple-touch-icon" href="meta/apple-touch-icon.png"> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="HandheldFriendly" content="True"> <meta name="MobileOptimized" content="320"> <meta name="viewport" content="width=device-width, target-densitydpi=160dpi, initial-scale=1.0, maximum-scale=1, user-scalable=no, minimal-ui"> </head> <body> <div class="container"> <div class="heading"> <h1 class="title">4096</h1> <div class="scores-container"> <div class="score-container">0</div> <div class="best-container">0</div> </div> </div> <p class="game-intro">Join the numbers and get to the <strong>4096 tile!</strong></p> <div class="game-container"> <div class="game-message"> <p></p> <div class="lower"> <a class="retry-button">Try again</a> </div> </div> <div class="grid-container"> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> <div class="grid-row"> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> <div class="grid-cell"></div> </div> </div> <div class="tile-container"> </div> </div> <p class="game-explanation"> <strong class="important">How to play:</strong> Use your <strong>arrow keys</strong> to move the tiles. When two tiles with the same number touch, they <strong>merge into one!</strong> </p> <hr> <p> <hr> <p> Created by <a href="http://gabrielecirulli.com" target="_blank">Gabriele Cirulli.</a> Based on <a href="https://itunes.apple.com/us/app/1024!/id823499224" target="_blank">1024 by Veewo Studio</a> and conceptually similar to <a href="http://asherv.com/threes/" target="_blank">Threes by Asher Vollmer.</a> <br> <a href="http://github.com/lolotobg/4096" target="_blank">4096</a> version by <a href="http://github.com/lolotobg" target="_blank">lolotobg</a> </p> </div> <script src="js/animframe_polyfill.js"></script> <script src="js/keyboard_input_manager.js"></script> <script src="js/html_actuator.js"></script> <script src="js/grid.js"></script> <script src="js/tile.js"></script> <script src="js/local_score_manager.js"></script> <script src="js/game_manager.js"></script> <script src="js/application.js"></script> </body> </html>
{ "content_hash": "dea9183aa500188a67faf7dd152df95b", "timestamp": "", "source": "github", "line_count": 89, "max_line_length": 310, "avg_line_length": 35.47191011235955, "alnum_prop": 0.5885334178017105, "repo_name": "lolotobg/4096", "id": "7506ea67fd3e82b72a4d9df6090a1d89135ccd46", "size": "3157", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "index.html", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "29847" }, { "name": "JavaScript", "bytes": "16255" } ], "symlink_target": "" }
#include <linux/fs.h> #include <linux/pagemap.h> #include <linux/jbd2.h> #include <linux/time.h> #include <linux/fcntl.h> #include <linux/stat.h> #include <linux/string.h> #include <linux/quotaops.h> #include <linux/buffer_head.h> #include <linux/bio.h> #include "ext4.h" #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" #include <trace/events/ext4.h> /* * define how far ahead to read directories while searching them. */ #define NAMEI_RA_CHUNKS 2 #define NAMEI_RA_BLOCKS 4 #define NAMEI_RA_SIZE (NAMEI_RA_CHUNKS * NAMEI_RA_BLOCKS) static struct buffer_head *ext4_append(handle_t *handle, struct inode *inode, ext4_lblk_t *block) { struct buffer_head *bh; int err = 0; if (unlikely(EXT4_SB(inode->i_sb)->s_max_dir_size_kb && ((inode->i_size >> 10) >= EXT4_SB(inode->i_sb)->s_max_dir_size_kb))) return ERR_PTR(-ENOSPC); *block = inode->i_size >> inode->i_sb->s_blocksize_bits; bh = ext4_bread(handle, inode, *block, 1, &err); if (!bh) return ERR_PTR(err); inode->i_size += inode->i_sb->s_blocksize; EXT4_I(inode)->i_disksize = inode->i_size; err = ext4_journal_get_write_access(handle, bh); if (err) { brelse(bh); ext4_std_error(inode->i_sb, err); return ERR_PTR(err); } return bh; } static int ext4_dx_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent); typedef enum { EITHER, INDEX, DIRENT } dirblock_type_t; #define ext4_read_dirblock(inode, block, type) \ __ext4_read_dirblock((inode), (block), (type), __LINE__) static struct buffer_head *__ext4_read_dirblock(struct inode *inode, ext4_lblk_t block, dirblock_type_t type, unsigned int line) { struct buffer_head *bh; struct ext4_dir_entry *dirent; int err = 0, is_dx_block = 0; bh = ext4_bread(NULL, inode, block, 0, &err); if (!bh) { if (err == 0) { ext4_error_inode(inode, __func__, line, block, "Directory hole found"); return ERR_PTR(-EIO); } __ext4_warning(inode->i_sb, __func__, line, "error reading directory block " "(ino %lu, block %lu)", inode->i_ino, (unsigned long) block); return ERR_PTR(err); } dirent = (struct ext4_dir_entry *) bh->b_data; /* Determine whether or not we have an index block */ if (is_dx(inode)) { if (block == 0) is_dx_block = 1; else if (ext4_rec_len_from_disk(dirent->rec_len, inode->i_sb->s_blocksize) == inode->i_sb->s_blocksize) is_dx_block = 1; } if (!is_dx_block && type == INDEX) { ext4_error_inode(inode, __func__, line, block, "directory leaf block found instead of index block"); return ERR_PTR(-EIO); } if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM) || buffer_verified(bh)) return bh; /* * An empty leaf block can get mistaken for a index block; for * this reason, we can only check the index checksum when the * caller is sure it should be an index block. */ if (is_dx_block && type == INDEX) { if (ext4_dx_csum_verify(inode, dirent)) set_buffer_verified(bh); else { ext4_error_inode(inode, __func__, line, block, "Directory index failed checksum"); brelse(bh); return ERR_PTR(-EIO); } } if (!is_dx_block) { if (ext4_dirent_csum_verify(inode, dirent)) set_buffer_verified(bh); else { ext4_error_inode(inode, __func__, line, block, "Directory block failed checksum"); brelse(bh); return ERR_PTR(-EIO); } } return bh; } #ifndef assert #define assert(test) J_ASSERT(test) #endif #ifdef DX_DEBUG #define dxtrace(command) command #else #define dxtrace(command) #endif struct fake_dirent { __le32 inode; __le16 rec_len; u8 name_len; u8 file_type; }; struct dx_countlimit { __le16 limit; __le16 count; }; struct dx_entry { __le32 hash; __le32 block; }; /* * dx_root_info is laid out so that if it should somehow get overlaid by a * dirent the two low bits of the hash version will be zero. Therefore, the * hash version mod 4 should never be 0. Sincerely, the paranoia department. */ struct dx_root { struct fake_dirent dot; char dot_name[4]; struct fake_dirent dotdot; char dotdot_name[4]; struct dx_root_info { __le32 reserved_zero; u8 hash_version; u8 info_length; /* 8 */ u8 indirect_levels; u8 unused_flags; } info; struct dx_entry entries[0]; }; struct dx_node { struct fake_dirent fake; struct dx_entry entries[0]; }; struct dx_frame { struct buffer_head *bh; struct dx_entry *entries; struct dx_entry *at; }; struct dx_map_entry { u32 hash; u16 offs; u16 size; }; /* * This goes at the end of each htree block. */ struct dx_tail { u32 dt_reserved; __le32 dt_checksum; /* crc32c(uuid+inum+dirblock) */ }; static inline ext4_lblk_t dx_get_block(struct dx_entry *entry); static void dx_set_block(struct dx_entry *entry, ext4_lblk_t value); static inline unsigned dx_get_hash(struct dx_entry *entry); static void dx_set_hash(struct dx_entry *entry, unsigned value); static unsigned dx_get_count(struct dx_entry *entries); static unsigned dx_get_limit(struct dx_entry *entries); static void dx_set_count(struct dx_entry *entries, unsigned value); static void dx_set_limit(struct dx_entry *entries, unsigned value); static unsigned dx_root_limit(struct inode *dir, unsigned infosize); static unsigned dx_node_limit(struct inode *dir); static struct dx_frame *dx_probe(const struct qstr *d_name, struct inode *dir, struct dx_hash_info *hinfo, struct dx_frame *frame, int *err); static void dx_release(struct dx_frame *frames); static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize, struct dx_hash_info *hinfo, struct dx_map_entry map[]); static void dx_sort_map(struct dx_map_entry *map, unsigned count); static struct ext4_dir_entry_2 *dx_move_dirents(char *from, char *to, struct dx_map_entry *offsets, int count, unsigned blocksize); static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize); static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block); static int ext4_htree_next_block(struct inode *dir, __u32 hash, struct dx_frame *frame, struct dx_frame *frames, __u32 *start_hash); static struct buffer_head * ext4_dx_find_entry(struct inode *dir, const struct qstr *d_name, struct ext4_dir_entry_2 **res_dir, int *err); static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry, struct inode *inode); /* checksumming functions */ void initialize_dirent_tail(struct ext4_dir_entry_tail *t, unsigned int blocksize) { memset(t, 0, sizeof(struct ext4_dir_entry_tail)); t->det_rec_len = ext4_rec_len_to_disk( sizeof(struct ext4_dir_entry_tail), blocksize); t->det_reserved_ft = EXT4_FT_DIR_CSUM; } /* Walk through a dirent block to find a checksum "dirent" at the tail */ static struct ext4_dir_entry_tail *get_dirent_tail(struct inode *inode, struct ext4_dir_entry *de) { struct ext4_dir_entry_tail *t; #ifdef PARANOID struct ext4_dir_entry *d, *top; d = de; top = (struct ext4_dir_entry *)(((void *)de) + (EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct ext4_dir_entry_tail))); while (d < top && d->rec_len) d = (struct ext4_dir_entry *)(((void *)d) + le16_to_cpu(d->rec_len)); if (d != top) return NULL; t = (struct ext4_dir_entry_tail *)d; #else t = EXT4_DIRENT_TAIL(de, EXT4_BLOCK_SIZE(inode->i_sb)); #endif if (t->det_reserved_zero1 || le16_to_cpu(t->det_rec_len) != sizeof(struct ext4_dir_entry_tail) || t->det_reserved_zero2 || t->det_reserved_ft != EXT4_FT_DIR_CSUM) return NULL; return t; } static __le32 ext4_dirent_csum(struct inode *inode, struct ext4_dir_entry *dirent, int size) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); __u32 csum; csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size); return cpu_to_le32(csum); } static void warn_no_space_for_csum(struct inode *inode) { ext4_warning(inode->i_sb, "no space in directory inode %lu leaf for " "checksum. Please run e2fsck -D.", inode->i_ino); } int ext4_dirent_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent) { struct ext4_dir_entry_tail *t; if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return 1; t = get_dirent_tail(inode, dirent); if (!t) { warn_no_space_for_csum(inode); return 0; } if (t->det_checksum != ext4_dirent_csum(inode, dirent, (void *)t - (void *)dirent)) return 0; return 1; } static void ext4_dirent_csum_set(struct inode *inode, struct ext4_dir_entry *dirent) { struct ext4_dir_entry_tail *t; if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return; t = get_dirent_tail(inode, dirent); if (!t) { warn_no_space_for_csum(inode); return; } t->det_checksum = ext4_dirent_csum(inode, dirent, (void *)t - (void *)dirent); } int ext4_handle_dirty_dirent_node(handle_t *handle, struct inode *inode, struct buffer_head *bh) { ext4_dirent_csum_set(inode, (struct ext4_dir_entry *)bh->b_data); return ext4_handle_dirty_metadata(handle, inode, bh); } static struct dx_countlimit *get_dx_countlimit(struct inode *inode, struct ext4_dir_entry *dirent, int *offset) { struct ext4_dir_entry *dp; struct dx_root_info *root; int count_offset; if (le16_to_cpu(dirent->rec_len) == EXT4_BLOCK_SIZE(inode->i_sb)) count_offset = 8; else if (le16_to_cpu(dirent->rec_len) == 12) { dp = (struct ext4_dir_entry *)(((void *)dirent) + 12); if (le16_to_cpu(dp->rec_len) != EXT4_BLOCK_SIZE(inode->i_sb) - 12) return NULL; root = (struct dx_root_info *)(((void *)dp + 12)); if (root->reserved_zero || root->info_length != sizeof(struct dx_root_info)) return NULL; count_offset = 32; } else return NULL; if (offset) *offset = count_offset; return (struct dx_countlimit *)(((void *)dirent) + count_offset); } static __le32 ext4_dx_csum(struct inode *inode, struct ext4_dir_entry *dirent, int count_offset, int count, struct dx_tail *t) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); __u32 csum; __le32 save_csum; int size; size = count_offset + (count * sizeof(struct dx_entry)); save_csum = t->dt_checksum; t->dt_checksum = 0; csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)dirent, size); csum = ext4_chksum(sbi, csum, (__u8 *)t, sizeof(struct dx_tail)); t->dt_checksum = save_csum; return cpu_to_le32(csum); } static int ext4_dx_csum_verify(struct inode *inode, struct ext4_dir_entry *dirent) { struct dx_countlimit *c; struct dx_tail *t; int count_offset, limit, count; if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return 1; c = get_dx_countlimit(inode, dirent, &count_offset); if (!c) { EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D."); return 1; } limit = le16_to_cpu(c->limit); count = le16_to_cpu(c->count); if (count_offset + (limit * sizeof(struct dx_entry)) > EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) { warn_no_space_for_csum(inode); return 1; } t = (struct dx_tail *)(((struct dx_entry *)c) + limit); if (t->dt_checksum != ext4_dx_csum(inode, dirent, count_offset, count, t)) return 0; return 1; } static void ext4_dx_csum_set(struct inode *inode, struct ext4_dir_entry *dirent) { struct dx_countlimit *c; struct dx_tail *t; int count_offset, limit, count; if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) return; c = get_dx_countlimit(inode, dirent, &count_offset); if (!c) { EXT4_ERROR_INODE(inode, "dir seems corrupt? Run e2fsck -D."); return; } limit = le16_to_cpu(c->limit); count = le16_to_cpu(c->count); if (count_offset + (limit * sizeof(struct dx_entry)) > EXT4_BLOCK_SIZE(inode->i_sb) - sizeof(struct dx_tail)) { warn_no_space_for_csum(inode); return; } t = (struct dx_tail *)(((struct dx_entry *)c) + limit); t->dt_checksum = ext4_dx_csum(inode, dirent, count_offset, count, t); } static inline int ext4_handle_dirty_dx_node(handle_t *handle, struct inode *inode, struct buffer_head *bh) { ext4_dx_csum_set(inode, (struct ext4_dir_entry *)bh->b_data); return ext4_handle_dirty_metadata(handle, inode, bh); } /* * p is at least 6 bytes before the end of page */ static inline struct ext4_dir_entry_2 * ext4_next_entry(struct ext4_dir_entry_2 *p, unsigned long blocksize) { return (struct ext4_dir_entry_2 *)((char *)p + ext4_rec_len_from_disk(p->rec_len, blocksize)); } /* * Future: use high four bits of block for coalesce-on-delete flags * Mask them off for now. */ static inline ext4_lblk_t dx_get_block(struct dx_entry *entry) { return le32_to_cpu(entry->block) & 0x00ffffff; } static inline void dx_set_block(struct dx_entry *entry, ext4_lblk_t value) { entry->block = cpu_to_le32(value); } static inline unsigned dx_get_hash(struct dx_entry *entry) { return le32_to_cpu(entry->hash); } static inline void dx_set_hash(struct dx_entry *entry, unsigned value) { entry->hash = cpu_to_le32(value); } static inline unsigned dx_get_count(struct dx_entry *entries) { return le16_to_cpu(((struct dx_countlimit *) entries)->count); } static inline unsigned dx_get_limit(struct dx_entry *entries) { return le16_to_cpu(((struct dx_countlimit *) entries)->limit); } static inline void dx_set_count(struct dx_entry *entries, unsigned value) { ((struct dx_countlimit *) entries)->count = cpu_to_le16(value); } static inline void dx_set_limit(struct dx_entry *entries, unsigned value) { ((struct dx_countlimit *) entries)->limit = cpu_to_le16(value); } static inline unsigned dx_root_limit(struct inode *dir, unsigned infosize) { unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(1) - EXT4_DIR_REC_LEN(2) - infosize; if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) entry_space -= sizeof(struct dx_tail); return entry_space / sizeof(struct dx_entry); } static inline unsigned dx_node_limit(struct inode *dir) { unsigned entry_space = dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0); if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) entry_space -= sizeof(struct dx_tail); return entry_space / sizeof(struct dx_entry); } /* * Debug */ #ifdef DX_DEBUG static void dx_show_index(char * label, struct dx_entry *entries) { int i, n = dx_get_count (entries); printk(KERN_DEBUG "%s index ", label); for (i = 0; i < n; i++) { printk("%x->%lu ", i ? dx_get_hash(entries + i) : 0, (unsigned long)dx_get_block(entries + i)); } printk("\n"); } struct stats { unsigned names; unsigned space; unsigned bcount; }; static struct stats dx_show_leaf(struct dx_hash_info *hinfo, struct ext4_dir_entry_2 *de, int size, int show_names) { unsigned names = 0, space = 0; char *base = (char *) de; struct dx_hash_info h = *hinfo; printk("names: "); while ((char *) de < base + size) { if (de->inode) { if (show_names) { int len = de->name_len; char *name = de->name; while (len--) printk("%c", *name++); ext4fs_dirhash(de->name, de->name_len, &h); printk(":%x.%u ", h.hash, (unsigned) ((char *) de - base)); } space += EXT4_DIR_REC_LEN(de->name_len); names++; } de = ext4_next_entry(de, size); } printk("(%i)\n", names); return (struct stats) { names, space, 1 }; } struct stats dx_show_entries(struct dx_hash_info *hinfo, struct inode *dir, struct dx_entry *entries, int levels) { unsigned blocksize = dir->i_sb->s_blocksize; unsigned count = dx_get_count(entries), names = 0, space = 0, i; unsigned bcount = 0; struct buffer_head *bh; int err; printk("%i indexed blocks...\n", count); for (i = 0; i < count; i++, entries++) { ext4_lblk_t block = dx_get_block(entries); ext4_lblk_t hash = i ? dx_get_hash(entries): 0; u32 range = i < count - 1? (dx_get_hash(entries + 1) - hash): ~hash; struct stats stats; printk("%s%3u:%03u hash %8x/%8x ",levels?"":" ", i, block, hash, range); if (!(bh = ext4_bread (NULL,dir, block, 0,&err))) continue; stats = levels? dx_show_entries(hinfo, dir, ((struct dx_node *) bh->b_data)->entries, levels - 1): dx_show_leaf(hinfo, (struct ext4_dir_entry_2 *) bh->b_data, blocksize, 0); names += stats.names; space += stats.space; bcount += stats.bcount; brelse(bh); } if (bcount) printk(KERN_DEBUG "%snames %u, fullness %u (%u%%)\n", levels ? "" : " ", names, space/bcount, (space/bcount)*100/blocksize); return (struct stats) { names, space, bcount}; } #endif /* DX_DEBUG */ /* * Probe for a directory leaf block to search. * * dx_probe can return ERR_BAD_DX_DIR, which means there was a format * error in the directory index, and the caller should fall back to * searching the directory normally. The callers of dx_probe **MUST** * check for this error code, and make sure it never gets reflected * back to userspace. */ static struct dx_frame * dx_probe(const struct qstr *d_name, struct inode *dir, struct dx_hash_info *hinfo, struct dx_frame *frame_in, int *err) { unsigned count, indirect; struct dx_entry *at, *entries, *p, *q, *m; struct dx_root *root; struct buffer_head *bh; struct dx_frame *frame = frame_in; u32 hash; frame->bh = NULL; bh = ext4_read_dirblock(dir, 0, INDEX); if (IS_ERR(bh)) { *err = PTR_ERR(bh); goto fail; } root = (struct dx_root *) bh->b_data; if (root->info.hash_version != DX_HASH_TEA && root->info.hash_version != DX_HASH_HALF_MD4 && root->info.hash_version != DX_HASH_LEGACY) { ext4_warning(dir->i_sb, "Unrecognised inode hash code %d", root->info.hash_version); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail; } hinfo->hash_version = root->info.hash_version; if (hinfo->hash_version <= DX_HASH_TEA) hinfo->hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned; hinfo->seed = EXT4_SB(dir->i_sb)->s_hash_seed; if (d_name) ext4fs_dirhash(d_name->name, d_name->len, hinfo); hash = hinfo->hash; if (root->info.unused_flags & 1) { ext4_warning(dir->i_sb, "Unimplemented inode hash flags: %#06x", root->info.unused_flags); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail; } if ((indirect = root->info.indirect_levels) > 1) { ext4_warning(dir->i_sb, "Unimplemented inode hash depth: %#06x", root->info.indirect_levels); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail; } entries = (struct dx_entry *) (((char *)&root->info) + root->info.info_length); if (dx_get_limit(entries) != dx_root_limit(dir, root->info.info_length)) { ext4_warning(dir->i_sb, "dx entry: limit != root limit"); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail; } dxtrace(printk("Look up %x", hash)); while (1) { count = dx_get_count(entries); if (!count || count > dx_get_limit(entries)) { ext4_warning(dir->i_sb, "dx entry: no count or count > limit"); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail2; } p = entries + 1; q = entries + count - 1; while (p <= q) { m = p + (q - p)/2; dxtrace(printk(".")); if (dx_get_hash(m) > hash) q = m - 1; else p = m + 1; } if (0) // linear search cross check { unsigned n = count - 1; at = entries; while (n--) { dxtrace(printk(",")); if (dx_get_hash(++at) > hash) { at--; break; } } assert (at == p - 1); } at = p - 1; dxtrace(printk(" %x->%u\n", at == entries? 0: dx_get_hash(at), dx_get_block(at))); frame->bh = bh; frame->entries = entries; frame->at = at; if (!indirect--) return frame; bh = ext4_read_dirblock(dir, dx_get_block(at), INDEX); if (IS_ERR(bh)) { *err = PTR_ERR(bh); goto fail2; } entries = ((struct dx_node *) bh->b_data)->entries; if (dx_get_limit(entries) != dx_node_limit (dir)) { ext4_warning(dir->i_sb, "dx entry: limit != node limit"); brelse(bh); *err = ERR_BAD_DX_DIR; goto fail2; } frame++; frame->bh = NULL; } fail2: while (frame >= frame_in) { brelse(frame->bh); frame--; } fail: if (*err == ERR_BAD_DX_DIR) ext4_warning(dir->i_sb, "Corrupt dir inode %lu, running e2fsck is " "recommended.", dir->i_ino); return NULL; } static void dx_release (struct dx_frame *frames) { if (frames[0].bh == NULL) return; if (((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels) brelse(frames[1].bh); brelse(frames[0].bh); } /* * This function increments the frame pointer to search the next leaf * block, and reads in the necessary intervening nodes if the search * should be necessary. Whether or not the search is necessary is * controlled by the hash parameter. If the hash value is even, then * the search is only continued if the next block starts with that * hash value. This is used if we are searching for a specific file. * * If the hash value is HASH_NB_ALWAYS, then always go to the next block. * * This function returns 1 if the caller should continue to search, * or 0 if it should not. If there is an error reading one of the * index blocks, it will a negative error code. * * If start_hash is non-null, it will be filled in with the starting * hash of the next page. */ static int ext4_htree_next_block(struct inode *dir, __u32 hash, struct dx_frame *frame, struct dx_frame *frames, __u32 *start_hash) { struct dx_frame *p; struct buffer_head *bh; int num_frames = 0; __u32 bhash; p = frame; /* * Find the next leaf page by incrementing the frame pointer. * If we run out of entries in the interior node, loop around and * increment pointer in the parent node. When we break out of * this loop, num_frames indicates the number of interior * nodes need to be read. */ while (1) { if (++(p->at) < p->entries + dx_get_count(p->entries)) break; if (p == frames) return 0; num_frames++; p--; } /* * If the hash is 1, then continue only if the next page has a * continuation hash of any value. This is used for readdir * handling. Otherwise, check to see if the hash matches the * desired contiuation hash. If it doesn't, return since * there's no point to read in the successive index pages. */ bhash = dx_get_hash(p->at); if (start_hash) *start_hash = bhash; if ((hash & 1) == 0) { if ((bhash & ~1) != hash) return 0; } /* * If the hash is HASH_NB_ALWAYS, we always go to the next * block so no check is necessary */ while (num_frames--) { bh = ext4_read_dirblock(dir, dx_get_block(p->at), INDEX); if (IS_ERR(bh)) return PTR_ERR(bh); p++; brelse(p->bh); p->bh = bh; p->at = p->entries = ((struct dx_node *) bh->b_data)->entries; } return 1; } /* * This function fills a red-black tree with information from a * directory block. It returns the number directory entries loaded * into the tree. If there is an error it is returned in err. */ static int htree_dirblock_to_tree(struct file *dir_file, struct inode *dir, ext4_lblk_t block, struct dx_hash_info *hinfo, __u32 start_hash, __u32 start_minor_hash) { struct buffer_head *bh; struct ext4_dir_entry_2 *de, *top; int err = 0, count = 0; dxtrace(printk(KERN_INFO "In htree dirblock_to_tree: block %lu\n", (unsigned long)block)); bh = ext4_read_dirblock(dir, block, DIRENT); if (IS_ERR(bh)) return PTR_ERR(bh); de = (struct ext4_dir_entry_2 *) bh->b_data; top = (struct ext4_dir_entry_2 *) ((char *) de + dir->i_sb->s_blocksize - EXT4_DIR_REC_LEN(0)); for (; de < top; de = ext4_next_entry(de, dir->i_sb->s_blocksize)) { if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data, bh->b_size, (block<<EXT4_BLOCK_SIZE_BITS(dir->i_sb)) + ((char *)de - bh->b_data))) { /* silently ignore the rest of the block */ break; } ext4fs_dirhash(de->name, de->name_len, hinfo); if ((hinfo->hash < start_hash) || ((hinfo->hash == start_hash) && (hinfo->minor_hash < start_minor_hash))) continue; if (de->inode == 0) continue; if ((err = ext4_htree_store_dirent(dir_file, hinfo->hash, hinfo->minor_hash, de)) != 0) { brelse(bh); return err; } count++; } brelse(bh); return count; } /* * This function fills a red-black tree with information from a * directory. We start scanning the directory in hash order, starting * at start_hash and start_minor_hash. * * This function returns the number of entries inserted into the tree, * or a negative error code. */ int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash, __u32 start_minor_hash, __u32 *next_hash) { struct dx_hash_info hinfo; struct ext4_dir_entry_2 *de; struct dx_frame frames[2], *frame; struct inode *dir; ext4_lblk_t block; int count = 0; int ret, err; __u32 hashval; dxtrace(printk(KERN_DEBUG "In htree_fill_tree, start hash: %x:%x\n", start_hash, start_minor_hash)); dir = file_inode(dir_file); if (!(ext4_test_inode_flag(dir, EXT4_INODE_INDEX))) { hinfo.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version; if (hinfo.hash_version <= DX_HASH_TEA) hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned; hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed; if (ext4_has_inline_data(dir)) { int has_inline_data = 1; count = htree_inlinedir_to_tree(dir_file, dir, 0, &hinfo, start_hash, start_minor_hash, &has_inline_data); if (has_inline_data) { *next_hash = ~0; return count; } } count = htree_dirblock_to_tree(dir_file, dir, 0, &hinfo, start_hash, start_minor_hash); *next_hash = ~0; return count; } hinfo.hash = start_hash; hinfo.minor_hash = 0; frame = dx_probe(NULL, dir, &hinfo, frames, &err); if (!frame) return err; /* Add '.' and '..' from the htree header */ if (!start_hash && !start_minor_hash) { de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data; if ((err = ext4_htree_store_dirent(dir_file, 0, 0, de)) != 0) goto errout; count++; } if (start_hash < 2 || (start_hash ==2 && start_minor_hash==0)) { de = (struct ext4_dir_entry_2 *) frames[0].bh->b_data; de = ext4_next_entry(de, dir->i_sb->s_blocksize); if ((err = ext4_htree_store_dirent(dir_file, 2, 0, de)) != 0) goto errout; count++; } while (1) { block = dx_get_block(frame->at); ret = htree_dirblock_to_tree(dir_file, dir, block, &hinfo, start_hash, start_minor_hash); if (ret < 0) { err = ret; goto errout; } count += ret; hashval = ~0; ret = ext4_htree_next_block(dir, HASH_NB_ALWAYS, frame, frames, &hashval); *next_hash = hashval; if (ret < 0) { err = ret; goto errout; } /* * Stop if: (a) there are no more entries, or * (b) we have inserted at least one entry and the * next hash value is not a continuation */ if ((ret == 0) || (count && ((hashval & 1) == 0))) break; } dx_release(frames); dxtrace(printk(KERN_DEBUG "Fill tree: returned %d entries, " "next hash: %x\n", count, *next_hash)); return count; errout: dx_release(frames); return (err); } static inline int search_dirblock(struct buffer_head *bh, struct inode *dir, const struct qstr *d_name, unsigned int offset, struct ext4_dir_entry_2 **res_dir) { return search_dir(bh, bh->b_data, dir->i_sb->s_blocksize, dir, d_name, offset, res_dir); } /* * Directory block splitting, compacting */ /* * Create map of hash values, offsets, and sizes, stored at end of block. * Returns number of entries mapped. */ static int dx_make_map(struct ext4_dir_entry_2 *de, unsigned blocksize, struct dx_hash_info *hinfo, struct dx_map_entry *map_tail) { int count = 0; char *base = (char *) de; struct dx_hash_info h = *hinfo; while ((char *) de < base + blocksize) { if (de->name_len && de->inode) { ext4fs_dirhash(de->name, de->name_len, &h); map_tail--; map_tail->hash = h.hash; map_tail->offs = ((char *) de - base)>>2; map_tail->size = le16_to_cpu(de->rec_len); count++; cond_resched(); } /* XXX: do we need to check rec_len == 0 case? -Chris */ de = ext4_next_entry(de, blocksize); } return count; } /* Sort map by hash value */ static void dx_sort_map (struct dx_map_entry *map, unsigned count) { struct dx_map_entry *p, *q, *top = map + count - 1; int more; /* Combsort until bubble sort doesn't suck */ while (count > 2) { count = count*10/13; if (count - 9 < 2) /* 9, 10 -> 11 */ count = 11; for (p = top, q = p - count; q >= map; p--, q--) if (p->hash < q->hash) swap(*p, *q); } /* Garden variety bubble sort */ do { more = 0; q = top; while (q-- > map) { if (q[1].hash >= q[0].hash) continue; swap(*(q+1), *q); more = 1; } } while(more); } static void dx_insert_block(struct dx_frame *frame, u32 hash, ext4_lblk_t block) { struct dx_entry *entries = frame->entries; struct dx_entry *old = frame->at, *new = old + 1; int count = dx_get_count(entries); assert(count < dx_get_limit(entries)); assert(old < entries + count); memmove(new + 1, new, (char *)(entries + count) - (char *)(new)); dx_set_hash(new, hash); dx_set_block(new, block); dx_set_count(entries, count + 1); } /* * NOTE! unlike strncmp, ext4_match returns 1 for success, 0 for failure. * * `len <= EXT4_NAME_LEN' is guaranteed by caller. * `de != NULL' is guaranteed by caller. */ static inline int ext4_match (int len, const char * const name, struct ext4_dir_entry_2 * de) { if (len != de->name_len) return 0; if (!de->inode) return 0; return !memcmp(name, de->name, len); } /* * Returns 0 if not found, -1 on failure, and 1 on success */ int search_dir(struct buffer_head *bh, char *search_buf, int buf_size, struct inode *dir, const struct qstr *d_name, unsigned int offset, struct ext4_dir_entry_2 **res_dir) { struct ext4_dir_entry_2 * de; char * dlimit; int de_len; const char *name = d_name->name; int namelen = d_name->len; de = (struct ext4_dir_entry_2 *)search_buf; dlimit = search_buf + buf_size; while ((char *) de < dlimit) { /* this code is executed quadratically often */ /* do minimal checking `by hand' */ if ((char *) de + namelen <= dlimit && ext4_match (namelen, name, de)) { /* found a match - just to be sure, do a full check */ if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data, bh->b_size, offset)) return -1; *res_dir = de; return 1; } /* prevent looping on a bad block */ de_len = ext4_rec_len_from_disk(de->rec_len, dir->i_sb->s_blocksize); if (de_len <= 0) return -1; offset += de_len; de = (struct ext4_dir_entry_2 *) ((char *) de + de_len); } return 0; } static int is_dx_internal_node(struct inode *dir, ext4_lblk_t block, struct ext4_dir_entry *de) { struct super_block *sb = dir->i_sb; if (!is_dx(dir)) return 0; if (block == 0) return 1; if (de->inode == 0 && ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) == sb->s_blocksize) return 1; return 0; } /* * ext4_find_entry() * * finds an entry in the specified directory with the wanted name. It * returns the cache buffer in which the entry was found, and the entry * itself (as a parameter - res_dir). It does NOT read the inode of the * entry - you'll have to do that yourself if you want to. * * The returned buffer_head has ->b_count elevated. The caller is expected * to brelse() it when appropriate. */ static struct buffer_head * ext4_find_entry (struct inode *dir, const struct qstr *d_name, struct ext4_dir_entry_2 **res_dir, int *inlined) { struct super_block *sb; struct buffer_head *bh_use[NAMEI_RA_SIZE]; struct buffer_head *bh, *ret = NULL; ext4_lblk_t start, block, b; const u8 *name = d_name->name; int ra_max = 0; /* Number of bh's in the readahead buffer, bh_use[] */ int ra_ptr = 0; /* Current index into readahead buffer */ int num = 0; ext4_lblk_t nblocks; int i, err; int namelen; *res_dir = NULL; sb = dir->i_sb; namelen = d_name->len; if (namelen > EXT4_NAME_LEN) return NULL; if (ext4_has_inline_data(dir)) { int has_inline_data = 1; ret = ext4_find_inline_entry(dir, d_name, res_dir, &has_inline_data); if (has_inline_data) { if (inlined) *inlined = 1; return ret; } } if ((namelen <= 2) && (name[0] == '.') && (name[1] == '.' || name[1] == '\0')) { /* * "." or ".." will only be in the first block * NFS may look up ".."; "." should be handled by the VFS */ block = start = 0; nblocks = 1; goto restart; } if (is_dx(dir)) { bh = ext4_dx_find_entry(dir, d_name, res_dir, &err); /* * On success, or if the error was file not found, * return. Otherwise, fall back to doing a search the * old fashioned way. */ if (bh || (err != ERR_BAD_DX_DIR)) return bh; dxtrace(printk(KERN_DEBUG "ext4_find_entry: dx failed, " "falling back\n")); } nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb); start = EXT4_I(dir)->i_dir_start_lookup; if (start >= nblocks) start = 0; block = start; restart: do { /* * We deal with the read-ahead logic here. */ if (ra_ptr >= ra_max) { /* Refill the readahead buffer */ ra_ptr = 0; b = block; for (ra_max = 0; ra_max < NAMEI_RA_SIZE; ra_max++) { /* * Terminate if we reach the end of the * directory and must wrap, or if our * search has finished at this block. */ if (b >= nblocks || (num && block == start)) { bh_use[ra_max] = NULL; break; } num++; bh = ext4_getblk(NULL, dir, b++, 0, &err); bh_use[ra_max] = bh; if (bh) ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh); } } if ((bh = bh_use[ra_ptr++]) == NULL) goto next; wait_on_buffer(bh); if (!buffer_uptodate(bh)) { /* read error, skip block & hope for the best */ EXT4_ERROR_INODE(dir, "reading directory lblock %lu", (unsigned long) block); brelse(bh); goto next; } if (!buffer_verified(bh) && !is_dx_internal_node(dir, block, (struct ext4_dir_entry *)bh->b_data) && !ext4_dirent_csum_verify(dir, (struct ext4_dir_entry *)bh->b_data)) { EXT4_ERROR_INODE(dir, "checksumming directory " "block %lu", (unsigned long)block); brelse(bh); goto next; } set_buffer_verified(bh); i = search_dirblock(bh, dir, d_name, block << EXT4_BLOCK_SIZE_BITS(sb), res_dir); if (i == 1) { EXT4_I(dir)->i_dir_start_lookup = block; ret = bh; goto cleanup_and_exit; } else { brelse(bh); if (i < 0) goto cleanup_and_exit; } next: if (++block >= nblocks) block = 0; } while (block != start); /* * If the directory has grown while we were searching, then * search the last part of the directory before giving up. */ block = nblocks; nblocks = dir->i_size >> EXT4_BLOCK_SIZE_BITS(sb); if (block < nblocks) { start = 0; goto restart; } cleanup_and_exit: /* Clean up the read-ahead blocks */ for (; ra_ptr < ra_max; ra_ptr++) brelse(bh_use[ra_ptr]); return ret; } static struct buffer_head * ext4_dx_find_entry(struct inode *dir, const struct qstr *d_name, struct ext4_dir_entry_2 **res_dir, int *err) { struct super_block * sb = dir->i_sb; struct dx_hash_info hinfo; struct dx_frame frames[2], *frame; struct buffer_head *bh; ext4_lblk_t block; int retval; if (!(frame = dx_probe(d_name, dir, &hinfo, frames, err))) return NULL; do { block = dx_get_block(frame->at); bh = ext4_read_dirblock(dir, block, DIRENT); if (IS_ERR(bh)) { *err = PTR_ERR(bh); goto errout; } retval = search_dirblock(bh, dir, d_name, block << EXT4_BLOCK_SIZE_BITS(sb), res_dir); if (retval == 1) { /* Success! */ dx_release(frames); return bh; } brelse(bh); if (retval == -1) { *err = ERR_BAD_DX_DIR; goto errout; } /* Check to see if we should continue to search */ retval = ext4_htree_next_block(dir, hinfo.hash, frame, frames, NULL); if (retval < 0) { ext4_warning(sb, "error reading index page in directory #%lu", dir->i_ino); *err = retval; goto errout; } } while (retval == 1); *err = -ENOENT; errout: dxtrace(printk(KERN_DEBUG "%s not found\n", d_name->name)); dx_release (frames); return NULL; } static struct dentry *ext4_lookup(struct inode *dir, struct dentry *dentry, unsigned int flags) { struct inode *inode; struct ext4_dir_entry_2 *de; struct buffer_head *bh; if (dentry->d_name.len > EXT4_NAME_LEN) return ERR_PTR(-ENAMETOOLONG); bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL); inode = NULL; if (bh) { __u32 ino = le32_to_cpu(de->inode); brelse(bh); if (!ext4_valid_inum(dir->i_sb, ino)) { EXT4_ERROR_INODE(dir, "bad inode number: %u", ino); return ERR_PTR(-EIO); } if (unlikely(ino == dir->i_ino)) { EXT4_ERROR_INODE(dir, "'%.*s' linked to parent dir", dentry->d_name.len, dentry->d_name.name); return ERR_PTR(-EIO); } inode = ext4_iget(dir->i_sb, ino); if (inode == ERR_PTR(-ESTALE)) { EXT4_ERROR_INODE(dir, "deleted inode referenced: %u", ino); return ERR_PTR(-EIO); } } return d_splice_alias(inode, dentry); } struct dentry *ext4_get_parent(struct dentry *child) { __u32 ino; static const struct qstr dotdot = QSTR_INIT("..", 2); struct ext4_dir_entry_2 * de; struct buffer_head *bh; bh = ext4_find_entry(child->d_inode, &dotdot, &de, NULL); if (!bh) return ERR_PTR(-ENOENT); ino = le32_to_cpu(de->inode); brelse(bh); if (!ext4_valid_inum(child->d_inode->i_sb, ino)) { EXT4_ERROR_INODE(child->d_inode, "bad parent inode number: %u", ino); return ERR_PTR(-EIO); } return d_obtain_alias(ext4_iget(child->d_inode->i_sb, ino)); } /* * Move count entries from end of map between two memory locations. * Returns pointer to last entry moved. */ static struct ext4_dir_entry_2 * dx_move_dirents(char *from, char *to, struct dx_map_entry *map, int count, unsigned blocksize) { unsigned rec_len = 0; while (count--) { struct ext4_dir_entry_2 *de = (struct ext4_dir_entry_2 *) (from + (map->offs<<2)); rec_len = EXT4_DIR_REC_LEN(de->name_len); memcpy (to, de, rec_len); ((struct ext4_dir_entry_2 *) to)->rec_len = ext4_rec_len_to_disk(rec_len, blocksize); de->inode = 0; map++; to += rec_len; } return (struct ext4_dir_entry_2 *) (to - rec_len); } /* * Compact each dir entry in the range to the minimal rec_len. * Returns pointer to last entry in range. */ static struct ext4_dir_entry_2* dx_pack_dirents(char *base, unsigned blocksize) { struct ext4_dir_entry_2 *next, *to, *prev, *de = (struct ext4_dir_entry_2 *) base; unsigned rec_len = 0; prev = to = de; while ((char*)de < base + blocksize) { next = ext4_next_entry(de, blocksize); if (de->inode && de->name_len) { rec_len = EXT4_DIR_REC_LEN(de->name_len); if (de > to) memmove(to, de, rec_len); to->rec_len = ext4_rec_len_to_disk(rec_len, blocksize); prev = to; to = (struct ext4_dir_entry_2 *) (((char *) to) + rec_len); } de = next; } return prev; } /* * Split a full leaf block to make room for a new dir entry. * Allocate a new block, and move entries so that they are approx. equally full. * Returns pointer to de in block into which the new entry will be inserted. */ static struct ext4_dir_entry_2 *do_split(handle_t *handle, struct inode *dir, struct buffer_head **bh,struct dx_frame *frame, struct dx_hash_info *hinfo, int *error) { unsigned blocksize = dir->i_sb->s_blocksize; unsigned count, continued; struct buffer_head *bh2; ext4_lblk_t newblock; u32 hash2; struct dx_map_entry *map; char *data1 = (*bh)->b_data, *data2; unsigned split, move, size; struct ext4_dir_entry_2 *de = NULL, *de2; struct ext4_dir_entry_tail *t; int csum_size = 0; int err = 0, i; if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); bh2 = ext4_append(handle, dir, &newblock); if (IS_ERR(bh2)) { brelse(*bh); *bh = NULL; *error = PTR_ERR(bh2); return NULL; } BUFFER_TRACE(*bh, "get_write_access"); err = ext4_journal_get_write_access(handle, *bh); if (err) goto journal_error; BUFFER_TRACE(frame->bh, "get_write_access"); err = ext4_journal_get_write_access(handle, frame->bh); if (err) goto journal_error; data2 = bh2->b_data; /* create map in the end of data2 block */ map = (struct dx_map_entry *) (data2 + blocksize); count = dx_make_map((struct ext4_dir_entry_2 *) data1, blocksize, hinfo, map); map -= count; dx_sort_map(map, count); /* Split the existing block in the middle, size-wise */ size = 0; move = 0; for (i = count-1; i >= 0; i--) { /* is more than half of this entry in 2nd half of the block? */ if (size + map[i].size/2 > blocksize/2) break; size += map[i].size; move++; } /* map index at which we will split */ split = count - move; hash2 = map[split].hash; continued = hash2 == map[split - 1].hash; dxtrace(printk(KERN_INFO "Split block %lu at %x, %i/%i\n", (unsigned long)dx_get_block(frame->at), hash2, split, count-split)); /* Fancy dance to stay within two buffers */ de2 = dx_move_dirents(data1, data2, map + split, count - split, blocksize); de = dx_pack_dirents(data1, blocksize); de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) - (char *) de, blocksize); de2->rec_len = ext4_rec_len_to_disk(data2 + (blocksize - csum_size) - (char *) de2, blocksize); if (csum_size) { t = EXT4_DIRENT_TAIL(data2, blocksize); initialize_dirent_tail(t, blocksize); t = EXT4_DIRENT_TAIL(data1, blocksize); initialize_dirent_tail(t, blocksize); } dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data1, blocksize, 1)); dxtrace(dx_show_leaf (hinfo, (struct ext4_dir_entry_2 *) data2, blocksize, 1)); /* Which block gets the new entry? */ if (hinfo->hash >= hash2) { swap(*bh, bh2); de = de2; } dx_insert_block(frame, hash2 + continued, newblock); err = ext4_handle_dirty_dirent_node(handle, dir, bh2); if (err) goto journal_error; err = ext4_handle_dirty_dx_node(handle, dir, frame->bh); if (err) goto journal_error; brelse(bh2); dxtrace(dx_show_index("frame", frame->entries)); return de; journal_error: brelse(*bh); brelse(bh2); *bh = NULL; ext4_std_error(dir->i_sb, err); *error = err; return NULL; } int ext4_find_dest_de(struct inode *dir, struct inode *inode, struct buffer_head *bh, void *buf, int buf_size, const char *name, int namelen, struct ext4_dir_entry_2 **dest_de) { struct ext4_dir_entry_2 *de; unsigned short reclen = EXT4_DIR_REC_LEN(namelen); int nlen, rlen; unsigned int offset = 0; char *top; de = (struct ext4_dir_entry_2 *)buf; top = buf + buf_size - reclen; while ((char *) de <= top) { if (ext4_check_dir_entry(dir, NULL, de, bh, buf, buf_size, offset)) return -EIO; if (ext4_match(namelen, name, de)) return -EEXIST; nlen = EXT4_DIR_REC_LEN(de->name_len); rlen = ext4_rec_len_from_disk(de->rec_len, buf_size); if ((de->inode ? rlen - nlen : rlen) >= reclen) break; de = (struct ext4_dir_entry_2 *)((char *)de + rlen); offset += rlen; } if ((char *) de > top) return -ENOSPC; *dest_de = de; return 0; } void ext4_insert_dentry(struct inode *inode, struct ext4_dir_entry_2 *de, int buf_size, const char *name, int namelen) { int nlen, rlen; nlen = EXT4_DIR_REC_LEN(de->name_len); rlen = ext4_rec_len_from_disk(de->rec_len, buf_size); if (de->inode) { struct ext4_dir_entry_2 *de1 = (struct ext4_dir_entry_2 *)((char *)de + nlen); de1->rec_len = ext4_rec_len_to_disk(rlen - nlen, buf_size); de->rec_len = ext4_rec_len_to_disk(nlen, buf_size); de = de1; } de->file_type = EXT4_FT_UNKNOWN; de->inode = cpu_to_le32(inode->i_ino); ext4_set_de_type(inode->i_sb, de, inode->i_mode); de->name_len = namelen; memcpy(de->name, name, namelen); } /* * Add a new entry into a directory (leaf) block. If de is non-NULL, * it points to a directory entry which is guaranteed to be large * enough for new directory entry. If de is NULL, then * add_dirent_to_buf will attempt search the directory block for * space. It will return -ENOSPC if no space is available, and -EIO * and -EEXIST if directory entry already exists. */ static int add_dirent_to_buf(handle_t *handle, struct dentry *dentry, struct inode *inode, struct ext4_dir_entry_2 *de, struct buffer_head *bh) { struct inode *dir = dentry->d_parent->d_inode; const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; unsigned int blocksize = dir->i_sb->s_blocksize; int csum_size = 0; int err; if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); if (!de) { err = ext4_find_dest_de(dir, inode, bh, bh->b_data, blocksize - csum_size, name, namelen, &de); if (err) return err; } BUFFER_TRACE(bh, "get_write_access"); err = ext4_journal_get_write_access(handle, bh); if (err) { ext4_std_error(dir->i_sb, err); return err; } /* By now the buffer is marked for journaling */ ext4_insert_dentry(inode, de, blocksize, name, namelen); /* * XXX shouldn't update any times until successful * completion of syscall, but too many callers depend * on this. * * XXX similarly, too many callers depend on * ext4_new_inode() setting the times, but error * recovery deletes the inode, so the worst that can * happen is that the times are slightly out of date * and/or different from the directory change time. */ dir->i_mtime = dir->i_ctime = ext4_current_time(dir); ext4_update_dx_flag(dir); dir->i_version++; ext4_mark_inode_dirty(handle, dir); BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_dirent_node(handle, dir, bh); if (err) ext4_std_error(dir->i_sb, err); return 0; } /* * This converts a one block unindexed directory to a 3 block indexed * directory, and adds the dentry to the indexed directory. */ static int make_indexed_dir(handle_t *handle, struct dentry *dentry, struct inode *inode, struct buffer_head *bh) { struct inode *dir = dentry->d_parent->d_inode; const char *name = dentry->d_name.name; int namelen = dentry->d_name.len; struct buffer_head *bh2; struct dx_root *root; struct dx_frame frames[2], *frame; struct dx_entry *entries; struct ext4_dir_entry_2 *de, *de2; struct ext4_dir_entry_tail *t; char *data1, *top; unsigned len; int retval; unsigned blocksize; struct dx_hash_info hinfo; ext4_lblk_t block; struct fake_dirent *fde; int csum_size = 0; if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); blocksize = dir->i_sb->s_blocksize; dxtrace(printk(KERN_DEBUG "Creating index: inode %lu\n", dir->i_ino)); retval = ext4_journal_get_write_access(handle, bh); if (retval) { ext4_std_error(dir->i_sb, retval); brelse(bh); return retval; } root = (struct dx_root *) bh->b_data; /* The 0th block becomes the root, move the dirents out */ fde = &root->dotdot; de = (struct ext4_dir_entry_2 *)((char *)fde + ext4_rec_len_from_disk(fde->rec_len, blocksize)); if ((char *) de >= (((char *) root) + blocksize)) { EXT4_ERROR_INODE(dir, "invalid rec_len for '..'"); brelse(bh); return -EIO; } len = ((char *) root) + (blocksize - csum_size) - (char *) de; /* Allocate new block for the 0th block's dirents */ bh2 = ext4_append(handle, dir, &block); if (IS_ERR(bh2)) { brelse(bh); return PTR_ERR(bh2); } ext4_set_inode_flag(dir, EXT4_INODE_INDEX); data1 = bh2->b_data; memcpy (data1, de, len); de = (struct ext4_dir_entry_2 *) data1; top = data1 + len; while ((char *)(de2 = ext4_next_entry(de, blocksize)) < top) de = de2; de->rec_len = ext4_rec_len_to_disk(data1 + (blocksize - csum_size) - (char *) de, blocksize); if (csum_size) { t = EXT4_DIRENT_TAIL(data1, blocksize); initialize_dirent_tail(t, blocksize); } /* Initialize the root; the dot dirents already exist */ de = (struct ext4_dir_entry_2 *) (&root->dotdot); de->rec_len = ext4_rec_len_to_disk(blocksize - EXT4_DIR_REC_LEN(2), blocksize); memset (&root->info, 0, sizeof(root->info)); root->info.info_length = sizeof(root->info); root->info.hash_version = EXT4_SB(dir->i_sb)->s_def_hash_version; entries = root->entries; dx_set_block(entries, 1); dx_set_count(entries, 1); dx_set_limit(entries, dx_root_limit(dir, sizeof(root->info))); /* Initialize as for dx_probe */ hinfo.hash_version = root->info.hash_version; if (hinfo.hash_version <= DX_HASH_TEA) hinfo.hash_version += EXT4_SB(dir->i_sb)->s_hash_unsigned; hinfo.seed = EXT4_SB(dir->i_sb)->s_hash_seed; ext4fs_dirhash(name, namelen, &hinfo); frame = frames; frame->entries = entries; frame->at = entries; frame->bh = bh; bh = bh2; ext4_handle_dirty_dx_node(handle, dir, frame->bh); ext4_handle_dirty_dirent_node(handle, dir, bh); de = do_split(handle,dir, &bh, frame, &hinfo, &retval); if (!de) { /* * Even if the block split failed, we have to properly write * out all the changes we did so far. Otherwise we can end up * with corrupted filesystem. */ ext4_mark_inode_dirty(handle, dir); dx_release(frames); return retval; } dx_release(frames); retval = add_dirent_to_buf(handle, dentry, inode, de, bh); brelse(bh); return retval; } /* * ext4_add_entry() * * adds a file entry to the specified directory, using the same * semantics as ext4_find_entry(). It returns NULL if it failed. * * NOTE!! The inode part of 'de' is left at 0 - which means you * may not sleep between calling this and putting something into * the entry, as someone else might have used it while you slept. */ static int ext4_add_entry(handle_t *handle, struct dentry *dentry, struct inode *inode) { struct inode *dir = dentry->d_parent->d_inode; struct buffer_head *bh; struct ext4_dir_entry_2 *de; struct ext4_dir_entry_tail *t; struct super_block *sb; int retval; int dx_fallback=0; unsigned blocksize; ext4_lblk_t block, blocks; int csum_size = 0; if (EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); sb = dir->i_sb; blocksize = sb->s_blocksize; if (!dentry->d_name.len) return -EINVAL; if (ext4_has_inline_data(dir)) { retval = ext4_try_add_inline_entry(handle, dentry, inode); if (retval < 0) return retval; if (retval == 1) { retval = 0; return retval; } } if (is_dx(dir)) { retval = ext4_dx_add_entry(handle, dentry, inode); if (!retval || (retval != ERR_BAD_DX_DIR)) return retval; ext4_clear_inode_flag(dir, EXT4_INODE_INDEX); dx_fallback++; ext4_mark_inode_dirty(handle, dir); } blocks = dir->i_size >> sb->s_blocksize_bits; for (block = 0; block < blocks; block++) { bh = ext4_read_dirblock(dir, block, DIRENT); if (IS_ERR(bh)) return PTR_ERR(bh); retval = add_dirent_to_buf(handle, dentry, inode, NULL, bh); if (retval != -ENOSPC) { brelse(bh); return retval; } if (blocks == 1 && !dx_fallback && EXT4_HAS_COMPAT_FEATURE(sb, EXT4_FEATURE_COMPAT_DIR_INDEX)) return make_indexed_dir(handle, dentry, inode, bh); brelse(bh); } bh = ext4_append(handle, dir, &block); if (IS_ERR(bh)) return PTR_ERR(bh); de = (struct ext4_dir_entry_2 *) bh->b_data; de->inode = 0; de->rec_len = ext4_rec_len_to_disk(blocksize - csum_size, blocksize); if (csum_size) { t = EXT4_DIRENT_TAIL(bh->b_data, blocksize); initialize_dirent_tail(t, blocksize); } retval = add_dirent_to_buf(handle, dentry, inode, de, bh); brelse(bh); if (retval == 0) ext4_set_inode_state(inode, EXT4_STATE_NEWENTRY); return retval; } /* * Returns 0 for success, or a negative error value */ static int ext4_dx_add_entry(handle_t *handle, struct dentry *dentry, struct inode *inode) { struct dx_frame frames[2], *frame; struct dx_entry *entries, *at; struct dx_hash_info hinfo; struct buffer_head *bh; struct inode *dir = dentry->d_parent->d_inode; struct super_block *sb = dir->i_sb; struct ext4_dir_entry_2 *de; int err; frame = dx_probe(&dentry->d_name, dir, &hinfo, frames, &err); if (!frame) return err; entries = frame->entries; at = frame->at; bh = ext4_read_dirblock(dir, dx_get_block(frame->at), DIRENT); if (IS_ERR(bh)) { err = PTR_ERR(bh); bh = NULL; goto cleanup; } BUFFER_TRACE(bh, "get_write_access"); err = ext4_journal_get_write_access(handle, bh); if (err) goto journal_error; err = add_dirent_to_buf(handle, dentry, inode, NULL, bh); if (err != -ENOSPC) goto cleanup; /* Block full, should compress but for now just split */ dxtrace(printk(KERN_DEBUG "using %u of %u node entries\n", dx_get_count(entries), dx_get_limit(entries))); /* Need to split index? */ if (dx_get_count(entries) == dx_get_limit(entries)) { ext4_lblk_t newblock; unsigned icount = dx_get_count(entries); int levels = frame - frames; struct dx_entry *entries2; struct dx_node *node2; struct buffer_head *bh2; if (levels && (dx_get_count(frames->entries) == dx_get_limit(frames->entries))) { ext4_warning(sb, "Directory index full!"); err = -ENOSPC; goto cleanup; } bh2 = ext4_append(handle, dir, &newblock); if (IS_ERR(bh2)) { err = PTR_ERR(bh2); goto cleanup; } node2 = (struct dx_node *)(bh2->b_data); entries2 = node2->entries; memset(&node2->fake, 0, sizeof(struct fake_dirent)); node2->fake.rec_len = ext4_rec_len_to_disk(sb->s_blocksize, sb->s_blocksize); BUFFER_TRACE(frame->bh, "get_write_access"); err = ext4_journal_get_write_access(handle, frame->bh); if (err) goto journal_error; if (levels) { unsigned icount1 = icount/2, icount2 = icount - icount1; unsigned hash2 = dx_get_hash(entries + icount1); dxtrace(printk(KERN_DEBUG "Split index %i/%i\n", icount1, icount2)); BUFFER_TRACE(frame->bh, "get_write_access"); /* index root */ err = ext4_journal_get_write_access(handle, frames[0].bh); if (err) goto journal_error; memcpy((char *) entries2, (char *) (entries + icount1), icount2 * sizeof(struct dx_entry)); dx_set_count(entries, icount1); dx_set_count(entries2, icount2); dx_set_limit(entries2, dx_node_limit(dir)); /* Which index block gets the new entry? */ if (at - entries >= icount1) { frame->at = at = at - entries - icount1 + entries2; frame->entries = entries = entries2; swap(frame->bh, bh2); } dx_insert_block(frames + 0, hash2, newblock); dxtrace(dx_show_index("node", frames[1].entries)); dxtrace(dx_show_index("node", ((struct dx_node *) bh2->b_data)->entries)); err = ext4_handle_dirty_dx_node(handle, dir, bh2); if (err) goto journal_error; brelse (bh2); } else { dxtrace(printk(KERN_DEBUG "Creating second level index...\n")); memcpy((char *) entries2, (char *) entries, icount * sizeof(struct dx_entry)); dx_set_limit(entries2, dx_node_limit(dir)); /* Set up root */ dx_set_count(entries, 1); dx_set_block(entries + 0, newblock); ((struct dx_root *) frames[0].bh->b_data)->info.indirect_levels = 1; /* Add new access path frame */ frame = frames + 1; frame->at = at = at - entries + entries2; frame->entries = entries = entries2; frame->bh = bh2; err = ext4_journal_get_write_access(handle, frame->bh); if (err) goto journal_error; } err = ext4_handle_dirty_dx_node(handle, dir, frames[0].bh); if (err) { ext4_std_error(inode->i_sb, err); goto cleanup; } } de = do_split(handle, dir, &bh, frame, &hinfo, &err); if (!de) goto cleanup; err = add_dirent_to_buf(handle, dentry, inode, de, bh); goto cleanup; journal_error: ext4_std_error(dir->i_sb, err); cleanup: brelse(bh); dx_release(frames); return err; } /* * ext4_generic_delete_entry deletes a directory entry by merging it * with the previous entry */ int ext4_generic_delete_entry(handle_t *handle, struct inode *dir, struct ext4_dir_entry_2 *de_del, struct buffer_head *bh, void *entry_buf, int buf_size, int csum_size) { struct ext4_dir_entry_2 *de, *pde; unsigned int blocksize = dir->i_sb->s_blocksize; int i; i = 0; pde = NULL; de = (struct ext4_dir_entry_2 *)entry_buf; while (i < buf_size - csum_size) { if (ext4_check_dir_entry(dir, NULL, de, bh, bh->b_data, bh->b_size, i)) return -EIO; if (de == de_del) { if (pde) pde->rec_len = ext4_rec_len_to_disk( ext4_rec_len_from_disk(pde->rec_len, blocksize) + ext4_rec_len_from_disk(de->rec_len, blocksize), blocksize); else de->inode = 0; dir->i_version++; return 0; } i += ext4_rec_len_from_disk(de->rec_len, blocksize); pde = de; de = ext4_next_entry(de, blocksize); } return -ENOENT; } static int ext4_delete_entry(handle_t *handle, struct inode *dir, struct ext4_dir_entry_2 *de_del, struct buffer_head *bh) { int err, csum_size = 0; if (ext4_has_inline_data(dir)) { int has_inline_data = 1; err = ext4_delete_inline_entry(handle, dir, de_del, bh, &has_inline_data); if (has_inline_data) return err; } if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); BUFFER_TRACE(bh, "get_write_access"); err = ext4_journal_get_write_access(handle, bh); if (unlikely(err)) goto out; err = ext4_generic_delete_entry(handle, dir, de_del, bh, bh->b_data, dir->i_sb->s_blocksize, csum_size); if (err) goto out; BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_dirent_node(handle, dir, bh); if (unlikely(err)) goto out; return 0; out: if (err != -ENOENT) ext4_std_error(dir->i_sb, err); return err; } /* * DIR_NLINK feature is set if 1) nlinks > EXT4_LINK_MAX or 2) nlinks == 2, * since this indicates that nlinks count was previously 1. */ static void ext4_inc_count(handle_t *handle, struct inode *inode) { inc_nlink(inode); if (is_dx(inode) && inode->i_nlink > 1) { /* limit is 16-bit i_links_count */ if (inode->i_nlink >= EXT4_LINK_MAX || inode->i_nlink == 2) { set_nlink(inode, 1); EXT4_SET_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_DIR_NLINK); } } } /* * If a directory had nlink == 1, then we should let it be 1. This indicates * directory has >EXT4_LINK_MAX subdirs. */ static void ext4_dec_count(handle_t *handle, struct inode *inode) { if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 2) drop_nlink(inode); } static int ext4_add_nondir(handle_t *handle, struct dentry *dentry, struct inode *inode) { int err = ext4_add_entry(handle, dentry, inode); if (!err) { ext4_mark_inode_dirty(handle, inode); unlock_new_inode(inode); d_instantiate(dentry, inode); return 0; } drop_nlink(inode); unlock_new_inode(inode); iput(inode); return err; } /* * By the time this is called, we already have created * the directory cache entry for the new file, but it * is so far negative - it has no inode. * * If the create succeeds, we fill in the inode information * with d_instantiate(). */ static int ext4_create(struct inode *dir, struct dentry *dentry, umode_t mode, bool excl) { handle_t *handle; struct inode *inode; int err, credits, retries = 0; dquot_initialize(dir); credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3); retry: inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0, NULL, EXT4_HT_DIR, credits); handle = ext4_journal_current_handle(); err = PTR_ERR(inode); if (!IS_ERR(inode)) { inode->i_op = &ext4_file_inode_operations; inode->i_fop = &ext4_file_operations; ext4_set_aops(inode); err = ext4_add_nondir(handle, dentry, inode); if (!err && IS_DIRSYNC(dir)) ext4_handle_sync(handle); } if (handle) ext4_journal_stop(handle); if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) goto retry; return err; } static int ext4_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t rdev) { handle_t *handle; struct inode *inode; int err, credits, retries = 0; if (!new_valid_dev(rdev)) return -EINVAL; dquot_initialize(dir); credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3); retry: inode = ext4_new_inode_start_handle(dir, mode, &dentry->d_name, 0, NULL, EXT4_HT_DIR, credits); handle = ext4_journal_current_handle(); err = PTR_ERR(inode); if (!IS_ERR(inode)) { init_special_inode(inode, inode->i_mode, rdev); inode->i_op = &ext4_special_inode_operations; err = ext4_add_nondir(handle, dentry, inode); if (!err && IS_DIRSYNC(dir)) ext4_handle_sync(handle); } if (handle) ext4_journal_stop(handle); if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) goto retry; return err; } struct ext4_dir_entry_2 *ext4_init_dot_dotdot(struct inode *inode, struct ext4_dir_entry_2 *de, int blocksize, int csum_size, unsigned int parent_ino, int dotdot_real_len) { de->inode = cpu_to_le32(inode->i_ino); de->name_len = 1; de->rec_len = ext4_rec_len_to_disk(EXT4_DIR_REC_LEN(de->name_len), blocksize); strcpy(de->name, "."); ext4_set_de_type(inode->i_sb, de, S_IFDIR); de = ext4_next_entry(de, blocksize); de->inode = cpu_to_le32(parent_ino); de->name_len = 2; if (!dotdot_real_len) de->rec_len = ext4_rec_len_to_disk(blocksize - (csum_size + EXT4_DIR_REC_LEN(1)), blocksize); else de->rec_len = ext4_rec_len_to_disk( EXT4_DIR_REC_LEN(de->name_len), blocksize); strcpy(de->name, ".."); ext4_set_de_type(inode->i_sb, de, S_IFDIR); return ext4_next_entry(de, blocksize); } static int ext4_init_new_dir(handle_t *handle, struct inode *dir, struct inode *inode) { struct buffer_head *dir_block = NULL; struct ext4_dir_entry_2 *de; struct ext4_dir_entry_tail *t; ext4_lblk_t block = 0; unsigned int blocksize = dir->i_sb->s_blocksize; int csum_size = 0; int err; if (EXT4_HAS_RO_COMPAT_FEATURE(dir->i_sb, EXT4_FEATURE_RO_COMPAT_METADATA_CSUM)) csum_size = sizeof(struct ext4_dir_entry_tail); if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { err = ext4_try_create_inline_dir(handle, dir, inode); if (err < 0 && err != -ENOSPC) goto out; if (!err) goto out; } inode->i_size = 0; dir_block = ext4_append(handle, inode, &block); if (IS_ERR(dir_block)) return PTR_ERR(dir_block); BUFFER_TRACE(dir_block, "get_write_access"); err = ext4_journal_get_write_access(handle, dir_block); if (err) goto out; de = (struct ext4_dir_entry_2 *)dir_block->b_data; ext4_init_dot_dotdot(inode, de, blocksize, csum_size, dir->i_ino, 0); set_nlink(inode, 2); if (csum_size) { t = EXT4_DIRENT_TAIL(dir_block->b_data, blocksize); initialize_dirent_tail(t, blocksize); } BUFFER_TRACE(dir_block, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_dirent_node(handle, inode, dir_block); if (err) goto out; set_buffer_verified(dir_block); out: brelse(dir_block); return err; } static int ext4_mkdir(struct inode *dir, struct dentry *dentry, umode_t mode) { handle_t *handle; struct inode *inode; int err, credits, retries = 0; if (EXT4_DIR_LINK_MAX(dir)) return -EMLINK; dquot_initialize(dir); credits = (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3); retry: inode = ext4_new_inode_start_handle(dir, S_IFDIR | mode, &dentry->d_name, 0, NULL, EXT4_HT_DIR, credits); handle = ext4_journal_current_handle(); err = PTR_ERR(inode); if (IS_ERR(inode)) goto out_stop; inode->i_op = &ext4_dir_inode_operations; inode->i_fop = &ext4_dir_operations; err = ext4_init_new_dir(handle, dir, inode); if (err) goto out_clear_inode; err = ext4_mark_inode_dirty(handle, inode); if (!err) err = ext4_add_entry(handle, dentry, inode); if (err) { out_clear_inode: clear_nlink(inode); unlock_new_inode(inode); ext4_mark_inode_dirty(handle, inode); iput(inode); goto out_stop; } ext4_inc_count(handle, dir); ext4_update_dx_flag(dir); err = ext4_mark_inode_dirty(handle, dir); if (err) goto out_clear_inode; unlock_new_inode(inode); d_instantiate(dentry, inode); if (IS_DIRSYNC(dir)) ext4_handle_sync(handle); out_stop: if (handle) ext4_journal_stop(handle); if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) goto retry; return err; } /* * routine to check that the specified directory is empty (for rmdir) */ static int empty_dir(struct inode *inode) { unsigned int offset; struct buffer_head *bh; struct ext4_dir_entry_2 *de, *de1; struct super_block *sb; int err = 0; if (ext4_has_inline_data(inode)) { int has_inline_data = 1; err = empty_inline_dir(inode, &has_inline_data); if (has_inline_data) return err; } sb = inode->i_sb; if (inode->i_size < EXT4_DIR_REC_LEN(1) + EXT4_DIR_REC_LEN(2)) { EXT4_ERROR_INODE(inode, "invalid size"); return 1; } bh = ext4_read_dirblock(inode, 0, EITHER); if (IS_ERR(bh)) return 1; de = (struct ext4_dir_entry_2 *) bh->b_data; de1 = ext4_next_entry(de, sb->s_blocksize); if (le32_to_cpu(de->inode) != inode->i_ino || !le32_to_cpu(de1->inode) || strcmp(".", de->name) || strcmp("..", de1->name)) { ext4_warning(inode->i_sb, "bad directory (dir #%lu) - no `.' or `..'", inode->i_ino); brelse(bh); return 1; } offset = ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize) + ext4_rec_len_from_disk(de1->rec_len, sb->s_blocksize); de = ext4_next_entry(de1, sb->s_blocksize); while (offset < inode->i_size) { if (!bh || (void *) de >= (void *) (bh->b_data+sb->s_blocksize)) { unsigned int lblock; err = 0; brelse(bh); lblock = offset >> EXT4_BLOCK_SIZE_BITS(sb); bh = ext4_read_dirblock(inode, lblock, EITHER); if (IS_ERR(bh)) return 1; de = (struct ext4_dir_entry_2 *) bh->b_data; } if (ext4_check_dir_entry(inode, NULL, de, bh, bh->b_data, bh->b_size, offset)) { de = (struct ext4_dir_entry_2 *)(bh->b_data + sb->s_blocksize); offset = (offset | (sb->s_blocksize - 1)) + 1; continue; } if (le32_to_cpu(de->inode)) { brelse(bh); return 0; } offset += ext4_rec_len_from_disk(de->rec_len, sb->s_blocksize); de = ext4_next_entry(de, sb->s_blocksize); } brelse(bh); return 1; } /* ext4_orphan_add() links an unlinked or truncated inode into a list of * such inodes, starting at the superblock, in case we crash before the * file is closed/deleted, or in case the inode truncate spans multiple * transactions and the last transaction is not recovered after a crash. * * At filesystem recovery time, we walk this list deleting unlinked * inodes and truncating linked inodes in ext4_orphan_cleanup(). */ int ext4_orphan_add(handle_t *handle, struct inode *inode) { struct super_block *sb = inode->i_sb; struct ext4_iloc iloc; int err = 0, rc; if (!EXT4_SB(sb)->s_journal) return 0; mutex_lock(&EXT4_SB(sb)->s_orphan_lock); if (!list_empty(&EXT4_I(inode)->i_orphan)) goto out_unlock; /* * Orphan handling is only valid for files with data blocks * being truncated, or files being unlinked. Note that we either * hold i_mutex, or the inode can not be referenced from outside, * so i_nlink should not be bumped due to race */ J_ASSERT((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)) || inode->i_nlink == 0); BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_unlock; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_unlock; /* * Due to previous errors inode may be already a part of on-disk * orphan list. If so skip on-disk list modification. */ if (NEXT_ORPHAN(inode) && NEXT_ORPHAN(inode) <= (le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count))) goto mem_insert; /* Insert this inode at the head of the on-disk orphan list... */ NEXT_ORPHAN(inode) = le32_to_cpu(EXT4_SB(sb)->s_es->s_last_orphan); EXT4_SB(sb)->s_es->s_last_orphan = cpu_to_le32(inode->i_ino); err = ext4_handle_dirty_super(handle, sb); rc = ext4_mark_iloc_dirty(handle, inode, &iloc); if (!err) err = rc; /* Only add to the head of the in-memory list if all the * previous operations succeeded. If the orphan_add is going to * fail (possibly taking the journal offline), we can't risk * leaving the inode on the orphan list: stray orphan-list * entries can cause panics at unmount time. * * This is safe: on error we're going to ignore the orphan list * anyway on the next recovery. */ mem_insert: if (!err) list_add(&EXT4_I(inode)->i_orphan, &EXT4_SB(sb)->s_orphan); jbd_debug(4, "superblock will point to %lu\n", inode->i_ino); jbd_debug(4, "orphan inode %lu will point to %d\n", inode->i_ino, NEXT_ORPHAN(inode)); out_unlock: mutex_unlock(&EXT4_SB(sb)->s_orphan_lock); ext4_std_error(inode->i_sb, err); return err; } /* * ext4_orphan_del() removes an unlinked or truncated inode from the list * of such inodes stored on disk, because it is finally being cleaned up. */ int ext4_orphan_del(handle_t *handle, struct inode *inode) { struct list_head *prev; struct ext4_inode_info *ei = EXT4_I(inode); struct ext4_sb_info *sbi; __u32 ino_next; struct ext4_iloc iloc; int err = 0; if ((!EXT4_SB(inode->i_sb)->s_journal) && !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) return 0; mutex_lock(&EXT4_SB(inode->i_sb)->s_orphan_lock); if (list_empty(&ei->i_orphan)) goto out; ino_next = NEXT_ORPHAN(inode); prev = ei->i_orphan.prev; sbi = EXT4_SB(inode->i_sb); jbd_debug(4, "remove inode %lu from orphan list\n", inode->i_ino); list_del_init(&ei->i_orphan); /* If we're on an error path, we may not have a valid * transaction handle with which to update the orphan list on * disk, but we still need to remove the inode from the linked * list in memory. */ if (!handle) goto out; err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) goto out_err; if (prev == &sbi->s_orphan) { jbd_debug(4, "superblock will point to %u\n", ino_next); BUFFER_TRACE(sbi->s_sbh, "get_write_access"); err = ext4_journal_get_write_access(handle, sbi->s_sbh); if (err) goto out_brelse; sbi->s_es->s_last_orphan = cpu_to_le32(ino_next); err = ext4_handle_dirty_super(handle, inode->i_sb); } else { struct ext4_iloc iloc2; struct inode *i_prev = &list_entry(prev, struct ext4_inode_info, i_orphan)->vfs_inode; jbd_debug(4, "orphan inode %lu will point to %u\n", i_prev->i_ino, ino_next); err = ext4_reserve_inode_write(handle, i_prev, &iloc2); if (err) goto out_brelse; NEXT_ORPHAN(i_prev) = ino_next; err = ext4_mark_iloc_dirty(handle, i_prev, &iloc2); } if (err) goto out_brelse; NEXT_ORPHAN(inode) = 0; err = ext4_mark_iloc_dirty(handle, inode, &iloc); out_err: ext4_std_error(inode->i_sb, err); out: mutex_unlock(&EXT4_SB(inode->i_sb)->s_orphan_lock); return err; out_brelse: brelse(iloc.bh); goto out_err; } static int ext4_rmdir(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode; struct buffer_head *bh; struct ext4_dir_entry_2 *de; handle_t *handle = NULL; /* Initialize quotas before so that eventual writes go in * separate transaction */ dquot_initialize(dir); dquot_initialize(dentry->d_inode); retval = -ENOENT; bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL); if (!bh) goto end_rmdir; inode = dentry->d_inode; retval = -EIO; if (le32_to_cpu(de->inode) != inode->i_ino) goto end_rmdir; retval = -ENOTEMPTY; if (!empty_dir(inode)) goto end_rmdir; handle = ext4_journal_start(dir, EXT4_HT_DIR, EXT4_DATA_TRANS_BLOCKS(dir->i_sb)); if (IS_ERR(handle)) { retval = PTR_ERR(handle); handle = NULL; goto end_rmdir; } if (IS_DIRSYNC(dir)) ext4_handle_sync(handle); retval = ext4_delete_entry(handle, dir, de, bh); if (retval) goto end_rmdir; if (!EXT4_DIR_LINK_EMPTY(inode)) ext4_warning(inode->i_sb, "empty directory has too many links (%d)", inode->i_nlink); inode->i_version++; clear_nlink(inode); /* There's no need to set i_disksize: the fact that i_nlink is * zero will ensure that the right thing happens during any * recovery. */ inode->i_size = 0; ext4_orphan_add(handle, inode); inode->i_ctime = dir->i_ctime = dir->i_mtime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); ext4_dec_count(handle, dir); ext4_update_dx_flag(dir); ext4_mark_inode_dirty(handle, dir); end_rmdir: brelse(bh); if (handle) ext4_journal_stop(handle); return retval; } static int ext4_unlink(struct inode *dir, struct dentry *dentry) { int retval; struct inode *inode; struct buffer_head *bh; struct ext4_dir_entry_2 *de; handle_t *handle = NULL; trace_ext4_unlink_enter(dir, dentry); /* Initialize quotas before so that eventual writes go * in separate transaction */ dquot_initialize(dir); dquot_initialize(dentry->d_inode); retval = -ENOENT; bh = ext4_find_entry(dir, &dentry->d_name, &de, NULL); if (!bh) goto end_unlink; inode = dentry->d_inode; retval = -EIO; if (le32_to_cpu(de->inode) != inode->i_ino) goto end_unlink; handle = ext4_journal_start(dir, EXT4_HT_DIR, EXT4_DATA_TRANS_BLOCKS(dir->i_sb)); if (IS_ERR(handle)) { retval = PTR_ERR(handle); handle = NULL; goto end_unlink; } if (IS_DIRSYNC(dir)) ext4_handle_sync(handle); if (!inode->i_nlink) { ext4_warning(inode->i_sb, "Deleting nonexistent file (%lu), %d", inode->i_ino, inode->i_nlink); set_nlink(inode, 1); } retval = ext4_delete_entry(handle, dir, de, bh); if (retval) goto end_unlink; dir->i_ctime = dir->i_mtime = ext4_current_time(dir); ext4_update_dx_flag(dir); ext4_mark_inode_dirty(handle, dir); drop_nlink(inode); if (!inode->i_nlink) ext4_orphan_add(handle, inode); inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); retval = 0; end_unlink: brelse(bh); if (handle) ext4_journal_stop(handle); trace_ext4_unlink_exit(dentry, retval); return retval; } static int ext4_symlink(struct inode *dir, struct dentry *dentry, const char *symname) { handle_t *handle; struct inode *inode; int l, err, retries = 0; int credits; l = strlen(symname)+1; if (l > dir->i_sb->s_blocksize) return -ENAMETOOLONG; dquot_initialize(dir); if (l > EXT4_N_BLOCKS * 4) { /* * For non-fast symlinks, we just allocate inode and put it on * orphan list in the first transaction => we need bitmap, * group descriptor, sb, inode block, quota blocks, and * possibly selinux xattr blocks. */ credits = 4 + EXT4_MAXQUOTAS_INIT_BLOCKS(dir->i_sb) + EXT4_XATTR_TRANS_BLOCKS; } else { /* * Fast symlink. We have to add entry to directory * (EXT4_DATA_TRANS_BLOCKS + EXT4_INDEX_EXTRA_TRANS_BLOCKS), * allocate new inode (bitmap, group descriptor, inode block, * quota blocks, sb is already counted in previous macros). */ credits = EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 3; } retry: inode = ext4_new_inode_start_handle(dir, S_IFLNK|S_IRWXUGO, &dentry->d_name, 0, NULL, EXT4_HT_DIR, credits); handle = ext4_journal_current_handle(); err = PTR_ERR(inode); if (IS_ERR(inode)) goto out_stop; if (l > EXT4_N_BLOCKS * 4) { inode->i_op = &ext4_symlink_inode_operations; ext4_set_aops(inode); /* * We cannot call page_symlink() with transaction started * because it calls into ext4_write_begin() which can wait * for transaction commit if we are running out of space * and thus we deadlock. So we have to stop transaction now * and restart it when symlink contents is written. * * To keep fs consistent in case of crash, we have to put inode * to orphan list in the mean time. */ drop_nlink(inode); err = ext4_orphan_add(handle, inode); ext4_journal_stop(handle); if (err) goto err_drop_inode; err = __page_symlink(inode, symname, l, 1); if (err) goto err_drop_inode; /* * Now inode is being linked into dir (EXT4_DATA_TRANS_BLOCKS * + EXT4_INDEX_EXTRA_TRANS_BLOCKS), inode is also modified */ handle = ext4_journal_start(dir, EXT4_HT_DIR, EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 1); if (IS_ERR(handle)) { err = PTR_ERR(handle); goto err_drop_inode; } set_nlink(inode, 1); err = ext4_orphan_del(handle, inode); if (err) { ext4_journal_stop(handle); clear_nlink(inode); goto err_drop_inode; } } else { /* clear the extent format for fast symlink */ ext4_clear_inode_flag(inode, EXT4_INODE_EXTENTS); inode->i_op = &ext4_fast_symlink_inode_operations; memcpy((char *)&EXT4_I(inode)->i_data, symname, l); inode->i_size = l-1; } EXT4_I(inode)->i_disksize = inode->i_size; err = ext4_add_nondir(handle, dentry, inode); if (!err && IS_DIRSYNC(dir)) ext4_handle_sync(handle); out_stop: if (handle) ext4_journal_stop(handle); if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) goto retry; return err; err_drop_inode: unlock_new_inode(inode); iput(inode); return err; } static int ext4_link(struct dentry *old_dentry, struct inode *dir, struct dentry *dentry) { handle_t *handle; struct inode *inode = old_dentry->d_inode; int err, retries = 0; if (inode->i_nlink >= EXT4_LINK_MAX) return -EMLINK; dquot_initialize(dir); retry: handle = ext4_journal_start(dir, EXT4_HT_DIR, (EXT4_DATA_TRANS_BLOCKS(dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS)); if (IS_ERR(handle)) return PTR_ERR(handle); if (IS_DIRSYNC(dir)) ext4_handle_sync(handle); inode->i_ctime = ext4_current_time(inode); ext4_inc_count(handle, inode); ihold(inode); err = ext4_add_entry(handle, dentry, inode); if (!err) { ext4_mark_inode_dirty(handle, inode); d_instantiate(dentry, inode); } else { drop_nlink(inode); iput(inode); } ext4_journal_stop(handle); if (err == -ENOSPC && ext4_should_retry_alloc(dir->i_sb, &retries)) goto retry; return err; } /* * Try to find buffer head where contains the parent block. * It should be the inode block if it is inlined or the 1st block * if it is a normal dir. */ static struct buffer_head *ext4_get_first_dir_block(handle_t *handle, struct inode *inode, int *retval, struct ext4_dir_entry_2 **parent_de, int *inlined) { struct buffer_head *bh; if (!ext4_has_inline_data(inode)) { bh = ext4_read_dirblock(inode, 0, EITHER); if (IS_ERR(bh)) { *retval = PTR_ERR(bh); return NULL; } *parent_de = ext4_next_entry( (struct ext4_dir_entry_2 *)bh->b_data, inode->i_sb->s_blocksize); return bh; } *inlined = 1; return ext4_get_first_inline_block(inode, parent_de, retval); } /* * Anybody can rename anything with this: the permission checks are left to the * higher-level routines. */ static int ext4_rename(struct inode *old_dir, struct dentry *old_dentry, struct inode *new_dir, struct dentry *new_dentry) { handle_t *handle; struct inode *old_inode, *new_inode; struct buffer_head *old_bh, *new_bh, *dir_bh; struct ext4_dir_entry_2 *old_de, *new_de; int retval, force_da_alloc = 0; int inlined = 0, new_inlined = 0; struct ext4_dir_entry_2 *parent_de; dquot_initialize(old_dir); dquot_initialize(new_dir); old_bh = new_bh = dir_bh = NULL; /* Initialize quotas before so that eventual writes go * in separate transaction */ if (new_dentry->d_inode) dquot_initialize(new_dentry->d_inode); handle = ext4_journal_start(old_dir, EXT4_HT_DIR, (2 * EXT4_DATA_TRANS_BLOCKS(old_dir->i_sb) + EXT4_INDEX_EXTRA_TRANS_BLOCKS + 2)); if (IS_ERR(handle)) return PTR_ERR(handle); if (IS_DIRSYNC(old_dir) || IS_DIRSYNC(new_dir)) ext4_handle_sync(handle); old_bh = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de, NULL); /* * Check for inode number is _not_ due to possible IO errors. * We might rmdir the source, keep it as pwd of some process * and merrily kill the link to whatever was created under the * same name. Goodbye sticky bit ;-< */ old_inode = old_dentry->d_inode; retval = -ENOENT; if (!old_bh || le32_to_cpu(old_de->inode) != old_inode->i_ino) goto end_rename; new_inode = new_dentry->d_inode; new_bh = ext4_find_entry(new_dir, &new_dentry->d_name, &new_de, &new_inlined); if (new_bh) { if (!new_inode) { brelse(new_bh); new_bh = NULL; } } if (S_ISDIR(old_inode->i_mode)) { if (new_inode) { retval = -ENOTEMPTY; if (!empty_dir(new_inode)) goto end_rename; } retval = -EIO; dir_bh = ext4_get_first_dir_block(handle, old_inode, &retval, &parent_de, &inlined); if (!dir_bh) goto end_rename; if (le32_to_cpu(parent_de->inode) != old_dir->i_ino) goto end_rename; retval = -EMLINK; if (!new_inode && new_dir != old_dir && EXT4_DIR_LINK_MAX(new_dir)) goto end_rename; BUFFER_TRACE(dir_bh, "get_write_access"); retval = ext4_journal_get_write_access(handle, dir_bh); if (retval) goto end_rename; } if (!new_bh) { retval = ext4_add_entry(handle, new_dentry, old_inode); if (retval) goto end_rename; } else { BUFFER_TRACE(new_bh, "get write access"); retval = ext4_journal_get_write_access(handle, new_bh); if (retval) goto end_rename; new_de->inode = cpu_to_le32(old_inode->i_ino); if (EXT4_HAS_INCOMPAT_FEATURE(new_dir->i_sb, EXT4_FEATURE_INCOMPAT_FILETYPE)) new_de->file_type = old_de->file_type; new_dir->i_version++; new_dir->i_ctime = new_dir->i_mtime = ext4_current_time(new_dir); ext4_mark_inode_dirty(handle, new_dir); BUFFER_TRACE(new_bh, "call ext4_handle_dirty_metadata"); if (!new_inlined) { retval = ext4_handle_dirty_dirent_node(handle, new_dir, new_bh); if (unlikely(retval)) { ext4_std_error(new_dir->i_sb, retval); goto end_rename; } } brelse(new_bh); new_bh = NULL; } /* * Like most other Unix systems, set the ctime for inodes on a * rename. */ old_inode->i_ctime = ext4_current_time(old_inode); ext4_mark_inode_dirty(handle, old_inode); /* * ok, that's it */ if (le32_to_cpu(old_de->inode) != old_inode->i_ino || old_de->name_len != old_dentry->d_name.len || strncmp(old_de->name, old_dentry->d_name.name, old_de->name_len) || (retval = ext4_delete_entry(handle, old_dir, old_de, old_bh)) == -ENOENT) { /* old_de could have moved from under us during htree split, so * make sure that we are deleting the right entry. We might * also be pointing to a stale entry in the unused part of * old_bh so just checking inum and the name isn't enough. */ struct buffer_head *old_bh2; struct ext4_dir_entry_2 *old_de2; old_bh2 = ext4_find_entry(old_dir, &old_dentry->d_name, &old_de2, NULL); if (old_bh2) { retval = ext4_delete_entry(handle, old_dir, old_de2, old_bh2); brelse(old_bh2); } } if (retval) { ext4_warning(old_dir->i_sb, "Deleting old file (%lu), %d, error=%d", old_dir->i_ino, old_dir->i_nlink, retval); } if (new_inode) { ext4_dec_count(handle, new_inode); new_inode->i_ctime = ext4_current_time(new_inode); } old_dir->i_ctime = old_dir->i_mtime = ext4_current_time(old_dir); ext4_update_dx_flag(old_dir); if (dir_bh) { parent_de->inode = cpu_to_le32(new_dir->i_ino); BUFFER_TRACE(dir_bh, "call ext4_handle_dirty_metadata"); if (!inlined) { if (is_dx(old_inode)) { retval = ext4_handle_dirty_dx_node(handle, old_inode, dir_bh); } else { retval = ext4_handle_dirty_dirent_node(handle, old_inode, dir_bh); } } else { retval = ext4_mark_inode_dirty(handle, old_inode); } if (retval) { ext4_std_error(old_dir->i_sb, retval); goto end_rename; } ext4_dec_count(handle, old_dir); if (new_inode) { /* checked empty_dir above, can't have another parent, * ext4_dec_count() won't work for many-linked dirs */ clear_nlink(new_inode); } else { ext4_inc_count(handle, new_dir); ext4_update_dx_flag(new_dir); ext4_mark_inode_dirty(handle, new_dir); } } ext4_mark_inode_dirty(handle, old_dir); if (new_inode) { ext4_mark_inode_dirty(handle, new_inode); if (!new_inode->i_nlink) ext4_orphan_add(handle, new_inode); if (!test_opt(new_dir->i_sb, NO_AUTO_DA_ALLOC)) force_da_alloc = 1; } retval = 0; end_rename: brelse(dir_bh); brelse(old_bh); brelse(new_bh); ext4_journal_stop(handle); if (retval == 0 && force_da_alloc) ext4_alloc_da_blocks(old_inode); return retval; } /* * directories can handle most operations... */ const struct inode_operations ext4_dir_inode_operations = { .create = ext4_create, .lookup = ext4_lookup, .link = ext4_link, .unlink = ext4_unlink, .symlink = ext4_symlink, .mkdir = ext4_mkdir, .rmdir = ext4_rmdir, .mknod = ext4_mknod, .rename = ext4_rename, .setattr = ext4_setattr, .setxattr = generic_setxattr, .getxattr = generic_getxattr, .listxattr = ext4_listxattr, .removexattr = generic_removexattr, .get_acl = ext4_get_acl, .fiemap = ext4_fiemap, }; const struct inode_operations ext4_special_inode_operations = { .setattr = ext4_setattr, .setxattr = generic_setxattr, .getxattr = generic_getxattr, .listxattr = ext4_listxattr, .removexattr = generic_removexattr, .get_acl = ext4_get_acl, };
{ "content_hash": "37a02a45f589ebfd24859f5e8a23a76c", "timestamp": "", "source": "github", "line_count": 3165, "max_line_length": 95, "avg_line_length": 27.146603475513427, "alnum_prop": 0.6406266367159766, "repo_name": "Ant-Droid/android_kernel_moto_shamu_OLD", "id": "ab2f6dc44b3abf88b62902433f48a1aa78ba8561", "size": "86651", "binary": false, "copies": "762", "ref": "refs/heads/mm600", "path": "fs/ext4/namei.c", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ASP", "bytes": "4528" }, { "name": "Assembly", "bytes": "9741484" }, { "name": "Awk", "bytes": "18681" }, { "name": "C", "bytes": "467006059" }, { "name": "C++", "bytes": "3470997" }, { "name": "Clojure", "bytes": "547" }, { "name": "Groff", "bytes": "22012" }, { "name": "Lex", "bytes": "40805" }, { "name": "Makefile", "bytes": "1342516" }, { "name": "Objective-C", "bytes": "1121986" }, { "name": "Perl", "bytes": "461504" }, { "name": "Python", "bytes": "33978" }, { "name": "Scilab", "bytes": "21433" }, { "name": "Shell", "bytes": "138789" }, { "name": "SourcePawn", "bytes": "4687" }, { "name": "UnrealScript", "bytes": "6113" }, { "name": "Yacc", "bytes": "83091" } ], "symlink_target": "" }
package com.gilesc.web.registration; import com.gilesc.service.registration.RegistrationException; import com.gilesc.service.registration.RegistrationService; import org.hibernate.exception.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; @Controller @RequestMapping("/registration") public class RegistrationController { private RegistrationForm form; private RegistrationService registration; private RegistrationFormValidator validator; @RequestMapping(method = RequestMethod.GET, value = "") public ModelAndView index() { ModelAndView mv = new ModelAndView("registration/registration", "registration", new RegistrationForm()); return mv; } @RequestMapping(method = RequestMethod.POST, value = "") public String register(@Valid @ModelAttribute("registration") RegistrationForm form, BindingResult result) throws RegistrationException { validator.validate(form, result); if (result.hasErrors()) { return "registration/registration"; } else { this.form = form; registration.register(form); return "registration/registration"; } } @Autowired public void setRegistrationService(RegistrationService registration) { this.registration = registration; } @Autowired public void setValidator(RegistrationFormValidator validator) { this.validator = validator; } @ExceptionHandler(RegistrationException.class) public ModelAndView handleError(HttpServletRequest req, Exception exception) { ModelAndView mav = new ModelAndView(); mav.addObject("exception", exception.getMessage()); mav.addObject("url", req.getRequestURL()); mav.addObject("registration", form); mav.setViewName("registration/registration"); return mav; } }
{ "content_hash": "55102049d8b7c034590e668012025f25", "timestamp": "", "source": "github", "line_count": 65, "max_line_length": 141, "avg_line_length": 36.707692307692305, "alnum_prop": 0.7460184409052808, "repo_name": "CraigGiles/springmvc", "id": "80b3296d17ae03dff37ef0937a9438a22202331d", "size": "2386", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/main/java/com/gilesc/web/registration/RegistrationController.java", "mode": "33188", "license": "mit", "language": [ { "name": "Java", "bytes": "17090" } ], "symlink_target": "" }
(function(lecture) { lecture.on('activate', function(e) { lecture.dispatch('progress', { progress: ((e.index) / (lecture.deck.length - 1)) * 100 }); }); }(lecture));
{ "content_hash": "6b182824521766f659a340ebde21083e", "timestamp": "", "source": "github", "line_count": 7, "max_line_length": 58, "avg_line_length": 24.857142857142858, "alnum_prop": 0.6091954022988506, "repo_name": "msavela/lecture.js-plugins", "id": "92fa7d003e99bd9f7a361270ba06e43f8a3f2841", "size": "174", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/lecture.progress.js", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "2069" } ], "symlink_target": "" }
<?xml version="1.0" encoding="ascii"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>gittigidiyor.jsonbuilder.JSONBuilder</title> <link rel="stylesheet" href="epydoc.css" type="text/css" /> <script type="text/javascript" src="epydoc.js"></script> </head> <body bgcolor="white" text="black" link="blue" vlink="#204080" alink="#204080"> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="gittigidiyor-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://dev.gittigidiyor.com">GittiGidiyor Python RESTLIKE API</a></th> </tr></table></th> </tr> </table> <table width="100%" cellpadding="0" cellspacing="0"> <tr valign="top"> <td width="100%"> <span class="breadcrumbs"> <a href="gittigidiyor-module.html">Package&nbsp;gittigidiyor</a> :: <a href="gittigidiyor.jsonbuilder-module.html">Module&nbsp;jsonbuilder</a> :: Class&nbsp;JSONBuilder </span> </td> <td> <table cellpadding="0" cellspacing="0"> <!-- hide/show private --> <tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink" onclick="toggle_private();">hide&nbsp;private</a>]</span></td></tr> <tr><td align="right"><span class="options" >[<a href="frames.html" target="_top">frames</a >]&nbsp;|&nbsp;<a href="gittigidiyor.jsonbuilder.JSONBuilder-class.html" target="_top">no&nbsp;frames</a>]</span></td></tr> </table> </td> </tr> </table> <!-- ==================== CLASS DESCRIPTION ==================== --> <h1 class="epydoc">Class JSONBuilder</h1><p class="nomargin-top"><span class="codelink"><a href="gittigidiyor.jsonbuilder-pysrc.html#JSONBuilder">source&nbsp;code</a></span></p> <pre class="base-tree"> object --+ | <strong class="uidshort">JSONBuilder</strong> </pre> <hr /> <p>This class basicly intends to build up json strings.. This class is never instantiated because it provides no instance method..</p> <!-- ==================== INSTANCE METHODS ==================== --> <a name="section-InstanceMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Instance Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-InstanceMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__delattr__</code>, <code>__format__</code>, <code>__getattribute__</code>, <code>__hash__</code>, <code>__init__</code>, <code>__new__</code>, <code>__reduce__</code>, <code>__reduce_ex__</code>, <code>__repr__</code>, <code>__setattr__</code>, <code>__sizeof__</code>, <code>__str__</code>, <code>__subclasshook__</code> </p> </td> </tr> </table> <!-- ==================== STATIC METHODS ==================== --> <a name="section-StaticMethods"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Static Methods</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-StaticMethods" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td width="15%" align="right" valign="top" class="summary"> <span class="summary-type">&nbsp;</span> </td><td class="summary"> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr> <td><span class="summary-sig"><a href="gittigidiyor.jsonbuilder.JSONBuilder-class.html#getJSONObj" class="summary-sig-name">getJSONObj</a>(<span class="summary-sig-arg">**kwargs</span>)</span><br /> Outputs a json-like dictionary with the given unlimited parameters..</td> <td align="right" valign="top"> <span class="codelink"><a href="gittigidiyor.jsonbuilder-pysrc.html#JSONBuilder.getJSONObj">source&nbsp;code</a></span> </td> </tr> </table> </td> </tr> </table> <!-- ==================== PROPERTIES ==================== --> <a name="section-Properties"></a> <table class="summary" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Properties</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-Properties" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> <tr> <td colspan="2" class="summary"> <p class="indent-wrapped-lines"><b>Inherited from <code>object</code></b>: <code>__class__</code> </p> </td> </tr> </table> <!-- ==================== METHOD DETAILS ==================== --> <a name="section-MethodDetails"></a> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr bgcolor="#70b0f0" class="table-header"> <td colspan="2" class="table-header"> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr valign="top"> <td align="left"><span class="table-header">Method Details</span></td> <td align="right" valign="top" ><span class="options">[<a href="#section-MethodDetails" class="privatelink" onclick="toggle_private();" >hide private</a>]</span></td> </tr> </table> </td> </tr> </table> <a name="getJSONObj"></a> <div> <table class="details" border="1" cellpadding="3" cellspacing="0" width="100%" bgcolor="white"> <tr><td> <table width="100%" cellpadding="0" cellspacing="0" border="0"> <tr valign="top"><td> <h3 class="epydoc"><span class="sig"><span class="sig-name">getJSONObj</span>(<span class="sig-arg">**kwargs</span>)</span> <br /><em class="fname">Static Method</em> </h3> </td><td align="right" valign="top" ><span class="codelink"><a href="gittigidiyor.jsonbuilder-pysrc.html#JSONBuilder.getJSONObj">source&nbsp;code</a></span>&nbsp; </td> </tr></table> <p>Outputs a json-like dictionary with the given unlimited parameters..</p> <p>Example: result = JSONBuilder.getJSONObj(name = 'ozgur', surname = 'vatansever')</p> <p>print result</p> <p>'{'name': 'ozgur', 'surname': 'vatansever'}'</p> <dl class="fields"> </dl> </td></tr></table> </div> <br /> <!-- ==================== NAVIGATION BAR ==================== --> <table class="navbar" border="0" width="100%" cellpadding="0" bgcolor="#a0c0ff" cellspacing="0"> <tr valign="middle"> <!-- Home link --> <th>&nbsp;&nbsp;&nbsp;<a href="gittigidiyor-module.html">Home</a>&nbsp;&nbsp;&nbsp;</th> <!-- Tree link --> <th>&nbsp;&nbsp;&nbsp;<a href="module-tree.html">Trees</a>&nbsp;&nbsp;&nbsp;</th> <!-- Index link --> <th>&nbsp;&nbsp;&nbsp;<a href="identifier-index.html">Indices</a>&nbsp;&nbsp;&nbsp;</th> <!-- Help link --> <th>&nbsp;&nbsp;&nbsp;<a href="help.html">Help</a>&nbsp;&nbsp;&nbsp;</th> <!-- Project homepage --> <th class="navbar" align="right" width="100%"> <table border="0" cellpadding="0" cellspacing="0"> <tr><th class="navbar" align="center" ><a class="navbar" target="_top" href="http://dev.gittigidiyor.com">GittiGidiyor Python RESTLIKE API</a></th> </tr></table></th> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%%"> <tr> <td align="left" class="footer"> Generated by Epydoc 3.0.1 on Mon Jul 5 19:36:29 2010 </td> <td align="right" class="footer"> <a target="mainFrame" href="http://epydoc.sourceforge.net" >http://epydoc.sourceforge.net</a> </td> </tr> </table> <script type="text/javascript"> <!-- // Private objects are initially displayed (because if // javascript is turned off then we want them to be // visible); but by default, we want to hide them. So hide // them unless we have a cookie that says to show them. checkCookie(); // --> </script> </body> </html>
{ "content_hash": "5be6cc5dfacd1ec6bba460a5cd130163", "timestamp": "", "source": "github", "line_count": 266, "max_line_length": 208, "avg_line_length": 37.25187969924812, "alnum_prop": 0.5765465738217782, "repo_name": "Annelutfen/gittigidiyor-python", "id": "6c011eafea27dfa01d8892314b509d9d454ec920", "size": "9909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "docs/html/gittigidiyor.jsonbuilder.JSONBuilder-class.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
(function EitherUses(){ var println = console.log; function Either(e,a){ if(!(this instanceof Either)) return new Either(e,a); this.left = e; this.right = a; } function Left(value){ if(!(this instanceof Left)) return new Left(value); this.either = new Either(value,null); this.toString = function(){return "Left("+value+")"}; } Left.prototype = new Either(); function Right(value){ if(!(this instanceof Right)) return new Right(value); this.either=Either(null,value); this.toString = function(){return "Right("+value+")"}; } Right.prototype = new Either(); Either.prototype.map = function(fn,context){ if(this instanceof Left) return this; return Right(fn.call(context,this.either.right)); } Either.prototype.flatMap = function(fn,context){ if(this instanceof Left) return this; return fn.call(context,this.either.right); } Either.prototype.orElse = function(fn,context) { if(this instanceof Left) return fn.call(context); return this; } Either.prototype.map2 = function(b,fn,context){ if(this instanceof Left) return this; var rightValue = this.either.right; return b.map(function(value){ return fn.call(context,rightValue,value); }); } function mean(array) { if(array==null || array.length ==0) return Left("mean of empty list"); else var sum = 0; for(var i=0;i<array.length;i++){ sum += array[i]; } return Right( sum / array.length); } function safeDiv(x,y) { try{ if(y==0) throw("divide by zero error"); else return Right(x/y); } catch(e){ return Left(e); } } //main println("mean of the empty array "+mean([])); println("mean of the normal array "+mean([1,2])); println("div by zero "+safeDiv(4,0)); println(safeDiv(5,0).map(function(value){return value*2;}).toString()); println(safeDiv(5,1).map(function(value){return value*2;}).toString()); println(safeDiv(5,0).orElse(function(){ return Right(10); }).orElse(function(){return Right(3);}).toString()); //Person example function Person(name,age) { this.name = name; this.age = age; this.toString = function(){ return "name:"+name+" age:"+age ;} } function mkName(name) { if(name=="" || name==null) return Left("name cannot be empty"); return Right(name); } function mkAge(age) { if(age <0) return Left("age is out of range"); return Right(age); } function mkPerson(name,age) { return mkName(name).map2(mkAge(age),function(n,a){ return new Person(n,a); }); } println("mkPerson " +mkPerson("test",20)); println("mkPerson negative age " +mkPerson("test",-2)); println("mkPerson null name " +mkPerson(null,2)); })();
{ "content_hash": "4d8467df449b43eedf4622c755bf15e3", "timestamp": "", "source": "github", "line_count": 113, "max_line_length": 75, "avg_line_length": 25.265486725663717, "alnum_prop": 0.6084063047285464, "repo_name": "phatak-dev/fpinjs", "id": "64dfb97dd870ca8fdba1e7f0768a4b613875eb88", "size": "2855", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "chapter4/either.js", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "JavaScript", "bytes": "22734" } ], "symlink_target": "" }
#include "ins.h" #include "binproc.h" #include "cinproc.h" #include "../../inproc.h" #include <string.h> /* nn_transport interface. */ static void nn_inproc_init (void); static void nn_inproc_term (void); static int nn_inproc_bind (struct nn_ep *); static int nn_inproc_connect (struct nn_ep *); struct nn_transport nn_inproc = { "inproc", NN_INPROC, nn_inproc_init, nn_inproc_term, nn_inproc_bind, nn_inproc_connect, NULL, }; static void nn_inproc_init (void) { nn_ins_init (); } static void nn_inproc_term (void) { nn_ins_term (); } static int nn_inproc_bind (struct nn_ep *ep) { return nn_binproc_create (ep); } static int nn_inproc_connect (struct nn_ep *ep) { return nn_cinproc_create (ep); }
{ "content_hash": "6ffeb72a7b3496589182c3539262b3db", "timestamp": "", "source": "github", "line_count": 45, "max_line_length": 47, "avg_line_length": 16.733333333333334, "alnum_prop": 0.6440903054448871, "repo_name": "thisco-de/nanomsg", "id": "b69fdd8d7fc56700b6f473ec7f3feea05aed1f8f", "size": "2024", "binary": false, "copies": "6", "ref": "refs/heads/master", "path": "src/transports/inproc/inproc.c", "mode": "33188", "license": "mit", "language": [ { "name": "C", "bytes": "1185443" }, { "name": "C++", "bytes": "151508" }, { "name": "CMake", "bytes": "26347" } ], "symlink_target": "" }
#import <UIKit/UIKit.h> FOUNDATION_EXPORT NSString *const kAPCSwitchCellIdentifier; @protocol APCSwitchTableViewCellDelegate; @interface APCSwitchTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UILabel *textLabel; @property (nonatomic, weak) IBOutlet UISwitch *cellSwitch; @property (nonatomic, weak) id <APCSwitchTableViewCellDelegate> delegate; @end @protocol APCSwitchTableViewCellDelegate <NSObject> - (void)switchTableViewCell:(APCSwitchTableViewCell *)cell switchValueChanged:(BOOL)on; @end
{ "content_hash": "ff25d0c796e7fa2dc3e0e9ae351d9b09", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 87, "avg_line_length": 24.09090909090909, "alnum_prop": 0.8150943396226416, "repo_name": "Erin-Mounts/AppCore", "id": "3bc25ae5a6cd1e103452deb04816553811667308", "size": "2288", "binary": false, "copies": "8", "ref": "refs/heads/master", "path": "APCAppCore/APCAppCore/UI/TableViewCells/APCSwitchTableViewCell.h", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "Objective-C", "bytes": "3344905" }, { "name": "Shell", "bytes": "5183" }, { "name": "Swift", "bytes": "2772" } ], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_02) on Mon Jan 14 20:52:50 GST 2008 --> <TITLE> I-Index </TITLE> <META NAME="date" CONTENT="2008-01-14"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="I-Index"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../mt/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../mt/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-8.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">Q</A> <A HREF="index-18.html">R</A> <A HREF="index-19.html">S</A> <A HREF="index-20.html">T</A> <A HREF="index-21.html">U</A> <A HREF="index-22.html">V</A> <HR> <A NAME="_I_"><!-- --></A><H2> <B>I</B></H2> <DL> <DT><A HREF="../mt/Mesa.html#iconesRodadas"><B>iconesRodadas</B></A> - Variable in class mt.<A HREF="../mt/Mesa.html" title="class in mt">Mesa</A> <DD>ícones que mostram o status das rodadas jogadas (vitória, empate, derrota ou não-jogada) <DT><A HREF="../mt/Configuracoes.html#idioma"><B>idioma</B></A> - Variable in class mt.<A HREF="../mt/Configuracoes.html" title="class in mt">Configuracoes</A> <DD>&nbsp; <DT><A HREF="../mt/MiniTruco.html#idiomaCommand"><B>idiomaCommand</B></A> - Static variable in class mt.<A HREF="../mt/MiniTruco.html" title="class in mt">MiniTruco</A> <DD>&nbsp; <DT><A HREF="../mt/ClienteBT.html#in"><B>in</B></A> - Variable in class mt.<A HREF="../mt/ClienteBT.html" title="class in mt">ClienteBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorBT.html#in"><B>in</B></A> - Variable in class mt.<A HREF="../mt/JogadorBT.html" title="class in mt">JogadorBT</A> <DD>Inputstream do jogador conectado <DT><A HREF="../mt/Jogador.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/Jogador.html" title="class in mt">Jogador</A> <DD>Informa que o jogador é beneficiário de uma "mão de 11", e, portanto, deve decidir se aceita ou não esta rodada (se aceitar vale 3 pontos, se ambos recusarem perde 1) <DT><A HREF="../mt/JogadorBot.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/JogadorBot.html" title="class in mt">JogadorBot</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorBT.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/JogadorBT.html" title="class in mt">JogadorBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorCPU.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/JogadorCPU.html" title="class in mt">JogadorCPU</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorDummy.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/JogadorDummy.html" title="class in mt">JogadorDummy</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorHumano.html#informaMao11(mt.Carta[])"><B>informaMao11(Carta[])</B></A> - Method in class mt.<A HREF="../mt/JogadorHumano.html" title="class in mt">JogadorHumano</A> <DD>&nbsp; <DT><A HREF="../mt/MiniTruco.html#iniciaJogo(mt.Jogo)"><B>iniciaJogo(Jogo)</B></A> - Method in class mt.<A HREF="../mt/MiniTruco.html" title="class in mt">MiniTruco</A> <DD>Inicia um jogo e o exibe. <DT><A HREF="../mt/MiniTruco.html#iniciarCommand"><B>iniciarCommand</B></A> - Static variable in class mt.<A HREF="../mt/MiniTruco.html" title="class in mt">MiniTruco</A> <DD>&nbsp; <DT><A HREF="../mt/Estrategia.html#inicioMao()"><B>inicioMao()</B></A> - Method in interface mt.<A HREF="../mt/Estrategia.html" title="interface in mt">Estrategia</A> <DD>Notifica que uma mão está começando <DT><A HREF="../mt/EstrategiaGasparotto.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaGasparotto.html" title="class in mt">EstrategiaGasparotto</A> <DD>&nbsp; <DT><A HREF="../mt/EstrategiaSellani.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaSellani.html" title="class in mt">EstrategiaSellani</A> <DD>&nbsp; <DT><A HREF="../mt/EstrategiaWillian.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaWillian.html" title="class in mt">EstrategiaWillian</A> <DD>&nbsp; <DT><A HREF="../mt/Jogador.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/Jogador.html" title="class in mt">Jogador</A> <DD>Informa ao jogador que uma nova mão está iniciando. <DT><A HREF="../mt/JogadorBot.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/JogadorBot.html" title="class in mt">JogadorBot</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorBT.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/JogadorBT.html" title="class in mt">JogadorBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorCPU.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/JogadorCPU.html" title="class in mt">JogadorCPU</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorDummy.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/JogadorDummy.html" title="class in mt">JogadorDummy</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorHumano.html#inicioMao()"><B>inicioMao()</B></A> - Method in class mt.<A HREF="../mt/JogadorHumano.html" title="class in mt">JogadorHumano</A> <DD>&nbsp; <DT><A HREF="../mt/Estrategia.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in interface mt.<A HREF="../mt/Estrategia.html" title="interface in mt">Estrategia</A> <DD>Notifica que uma partida está começando. <DT><A HREF="../mt/EstrategiaGasparotto.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaGasparotto.html" title="class in mt">EstrategiaGasparotto</A> <DD>&nbsp; <DT><A HREF="../mt/EstrategiaSellani.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaSellani.html" title="class in mt">EstrategiaSellani</A> <DD>&nbsp; <DT><A HREF="../mt/EstrategiaWillian.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/EstrategiaWillian.html" title="class in mt">EstrategiaWillian</A> <DD>&nbsp; <DT><A HREF="../mt/Jogador.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/Jogador.html" title="class in mt">Jogador</A> <DD>Informa que uma partida começou. <DT><A HREF="../mt/JogadorBot.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/JogadorBot.html" title="class in mt">JogadorBot</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorBT.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/JogadorBT.html" title="class in mt">JogadorBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorCPU.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/JogadorCPU.html" title="class in mt">JogadorCPU</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorDummy.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/JogadorDummy.html" title="class in mt">JogadorDummy</A> <DD>&nbsp; <DT><A HREF="../mt/JogadorHumano.html#inicioPartida()"><B>inicioPartida()</B></A> - Method in class mt.<A HREF="../mt/JogadorHumano.html" title="class in mt">JogadorHumano</A> <DD>&nbsp; <DT><A HREF="../mt/ClienteBT.ClienteBTListener.html#inquiryCompleted(int)"><B>inquiryCompleted(int)</B></A> - Method in class mt.<A HREF="../mt/ClienteBT.ClienteBTListener.html" title="class in mt">ClienteBT.ClienteBTListener</A> <DD>Notifica conclusão da busca de dispositivos <DT><A HREF="../mt/Mesa.html#isAberturaVisivel()"><B>isAberturaVisivel()</B></A> - Method in class mt.<A HREF="../mt/Mesa.html" title="class in mt">Mesa</A> <DD>&nbsp; <DT><A HREF="../mt/Jogo.html#isAlguemTem11Pontos()"><B>isAlguemTem11Pontos()</B></A> - Method in class mt.<A HREF="../mt/Jogo.html" title="class in mt">Jogo</A> <DD>Informa se alguma das equipes tem 11 pontos (para fins de permitir trucar) Isso não tem a ver com a "mão de 11" - aquela em que uma das equipes apenas tem 11. <DT><A HREF="../mt/Animador.html#isAnimacaoLigada()"><B>isAnimacaoLigada()</B></A> - Static method in class mt.<A HREF="../mt/Animador.html" title="class in mt">Animador</A> <DD>&nbsp; <DT><A HREF="../mt/Mesa.html#isAppRodando"><B>isAppRodando</B></A> - Variable in class mt.<A HREF="../mt/Mesa.html" title="class in mt">Mesa</A> <DD>&nbsp; <DT><A HREF="../mt/Jogo.html#isBaralhoLimpo()"><B>isBaralhoLimpo()</B></A> - Method in class mt.<A HREF="../mt/Jogo.html" title="class in mt">Jogo</A> <DD>&nbsp; <DT><A HREF="../mt/JogoBT.html#isBaralhoLimpo()"><B>isBaralhoLimpo()</B></A> - Method in class mt.<A HREF="../mt/JogoBT.html" title="class in mt">JogoBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogoLocal.html#isBaralhoLimpo()"><B>isBaralhoLimpo()</B></A> - Method in class mt.<A HREF="../mt/JogoLocal.html" title="class in mt">JogoLocal</A> <DD>&nbsp; <DT><A HREF="../mt/JogoTCP.html#isBaralhoLimpo()"><B>isBaralhoLimpo()</B></A> - Method in class mt.<A HREF="../mt/JogoTCP.html" title="class in mt">JogoTCP</A> <DD>&nbsp; <DT><A HREF="../mt/Carta.html#isCartaEmJogo()"><B>isCartaEmJogo()</B></A> - Method in class mt.<A HREF="../mt/Carta.html" title="class in mt">Carta</A> <DD>Indica se a carta está em jogo, e, portanto, deve ficar "clarinha" (as cartas de rodadas passadas são escurecidas <DT><A HREF="../mt/Carta.html#isCartasGrandes()"><B>isCartasGrandes()</B></A> - Static method in class mt.<A HREF="../mt/Carta.html" title="class in mt">Carta</A> <DD>&nbsp; <DT><A HREF="../mt/Carta.html#isClicado(int, int)"><B>isClicado(int, int)</B></A> - Method in class mt.<A HREF="../mt/Carta.html" title="class in mt">Carta</A> <DD>Retorna true se um clique do apontador nesta posição corresponde a esta carta <DT><A HREF="../mt/Configuracoes.html#isDefault()"><B>isDefault()</B></A> - Method in class mt.<A HREF="../mt/Configuracoes.html" title="class in mt">Configuracoes</A> <DD>Indica se as configurações do objeto foram recuperadas do celular ou se são as default para primeira execução (ou para dispostivos que não suportam RecordStore) <DT><A HREF="../mt/Carta.html#isFechada()"><B>isFechada()</B></A> - Method in class mt.<A HREF="../mt/Carta.html" title="class in mt">Carta</A> <DD>&nbsp; <DT><A HREF="../mt/Mesa.html#isJogada(mt.Carta)"><B>isJogada(Carta)</B></A> - Method in class mt.<A HREF="../mt/Mesa.html" title="class in mt">Mesa</A> <DD>Verifica se uma carta já foi jogada na mesa <DT><A HREF="../mt/Jogo.html#isManilhaVelha()"><B>isManilhaVelha()</B></A> - Method in class mt.<A HREF="../mt/Jogo.html" title="class in mt">Jogo</A> <DD>&nbsp; <DT><A HREF="../mt/JogoBT.html#isManilhaVelha()"><B>isManilhaVelha()</B></A> - Method in class mt.<A HREF="../mt/JogoBT.html" title="class in mt">JogoBT</A> <DD>&nbsp; <DT><A HREF="../mt/JogoLocal.html#isManilhaVelha()"><B>isManilhaVelha()</B></A> - Method in class mt.<A HREF="../mt/JogoLocal.html" title="class in mt">JogoLocal</A> <DD>&nbsp; <DT><A HREF="../mt/JogoTCP.html#isManilhaVelha()"><B>isManilhaVelha()</B></A> - Method in class mt.<A HREF="../mt/JogoTCP.html" title="class in mt">JogoTCP</A> <DD>&nbsp; <DT><A HREF="../mt/Carta.html#isVirada()"><B>isVirada()</B></A> - Method in class mt.<A HREF="../mt/Carta.html" title="class in mt">Carta</A> <DD>Determina se uma carta está virada (mostrando o valor) </DL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../mt/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../mt/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="index-8.html"><B>PREV LETTER</B></A>&nbsp; &nbsp;<A HREF="index-10.html"><B>NEXT LETTER</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../index.html?index-filesindex-9.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="index-9.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">J</A> <A HREF="index-11.html">K</A> <A HREF="index-12.html">L</A> <A HREF="index-13.html">M</A> <A HREF="index-14.html">N</A> <A HREF="index-15.html">O</A> <A HREF="index-16.html">P</A> <A HREF="index-17.html">Q</A> <A HREF="index-18.html">R</A> <A HREF="index-19.html">S</A> <A HREF="index-20.html">T</A> <A HREF="index-21.html">U</A> <A HREF="index-22.html">V</A> <HR> </BODY> </HTML>
{ "content_hash": "c0260e3a3552faf9f732889260620eb1", "timestamp": "", "source": "github", "line_count": 312, "max_line_length": 655, "avg_line_length": 55.89102564102564, "alnum_prop": 0.6418740681270788, "repo_name": "chesterbr/minitruco-j2me", "id": "3841860b34bc2f6b8ae0a613e454ccf716b8402d", "size": "17468", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "miniTruco/docs/javadoc/index-files/index-9.html", "mode": "33188", "license": "bsd-3-clause", "language": [ { "name": "CSS", "bytes": "1420" }, { "name": "Java", "bytes": "536877" } ], "symlink_target": "" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.7.7: v8::ExternalResourceVisitor Class Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.7.7 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1_external_resource_visitor.html">ExternalResourceVisitor</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="classv8_1_1_external_resource_visitor-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">v8::ExternalResourceVisitor Class Reference</div> </div> </div><!--header--> <div class="contents"> <p><code>#include &lt;<a class="el" href="v8_8h_source.html">v8.h</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:ab00ff4cd0d0167894faa8331b68a58c6"><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="ab00ff4cd0d0167894faa8331b68a58c6"></a> virtual void&#160;</td><td class="memItemRight" valign="bottom"><b>VisitExternalString</b> (<a class="el" href="classv8_1_1_handle.html">Handle</a>&lt; <a class="el" href="classv8_1_1_string.html">String</a> &gt; string)</td></tr> <tr class="separator:ab00ff4cd0d0167894faa8331b68a58c6"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>Interface for iterating though all external resources in the heap. </p> </div><hr/>The documentation for this class was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:48:11 for V8 API Reference Guide for node.js v0.7.7 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{ "content_hash": "22620a297147dcd9a97f4f8f59db79d3", "timestamp": "", "source": "github", "line_count": 120, "max_line_length": 230, "avg_line_length": 46.85, "alnum_prop": 0.6606189967982924, "repo_name": "v8-dox/v8-dox.github.io", "id": "ef004da1f2cd9b388786e56491ef8b28299d9181", "size": "5622", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "6ebe9e0/html/classv8_1_1_external_resource_visitor.html", "mode": "33188", "license": "mit", "language": [], "symlink_target": "" }
using System.IO; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace TrixonSystems.PTemplater { internal static class RazorHelper { #region Public methods public static string RenderView(string pathToView, object model, ControllerContext controllerContext) { var st = new StringWriter(); var razor = new RazorView(controllerContext, pathToView, null, false, null); razor.Render(new ViewContext(controllerContext, razor, new ViewDataDictionary(model), new TempDataDictionary(), st), st); return st.ToString(); } public static string RenderView(string pathToView, object model, Controller controller) { var controllerContext = GetFakeControllerContext(controller); return RenderView(pathToView, model, controllerContext); } public static string RenderView(string pathToView, object model) { var controllerContext = GetFakeControllerContext(new PTemplaterController()); return RenderView(pathToView, model, controllerContext); } #endregion #region Private methods /// <summary> /// Get the fake controller context /// </summary> /// <returns>Fake controller context</returns> private static ControllerContext GetFakeControllerContext(Controller controller) { var context = new HttpContextWrapper(HttpContext.Current); var routeData = new RouteData(); return new ControllerContext(new RequestContext(context, routeData), controller); } #endregion } }
{ "content_hash": "d2c78a27e68d45d1f5101b32999257e1", "timestamp": "", "source": "github", "line_count": 49, "max_line_length": 133, "avg_line_length": 34.36734693877551, "alnum_prop": 0.6567695961995249, "repo_name": "TrixonSystems/PTemplater", "id": "08c4cc0504d4c24216c7a858c39958c972dff710", "size": "1686", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "TrixonSystems.PTemplater/RazorHelper.cs", "mode": "33188", "license": "mit", "language": [ { "name": "ASP", "bytes": "130" }, { "name": "C#", "bytes": "26999" }, { "name": "CSS", "bytes": "316" }, { "name": "HTML", "bytes": "4166" } ], "symlink_target": "" }
from __future__ import (absolute_import, print_function, division) import copy import os from netlib import tcp, certutils from .. import stateobject, utils class ClientConnection(tcp.BaseHandler, stateobject.StateObject): def __init__(self, client_connection, address, server): # Eventually, this object is restored from state. We don't have a # connection then. if client_connection: super(ClientConnection, self).__init__(client_connection, address, server) else: self.connection = None self.server = None self.wfile = None self.rfile = None self.address = None self.clientcert = None self.ssl_established = None self.timestamp_start = utils.timestamp() self.timestamp_end = None self.timestamp_ssl_setup = None self.protocol = None def __nonzero__(self): return bool(self.connection) and not self.finished def __repr__(self): return "<ClientConnection: {ssl}{host}:{port}>".format( ssl="[ssl] " if self.ssl_established else "", host=self.address.host, port=self.address.port ) @property def tls_established(self): return self.ssl_established _stateobject_attributes = dict( ssl_established=bool, timestamp_start=float, timestamp_end=float, timestamp_ssl_setup=float ) def get_state(self, short=False): d = super(ClientConnection, self).get_state(short) d.update( address={ "address": self.address(), "use_ipv6": self.address.use_ipv6}, clientcert=self.cert.to_pem() if self.clientcert else None) return d def load_state(self, state): super(ClientConnection, self).load_state(state) self.address = tcp.Address( **state["address"]) if state["address"] else None self.clientcert = certutils.SSLCert.from_pem( state["clientcert"]) if state["clientcert"] else None def copy(self): return copy.copy(self) def send(self, message): if isinstance(message, list): message = b''.join(message) self.wfile.write(message) self.wfile.flush() @classmethod def from_state(cls, state): f = cls(None, tuple(), None) f.load_state(state) return f def convert_to_ssl(self, *args, **kwargs): super(ClientConnection, self).convert_to_ssl(*args, **kwargs) self.timestamp_ssl_setup = utils.timestamp() def finish(self): super(ClientConnection, self).finish() self.timestamp_end = utils.timestamp() class ServerConnection(tcp.TCPClient, stateobject.StateObject): def __init__(self, address): tcp.TCPClient.__init__(self, address) self.via = None self.timestamp_start = None self.timestamp_end = None self.timestamp_tcp_setup = None self.timestamp_ssl_setup = None self.protocol = None def __nonzero__(self): return bool(self.connection) and not self.finished def __repr__(self): if self.ssl_established and self.sni: ssl = "[ssl: {0}] ".format(self.sni) elif self.ssl_established: ssl = "[ssl] " else: ssl = "" return "<ServerConnection: {ssl}{host}:{port}>".format( ssl=ssl, host=self.address.host, port=self.address.port ) @property def tls_established(self): return self.ssl_established _stateobject_attributes = dict( timestamp_start=float, timestamp_end=float, timestamp_tcp_setup=float, timestamp_ssl_setup=float, address=tcp.Address, source_address=tcp.Address, cert=certutils.SSLCert, ssl_established=bool, sni=str ) _stateobject_long_attributes = {"cert"} def get_state(self, short=False): d = super(ServerConnection, self).get_state(short) d.update( address={"address": self.address(), "use_ipv6": self.address.use_ipv6}, source_address=({"address": self.source_address(), "use_ipv6": self.source_address.use_ipv6} if self.source_address else None), cert=self.cert.to_pem() if self.cert else None ) return d def load_state(self, state): super(ServerConnection, self).load_state(state) self.address = tcp.Address( **state["address"]) if state["address"] else None self.source_address = tcp.Address( **state["source_address"]) if state["source_address"] else None self.cert = certutils.SSLCert.from_pem( state["cert"]) if state["cert"] else None @classmethod def from_state(cls, state): f = cls(tuple()) f.load_state(state) return f def copy(self): return copy.copy(self) def connect(self): self.timestamp_start = utils.timestamp() tcp.TCPClient.connect(self) self.timestamp_tcp_setup = utils.timestamp() def send(self, message): if isinstance(message, list): message = b''.join(message) self.wfile.write(message) self.wfile.flush() def establish_ssl(self, clientcerts, sni, **kwargs): clientcert = None if clientcerts: path = os.path.join( clientcerts, self.address.host.encode("idna")) + ".pem" if os.path.exists(path): clientcert = path self.convert_to_ssl(cert=clientcert, sni=sni, **kwargs) self.sni = sni self.timestamp_ssl_setup = utils.timestamp() def finish(self): tcp.TCPClient.finish(self) self.timestamp_end = utils.timestamp() ServerConnection._stateobject_attributes["via"] = ServerConnection
{ "content_hash": "dee8d02230b6eb97f6750d4f9cb0db30", "timestamp": "", "source": "github", "line_count": 194, "max_line_length": 105, "avg_line_length": 30.95360824742268, "alnum_prop": 0.5866777685262281, "repo_name": "scriptmediala/mitmproxy", "id": "f1e10de9f68ea3c020acd89d986293f5f6a15ba6", "size": "6005", "binary": false, "copies": "12", "ref": "refs/heads/master", "path": "libmproxy/models/connections.py", "mode": "33188", "license": "mit", "language": [ { "name": "Batchfile", "bytes": "425" }, { "name": "CSS", "bytes": "188807" }, { "name": "HTML", "bytes": "2824" }, { "name": "JavaScript", "bytes": "1728524" }, { "name": "Python", "bytes": "653717" }, { "name": "Shell", "bytes": "2303" } ], "symlink_target": "" }
package org.apache.jackrabbit.oak.plugins.index.search.util; import static org.apache.jackrabbit.oak.plugins.memory.EmptyNodeState.EMPTY_NODE; import static org.junit.Assert.assertEquals; import java.util.Arrays; import org.apache.jackrabbit.oak.api.Type; import org.apache.jackrabbit.oak.plugins.memory.ArrayBasedBlob; import org.junit.Test; public class FunctionIndexProcessorTest { @Test public void getProperties() { assertEquals( "[a, test/b, test/:name]", Arrays.toString( FunctionIndexProcessor.getProperties(new String[] { "function", "multiply", "@a", "add", "@test/b", "@test/:name" }))); } @Test public void tryCalculateValue() { // length of a string assertEquals("value = 11", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data", "Hello World").getNodeState(), new String[]{"function", "length", "@data"}).toString()); // length of a binary property assertEquals("value = 100", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data", new ArrayBasedBlob(new byte[100]), Type.BINARY).getNodeState(), new String[]{"function", "length", "@data"}).toString()); // uppercase assertEquals("value = HELLO WORLD", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data", "Hello World").getNodeState(), new String[]{"function", "upper", "@data"}).toString()); // lowercase assertEquals("value = hello world", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data", "Hello World").getNodeState(), new String[]{"function", "lower", "@data"}).toString()); // coalesce assertEquals("value = Hello", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder(). setProperty("data1", "Hello"). setProperty("data2", "World").getNodeState(), new String[]{"function", "coalesce", "@data1", "@data2"}).toString()); assertEquals("value = World", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data2", "World").getNodeState(), new String[]{"function", "coalesce", "@data1", "@data2"}).toString()); assertEquals("value = Hello", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data1", "Hello").getNodeState(), new String[]{"function", "coalesce", "@data1", "@data2"}).toString()); assertEquals("null", "" + FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("data3", "Hello").getNodeState(), new String[]{"function", "coalesce", "@data1", "@data2"})); // first assertEquals("value = Hello", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("array", Arrays.asList("Hello", "World"), Type.STRINGS).getNodeState(), new String[]{"function", "first", "@array"}).toString()); assertEquals("value = Hello", FunctionIndexProcessor.tryCalculateValue("x", EMPTY_NODE.builder().setProperty("array", Arrays.asList("Hello"), Type.STRINGS).getNodeState(), new String[]{"function", "first", "@array"}).toString()); // name assertEquals("value = abc:content", FunctionIndexProcessor.tryCalculateValue("abc:content", EMPTY_NODE.builder().getNodeState(), new String[]{"function", "@:name"}).toString()); // localname assertEquals("value = content", FunctionIndexProcessor.tryCalculateValue("abc:content", EMPTY_NODE.builder().getNodeState(), new String[]{"function", "@:localname"}).toString()); // path assertEquals("value = /content", FunctionIndexProcessor.tryCalculateValue("/content", EMPTY_NODE.builder().getNodeState(), new String[]{"function", "@:path"}).toString()); } @Test public void xpath() { checkConvert( "fn:upper-case(@data)", "function*upper*@data"); checkConvert( "fn:lower-case(test/@data)", "function*lower*@test/data"); checkConvert( "fn:lower-case(fn:name())", "function*lower*@:name"); checkConvert( "fn:lower-case(fn:local-name())", "function*lower*@:localname"); checkConvert( "fn:string-length(test/@data)", "function*length*@test/data"); checkConvert( "fn:string-length(fn:name())", "function*length*@:name"); checkConvert( "fn:path()", "function*@:path"); checkConvert( "fn:string-length(fn:path())", "function*length*@:path"); checkConvert( "fn:string-length(@jcr:path)", "function*length*@:path"); checkConvert( "fn:lower-case(fn:upper-case(test/@data))", "function*lower*upper*@test/data"); checkConvert("fn:coalesce(jcr:content/@foo2, jcr:content/@foo)", "function*coalesce*@jcr:content/foo2*@jcr:content/foo"); checkConvert("fn:coalesce(jcr:content/@foo2,fn:lower-case(jcr:content/@foo))", "function*coalesce*@jcr:content/foo2*lower*@jcr:content/foo"); checkConvert("fn:coalesce(jcr:content/@foo2,fn:coalesce(jcr:content/@foo, fn:lower-case(fn:name())))", "function*coalesce*@jcr:content/foo2*coalesce*@jcr:content/foo*lower*@:name"); checkConvert("fn:coalesce(fn:coalesce(jcr:content/@foo2,jcr:content/@foo), fn:coalesce(@a:b, @c:d))", "function*coalesce*coalesce*@jcr:content/foo2*@jcr:content/foo*coalesce*@a:b*@c:d"); checkConvert("jcr:first(jcr:content/@foo2)", "function*first*@jcr:content/foo2"); } @Test public void sql2() { checkConvert( "upper([data])", "function*upper*@data"); checkConvert( "lower([test/data])", "function*lower*@test/data"); checkConvert( "lower(name())", "function*lower*@:name"); checkConvert( "lower(localname())", "function*lower*@:localname"); checkConvert( "length([test/data])", "function*length*@test/data"); checkConvert( "length(name())", "function*length*@:name"); checkConvert( "path()", "function*@:path"); checkConvert( "length(path())", "function*length*@:path"); checkConvert( "length([jcr:path])", "function*length*@:path"); checkConvert( "lower(upper([test/data]))", "function*lower*upper*@test/data"); // the ']' character is escaped as ']]' checkConvert( "[strange[0]]]", "function*@strange[0]"); checkConvert("coalesce([jcr:content/foo2],[jcr:content/foo])", "function*coalesce*@jcr:content/foo2*@jcr:content/foo"); checkConvert("coalesce([jcr:content/foo2], lower([jcr:content/foo]))", "function*coalesce*@jcr:content/foo2*lower*@jcr:content/foo"); checkConvert("coalesce([jcr:content/foo2] , coalesce([jcr:content/foo],lower(name())))", "function*coalesce*@jcr:content/foo2*coalesce*@jcr:content/foo*lower*@:name"); checkConvert("coalesce(coalesce([jcr:content/foo2],[jcr:content/foo]), coalesce([a:b], [c:d]))", "function*coalesce*coalesce*@jcr:content/foo2*@jcr:content/foo*coalesce*@a:b*@c:d"); checkConvert("first([jcr:content/foo2])", "function*first*@jcr:content/foo2"); } private static void checkConvert(String function, String expectedPolishNotation) { String p = FunctionIndexProcessor.convertToPolishNotation(function); assertEquals(expectedPolishNotation, p); } }
{ "content_hash": "02a9fbea07110b6edebf56812bc70331", "timestamp": "", "source": "github", "line_count": 189, "max_line_length": 120, "avg_line_length": 46.05820105820106, "alnum_prop": 0.5515221137277426, "repo_name": "amit-jain/jackrabbit-oak", "id": "e01f89f0eb1f404c29979acdadda332e33250329", "size": "9512", "binary": false, "copies": "4", "ref": "refs/heads/trunk", "path": "oak-search/src/test/java/org/apache/jackrabbit/oak/plugins/index/search/util/FunctionIndexProcessorTest.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "24043" }, { "name": "Groovy", "bytes": "146403" }, { "name": "HTML", "bytes": "1406" }, { "name": "Java", "bytes": "33038785" }, { "name": "JavaScript", "bytes": "43898" }, { "name": "Perl", "bytes": "7585" }, { "name": "Rich Text Format", "bytes": "64887" }, { "name": "Shell", "bytes": "18524" } ], "symlink_target": "" }
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{ "content_hash": "f826dd80a75aaab1f3c23373636503f7", "timestamp": "", "source": "github", "line_count": 13, "max_line_length": 31, "avg_line_length": 9.692307692307692, "alnum_prop": 0.7063492063492064, "repo_name": "mdoering/backbone", "id": "ea214b8f0cbffcb30656e697c2f85535bf8b06d5", "size": "171", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "life/Plantae/Magnoliophyta/Magnoliopsida/Brassicales/Brassicaceae/Draba/Draba setulosa/README.md", "mode": "33188", "license": "apache-2.0", "language": [], "symlink_target": "" }
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_73) on Mon Sep 19 13:35:21 PDT 2016 --> <title>GraphWalkIteratorProvider</title> <meta name="date" content="2016-09-19"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="GraphWalkIteratorProvider"; } } catch(err) { } //--> var methods = {"i0":6}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],4:["t3","Abstract Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../org/deeplearning4j/graph/iterator/parallel/RandomWalkGraphIteratorProvider.html" title="class in org.deeplearning4j.graph.iterator.parallel"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html" target="_top">Frames</a></li> <li><a href="GraphWalkIteratorProvider.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">org.deeplearning4j.graph.iterator.parallel</div> <h2 title="Interface GraphWalkIteratorProvider" class="title">Interface GraphWalkIteratorProvider&lt;V&gt;</h2> </div> <div class="contentContainer"> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Known Implementing Classes:</dt> <dd><a href="../../../../../org/deeplearning4j/graph/iterator/parallel/RandomWalkGraphIteratorProvider.html" title="class in org.deeplearning4j.graph.iterator.parallel">RandomWalkGraphIteratorProvider</a>, <a href="../../../../../org/deeplearning4j/graph/iterator/parallel/WeightedRandomWalkGraphIteratorProvider.html" title="class in org.deeplearning4j.graph.iterator.parallel">WeightedRandomWalkGraphIteratorProvider</a></dd> </dl> <hr> <br> <pre>public interface <span class="typeNameLabel">GraphWalkIteratorProvider&lt;V&gt;</span></pre> <div class="block">GraphWalkIteratorProvider: implementations of this interface provide a set of GraphWalkIterator objects. Intended use: parallelization. One GraphWalkIterator per thread.</div> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">Abstract Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>java.util.List&lt;<a href="../../../../../org/deeplearning4j/graph/iterator/GraphWalkIterator.html" title="interface in org.deeplearning4j.graph.iterator">GraphWalkIterator</a>&lt;<a href="../../../../../org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html" title="type parameter in GraphWalkIteratorProvider">V</a>&gt;&gt;</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html#getGraphWalkIterators-int-">getGraphWalkIterators</a></span>(int&nbsp;numIterators)</code> <div class="block">Get a list of GraphWalkIterators.</div> </td> </tr> </table> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="getGraphWalkIterators-int-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getGraphWalkIterators</h4> <pre>java.util.List&lt;<a href="../../../../../org/deeplearning4j/graph/iterator/GraphWalkIterator.html" title="interface in org.deeplearning4j.graph.iterator">GraphWalkIterator</a>&lt;<a href="../../../../../org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html" title="type parameter in GraphWalkIteratorProvider">V</a>&gt;&gt;&nbsp;getGraphWalkIterators(int&nbsp;numIterators)</pre> <div class="block">Get a list of GraphWalkIterators. In general: may return less than the specified number of iterators, (for example, for small networks) but never more than it</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>numIterators</code> - Number of iterators to return</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev&nbsp;Class</li> <li><a href="../../../../../org/deeplearning4j/graph/iterator/parallel/RandomWalkGraphIteratorProvider.html" title="class in org.deeplearning4j.graph.iterator.parallel"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html" target="_top">Frames</a></li> <li><a href="GraphWalkIteratorProvider.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li>Constr&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
{ "content_hash": "b64e1de74029f09a9cd9ba8a1fd048bd", "timestamp": "", "source": "github", "line_count": 233, "max_line_length": 427, "avg_line_length": 39.82832618025751, "alnum_prop": 0.6585129310344827, "repo_name": "YeewenTan/YeewenTan.github.io", "id": "0570986c9fab9f2430ab642e5115712616f2bb4d", "size": "9280", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "doc/org/deeplearning4j/graph/iterator/parallel/GraphWalkIteratorProvider.html", "mode": "33261", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "133538" }, { "name": "HTML", "bytes": "32734320" }, { "name": "JavaScript", "bytes": "784456" }, { "name": "PHP", "bytes": "23949" }, { "name": "Ruby", "bytes": "11810" }, { "name": "Shell", "bytes": "122" } ], "symlink_target": "" }
/** Maximum supported key kength */ #define MAX_AES_KEY_LENGTH 256 /* TODO: remove in a future version */ /* Guard against using an old export control restriction #define */ #ifdef AES_USE_KEY_BITS #error AES_USE_KEY_BITS not supported #endif extern uint *my_aes_opmode_key_sizes; void my_aes_create_key(const unsigned char *key, uint key_length, uint8 *rkey, enum my_aes_opmode opmode);
{ "content_hash": "2df4ebc80e16cc6f6517b55fb8096b95", "timestamp": "", "source": "github", "line_count": 18, "max_line_length": 67, "avg_line_length": 23.27777777777778, "alnum_prop": 0.6921241050119332, "repo_name": "fjz13/Medusa", "id": "2e18b2ea0ef5eae79600dc6d4807495a992304e5", "size": "1126", "binary": false, "copies": "121", "ref": "refs/heads/master", "path": "External/mysql-connector-c/mysys_ssl/my_aes_impl.h", "mode": "33188", "license": "mit", "language": [ { "name": "ActionScript", "bytes": "556" }, { "name": "Assembly", "bytes": "12744" }, { "name": "Batchfile", "bytes": "42344" }, { "name": "C", "bytes": "46036497" }, { "name": "C#", "bytes": "1027908" }, { "name": "C++", "bytes": "11168236" }, { "name": "CMake", "bytes": "375952" }, { "name": "Csound Document", "bytes": "21752" }, { "name": "GLSL", "bytes": "3718" }, { "name": "Groff", "bytes": "63948" }, { "name": "Lua", "bytes": "1021348" }, { "name": "Makefile", "bytes": "94750" }, { "name": "Objective-C", "bytes": "59375" }, { "name": "Objective-C++", "bytes": "71532" }, { "name": "Pascal", "bytes": "67274" }, { "name": "Perl", "bytes": "75573" }, { "name": "Python", "bytes": "181715" }, { "name": "Shell", "bytes": "93494" }, { "name": "Visual Basic", "bytes": "11281" } ], "symlink_target": "" }
/****************************************************************** Theme Name: The Return of Minimalistic Me Theme URI: https://github.com/aniketpant/return-of-minimalistic-me Description: The second stable WordPress theme for my blog Author: Aniket Pant Author URI: http://www.aniketpant.com Version: 2.0 Tags: flexble-width, translation-ready, microformats, rtl-language-support License: WTFPL License URI: http://sam.zoy.org/wtfpl/ Are You Serious? Yes. MAKE SURE TO READ BELOW BEFORE GETTING STARTED FOR THE FIRST TIME! ------------------------------------------------------------------ You may be thinking… WHOA, WHOA, WHOA…WHAT HAPPENED HERE? But before you freak out, let me take a few minutes to explain. Bones now uses LESS or Sass by default. If you prefer using regular CSS, then feel free to modify this theme how you like and keep a copy as your own personal starting point. DON'T DISMISS IT JUST YET THOUGH, USING LESS or Sass ISN'T AS COMPLICATED AS YOU THINK. It does take a few minutes to wrap your head around, but it will all be worth it. Need a quick intro? Here are a few quick reads: http://cognition.happycog.com/article/preprocess-this http://coding.smashingmagazine.com/2011/09/09/an-introduction-to-less-and-comparison-to-sass/ I would HIGHLY RECOMMEND, if you are going to be working with LESS or Sass, that you work locally. Sass isn't readable by a browser and using a LESS js file to parse it on live sites can make your site sluggish. That being said, here are a few MUST HAVE TOOLS for working with a pre-processor: (You really only need one of them) CodeKit: (Highly Recommended) http://incident57.com/codekit/ LESS App: http://incident57.com/less/ Compass App: (Windows / Mac Users) http://compass.handlino.com/ SimpLESS: (Windows Users) http://wearekiss.com/simpless WinLESS: (Windows Users) http://winless.org/ These applications compile LESS or Sass into valid CSS. This way you can keep your production files easy to read and your CSS minified and speedy. Simply set the output to the library/css folder and you are all set. It's a thing of beauty. --------------------------------------------------------------- Remember, once you download Bones it's up to you how to use it, so go nuts. Set things up and develop in a way that's easiest for you. If LESS/Sass is still a bit confusing for you, then remove them and customize this template as you see fit. If you're frustrated with this new direction and don't like change, take a few minutes and think about how much better a developer you can become by just TRYING out new technologies. It may be tough at first but it WILL make you a better developer. TRUST ME ON THIS. Give it a week, maybe two, and you will never go back. Happy Developing! ******************************************************************/
{ "content_hash": "a7f19b18123e7a30f9f10abee0455749", "timestamp": "", "source": "github", "line_count": 79, "max_line_length": 93, "avg_line_length": 36.77215189873418, "alnum_prop": 0.680895008605852, "repo_name": "aniketpant/return-of-minimalistic-me", "id": "0f49b2e42ca8baaee9d076ecf01773156c35c997", "size": "2909", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "style.css", "mode": "33188", "license": "mit", "language": [ { "name": "JavaScript", "bytes": "3502" }, { "name": "PHP", "bytes": "73718" }, { "name": "Ruby", "bytes": "947" } ], "symlink_target": "" }
package org.apache.geode.internal.cache.tier.sockets.command; import java.io.IOException; import java.nio.ByteBuffer; import org.jetbrains.annotations.NotNull; import org.apache.geode.annotations.Immutable; import org.apache.geode.internal.InternalDataSerializer; import org.apache.geode.internal.cache.EventID; import org.apache.geode.internal.cache.tier.Command; import org.apache.geode.internal.cache.tier.sockets.BaseCommand; import org.apache.geode.internal.cache.tier.sockets.CacheServerHelper; import org.apache.geode.internal.cache.tier.sockets.Message; import org.apache.geode.internal.cache.tier.sockets.Part; import org.apache.geode.internal.cache.tier.sockets.ServerConnection; import org.apache.geode.internal.security.SecurityService; public class RegisterDataSerializers extends BaseCommand { @Immutable private static final RegisterDataSerializers singleton = new RegisterDataSerializers(); public static Command getCommand() { return singleton; } private RegisterDataSerializers() {} @Override public void cmdExecute(final @NotNull Message clientMessage, final @NotNull ServerConnection serverConnection, final @NotNull SecurityService securityService, long start) throws IOException, ClassNotFoundException { serverConnection.setAsTrue(REQUIRES_RESPONSE); if (logger.isDebugEnabled()) { logger.debug("{}: Received register dataserializer request ({} parts) from {}", serverConnection.getName(), clientMessage.getNumberOfParts(), serverConnection.getSocketString()); } if (!ServerConnection.allowInternalMessagesWithoutCredentials) { serverConnection.getAuthzRequest(); } int noOfParts = clientMessage.getNumberOfParts(); // 2 parts per instantiator and one eventId part int noOfDataSerializers = (noOfParts - 1) / 2; // retrieve eventID from the last Part ByteBuffer eventIdPartsBuffer = ByteBuffer.wrap(clientMessage.getPart(noOfParts - 1).getSerializedForm()); long threadId = EventID.readEventIdPartsFromOptimizedByteArray(eventIdPartsBuffer); long sequenceId = EventID.readEventIdPartsFromOptimizedByteArray(eventIdPartsBuffer); EventID eventId = new EventID(serverConnection.getEventMemberIDByteArray(), threadId, sequenceId); byte[][] serializedDataSerializers = new byte[noOfDataSerializers * 2][]; boolean caughtCNFE = false; Exception cnfe = null; try { for (int i = 0; i < noOfParts - 1; i = i + 2) { Part dataSerializerClassNamePart = clientMessage.getPart(i); serializedDataSerializers[i] = dataSerializerClassNamePart.getSerializedForm(); String dataSerializerClassName = (String) CacheServerHelper.deserialize(serializedDataSerializers[i]); Part idPart = clientMessage.getPart(i + 1); serializedDataSerializers[i + 1] = idPart.getSerializedForm(); int id = idPart.getInt(); Class dataSerializerClass = null; try { dataSerializerClass = InternalDataSerializer.getCachedClass(dataSerializerClassName); InternalDataSerializer.register(dataSerializerClass, true, eventId, serverConnection.getProxyID()); } catch (ClassNotFoundException e) { // If a ClassNotFoundException is caught, store it, but continue // processing other instantiators caughtCNFE = true; cnfe = e; } } } catch (Exception e) { writeException(clientMessage, e, false, serverConnection); serverConnection.setAsTrue(RESPONDED); } // If a ClassNotFoundException was caught while processing the // instantiators, send it back to the client. Note: This only sends // the last CNFE. if (caughtCNFE) { writeException(clientMessage, cnfe, false, serverConnection); serverConnection.setAsTrue(RESPONDED); } // Send reply to client if necessary. If an exception occurs in the above // code, then the reply has already been sent. if (!serverConnection.getTransientFlag(RESPONDED)) { writeReply(clientMessage, serverConnection); } if (logger.isDebugEnabled()) { logger.debug("Registered dataserializer for MembershipId = {}", serverConnection.getMembershipID()); } } }
{ "content_hash": "ad33a39a993dadc98613f722c54d1aee", "timestamp": "", "source": "github", "line_count": 111, "max_line_length": 95, "avg_line_length": 38.77477477477478, "alnum_prop": 0.7279275092936803, "repo_name": "jdeppe-pivotal/geode", "id": "81f2804bd9a8cd5c88fbbc63edc6b73a883e8ea9", "size": "5093", "binary": false, "copies": "4", "ref": "refs/heads/develop", "path": "geode-core/src/main/java/org/apache/geode/internal/cache/tier/sockets/command/RegisterDataSerializers.java", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "CSS", "bytes": "104031" }, { "name": "Dockerfile", "bytes": "15956" }, { "name": "Go", "bytes": "40709" }, { "name": "Groovy", "bytes": "41916" }, { "name": "HTML", "bytes": "4037680" }, { "name": "Java", "bytes": "33151406" }, { "name": "JavaScript", "bytes": "1780821" }, { "name": "Python", "bytes": "29801" }, { "name": "Ruby", "bytes": "1801" }, { "name": "SCSS", "bytes": "2677" }, { "name": "Shell", "bytes": "275617" } ], "symlink_target": "" }
<?xml version="1.0" encoding="UTF-8" ?> <!-- ~ 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. --> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="org.flowable.engine.impl.persistence.entity.CommentEntityImpl"> <!-- COMMENT INSERT --> <insert id="insertComment" parameterType="org.flowable.engine.impl.persistence.entity.CommentEntityImpl"> insert into ${prefix}ACT_HI_COMMENT (ID_, TYPE_, TIME_, USER_ID_, TASK_ID_, PROC_INST_ID_, ACTION_, MESSAGE_, FULL_MSG_) values (#{id ,jdbcType=VARCHAR}, #{type ,jdbcType=VARCHAR}, #{time ,jdbcType=TIMESTAMP}, #{userId ,jdbcType=VARCHAR}, #{taskId ,jdbcType=VARCHAR}, #{processInstanceId ,jdbcType=VARCHAR}, #{action ,jdbcType=VARCHAR}, #{message ,jdbcType=VARCHAR}, #{fullMessageBytes ,jdbcType=${blobType}}) </insert> <insert id="bulkInsertComment" parameterType="java.util.List"> insert into ${prefix}ACT_HI_COMMENT (ID_, TYPE_, TIME_, USER_ID_, TASK_ID_, PROC_INST_ID_, ACTION_, MESSAGE_, FULL_MSG_) values <foreach collection="list" item="comment" index="index" separator=","> (#{comment.id ,jdbcType=VARCHAR}, #{comment.type ,jdbcType=VARCHAR}, #{comment.time ,jdbcType=TIMESTAMP}, #{comment.userId ,jdbcType=VARCHAR}, #{comment.taskId ,jdbcType=VARCHAR}, #{comment.processInstanceId ,jdbcType=VARCHAR}, #{comment.action ,jdbcType=VARCHAR}, #{comment.message ,jdbcType=VARCHAR}, #{comment.fullMessageBytes ,jdbcType=${blobType}}) </foreach> </insert> <insert id="bulkInsertComment" databaseId="oracle" parameterType="java.util.List"> INSERT ALL <foreach collection="list" item="comment" index="index"> into ${prefix}ACT_HI_COMMENT (ID_, TYPE_, TIME_, USER_ID_, TASK_ID_, PROC_INST_ID_, ACTION_, MESSAGE_, FULL_MSG_) VALUES (#{comment.id ,jdbcType=VARCHAR}, #{comment.type ,jdbcType=VARCHAR}, #{comment.time ,jdbcType=TIMESTAMP}, #{comment.userId ,jdbcType=VARCHAR}, #{comment.taskId ,jdbcType=VARCHAR}, #{comment.processInstanceId ,jdbcType=VARCHAR}, #{comment.action ,jdbcType=VARCHAR}, #{comment.message ,jdbcType=VARCHAR}, #{comment.fullMessageBytes ,jdbcType=${blobType}}) </foreach> SELECT * FROM dual </insert> <!-- COMMENT DELETE --> <delete id="deleteComment" parameterType="string"> delete from ${prefix}ACT_HI_COMMENT where ID_ = #{id} </delete> <delete id="deleteCommentsByTaskId" parameterType="string"> delete from ${prefix}ACT_HI_COMMENT where TASK_ID_ = #{taskId} </delete> <delete id="deleteCommentsByProcessInstanceId" parameterType="string"> delete from ${prefix}ACT_HI_COMMENT where PROC_INST_ID_ = #{processInstanceId} </delete> <!-- COMMENT RESULTMAP --> <resultMap id="commentResultMap" type="org.flowable.engine.impl.persistence.entity.CommentEntityImpl"> <id property="id" column="ID_" jdbcType="VARCHAR" /> <result property="type" column="TYPE_" jdbcType="VARCHAR" /> <result property="userId" column="USER_ID_" jdbcType="VARCHAR" /> <result property="time" column="TIME_" jdbcType="TIMESTAMP" /> <result property="taskId" column="TASK_ID_" jdbcType="VARCHAR" /> <result property="processInstanceId" column="PROC_INST_ID_" jdbcType="VARCHAR" /> <result property="action" column="ACTION_" jdbcType="VARCHAR" /> <result property="message" column="MESSAGE_" jdbcType="VARCHAR" /> <result property="fullMessageBytes" column="FULL_MSG_" jdbcType="${blobType}" /> </resultMap> <!-- COMMENT SELECT --> <select id="selectComment" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where ID_ = #{parameter,jdbcType=VARCHAR} </select> <select id="selectCommentsByTaskId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where TASK_ID_ = #{parameter,jdbcType=VARCHAR} and TYPE_ = 'comment' order by TIME_ desc </select> <select id="selectCommentsByTaskIdAndType" parameterType="java.util.Map" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where TASK_ID_ = #{taskId,jdbcType=VARCHAR} and TYPE_ = #{type,jdbcType=VARCHAR} order by TIME_ desc </select> <select id="selectCommentsByType" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where TYPE_ = #{parameter,jdbcType=VARCHAR} order by TIME_ desc </select> <select id="selectEventsByTaskId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where TASK_ID_ = #{parameter,jdbcType=VARCHAR} order by TIME_ desc </select> <select id="selectEventsByProcessInstanceId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where PROC_INST_ID_ = #{parameter,jdbcType=VARCHAR} order by TIME_ desc </select> <select id="selectCommentsByProcessInstanceId" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where PROC_INST_ID_ = #{parameter,jdbcType=VARCHAR} order by TIME_ desc </select> <select id="selectCommentsByProcessInstanceIdAndType" parameterType="org.flowable.engine.common.impl.db.ListQueryParameterObject" resultMap="commentResultMap"> select * from ${prefix}ACT_HI_COMMENT where PROC_INST_ID_ = #{processInstanceId,jdbcType=VARCHAR} and TYPE_ = #{type,jdbcType=VARCHAR} order by TIME_ desc </select> </mapper>
{ "content_hash": "4c9c7bc9716dd4e1b19bfb3d64ecdb85", "timestamp": "", "source": "github", "line_count": 157, "max_line_length": 161, "avg_line_length": 42.93630573248408, "alnum_prop": 0.6714137368342976, "repo_name": "motorina0/flowable-engine", "id": "412b7a914c784895de20c47878730eac9ad03594", "size": "6741", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "modules/flowable-engine/src/main/resources/org/flowable/db/mapping/entity/Comment.xml", "mode": "33188", "license": "apache-2.0", "language": [ { "name": "ApacheConf", "bytes": "96556" }, { "name": "Batchfile", "bytes": "166" }, { "name": "CSS", "bytes": "681931" }, { "name": "HTML", "bytes": "858905" }, { "name": "Java", "bytes": "22289599" }, { "name": "JavaScript", "bytes": "12782950" }, { "name": "Shell", "bytes": "18731" } ], "symlink_target": "" }
date: "2019-10-06T08:00:00+05:00" title: "Usage: Git LFS setup" slug: "git-lfs-setup" weight: 12 toc: true draft: false menu: sidebar: parent: "usage" name: "Git LFS setup" weight: 12 identifier: "git-lfs-setup" --- # Git Large File Storage setup To use Gitea's built-in LFS support, you must update the `app.ini` file: ```ini [server] ; Enables git-lfs support. true or false, default is false. LFS_START_SERVER = true ; Where your lfs files reside, default is data/lfs. LFS_CONTENT_PATH = /home/gitea/data/lfs ```
{ "content_hash": "55ba1f8cf3e1575ad627634afccb09ab", "timestamp": "", "source": "github", "line_count": 25, "max_line_length": 72, "avg_line_length": 21.44, "alnum_prop": 0.6884328358208955, "repo_name": "typeless/gitea", "id": "2d5fab3cb3829935ea09d8c9d4affcc852b5569b", "size": "540", "binary": false, "copies": "4", "ref": "refs/heads/master", "path": "docs/content/doc/usage/git-lfs-support.md", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "142213" }, { "name": "Dockerfile", "bytes": "1249" }, { "name": "Go", "bytes": "4286052" }, { "name": "JavaScript", "bytes": "264009" }, { "name": "Makefile", "bytes": "22289" }, { "name": "Perl", "bytes": "36597" }, { "name": "Roff", "bytes": "164" }, { "name": "Shell", "bytes": "357092" }, { "name": "TSQL", "bytes": "117" } ], "symlink_target": "" }
import { VisibleCardData } from "./VisibleCardData"; import { SeatMoneyData } from "./SeatMoneyData"; import { BetsMoneyData } from "./BetsMoneyData"; import { AbstractData } from "../../core/data/AbstractData"; export class SrvTUShowDownData extends AbstractData { public seatID:number; public notify:boolean; public visibleCards:VisibleCardData[]; public wins:SeatMoneyData[]; public bets:BetsMoneyData[]; public casinoProfit:number; public bbjFee:number; constructor(parent?:AbstractData) { super(parent); } }
{ "content_hash": "0d5e48eb7dc9e1eecb9ae2eefba6f8aa", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 60, "avg_line_length": 24.454545454545453, "alnum_prop": 0.741635687732342, "repo_name": "gesh123/MyLibrary", "id": "0b8033c94f32ab107f407bc2c6c3a7014ab1ea6a", "size": "539", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "src/client/app/poker/connection/protocol/generated/data/SrvTUShowDownData.ts", "mode": "33188", "license": "mit", "language": [ { "name": "CSS", "bytes": "1191" }, { "name": "HTML", "bytes": "595" }, { "name": "JavaScript", "bytes": "7934" }, { "name": "TypeScript", "bytes": "1251145" } ], "symlink_target": "" }
module Downlow class Git < Fetcher handles(/^git\:\/\//) def fetch self.destination = destination.dirname + destination.stem git_clone rm_dot_git unless options[:keep_git] @local_path = destination end def git_clone system "`which git` clone #{url} #{destination.expand_path}" end def rm_dot_git FileUtils.rm_rf(destination + '.git') end end end
{ "content_hash": "5eeb28fced099ab5dabe5255cb3274bd", "timestamp": "", "source": "github", "line_count": 22, "max_line_length": 66, "avg_line_length": 19.90909090909091, "alnum_prop": 0.58675799086758, "repo_name": "quirkey/downlow", "id": "0bd80be4da06b8e30489ce43d86faaffcc16e777", "size": "438", "binary": false, "copies": "1", "ref": "refs/heads/master", "path": "lib/downlow/fetchers/git.rb", "mode": "33188", "license": "mit", "language": [ { "name": "Ruby", "bytes": "26489" } ], "symlink_target": "" }