text:
void GIFGetBackgroundColor(const ColorMapObject* const color_map,
                           int bgcolor_index, int transparent_index,
                           uint32_t* const bgcolor) {
  if (transparent_index != GIF_INDEX_INVALID &&
      bgcolor_index == transparent_index) {
    *bgcolor = GIF_TRANSPARENT_COLOR;  // Special case.
  } else if (color_map == NULL || color_map->Colors == NULL
             || bgcolor_index >= color_map->ColorCount) {
    *bgcolor = GIF_WHITE_COLOR;
    fprintf(stderr,
            "GIF decode warning: invalid background color index. Assuming "
            "white background.\n");
  } else {
    const GifColorType color = color_map->Colors[bgcolor_index];
    *bgcolor = (0xff        << 24)
             | (color.Red   << 16)
             | (color.Green <<  8)
             | (color.Blue  <<  0);
  }
}

int GIFReadGraphicsExtension(const GifByteType* const buf, int* const duration,
                             GIFDisposeMethod* const dispose,
                             int* const transparent_index) {
  const int flags = buf[1];
  const int dispose_raw = (flags >> GIF_DISPOSE_SHIFT) & GIF_DISPOSE_MASK;
  const int duration_raw = buf[2] | (buf[3] << 8);  // In 10 ms units.
  if (buf[0] != 4) return 0;
  *duration = duration_raw * 10;  // Duration is in 1 ms units.
  switch (dispose_raw) {
    case 3:
      *dispose = GIF_DISPOSE_RESTORE_PREVIOUS;
      break;
    case 2:
      *dispose = GIF_DISPOSE_BACKGROUND;
      break;
    case 1:
    case 0:
    default:
      *dispose = GIF_DISPOSE_NONE;
      break;
  }
  *transparent_index =
      (flags & GIF_TRANSPARENT_MASK) ? buf[4] : GIF_INDEX_INVALID;
  return 1;
}

static void Remap(const GifFileType* const gif, const uint8_t* const src,
                  int len, int transparent_index, uint32_t* dst) {
  int i;
  const GifColorType* colors;
  const ColorMapObject* const cmap =
      gif->Image.ColorMap ? gif->Image.ColorMap : gif->SColorMap;
  if (cmap == NULL) return;
  colors = cmap->Colors;

  for (i = 0; i < len; ++i) {
    const GifColorType c = colors[src[i]];
    dst[i] = (src[i] == transparent_index) ? GIF_TRANSPARENT_COLOR
           : c.Blue | (c.Green << 8) | (c.Red << 16) | (0xff << 24);
  }
}

int GIFReadFrame(GifFileType* const gif, int transparent_index,
                 GIFFrameRect* const gif_rect, WebPPicture* const picture) {
  WebPPicture sub_image;
  const GifImageDesc* const image_desc = &gif->Image;
  uint32_t* dst = NULL;
  uint8_t* tmp = NULL;
  int ok = 0;
  GIFFrameRect rect = {
      image_desc->Left, image_desc->Top, image_desc->Width, image_desc->Height
  };
  *gif_rect = rect;

  // Use a view for the sub-picture:
  if (!WebPPictureView(picture, rect.x_offset, rect.y_offset,
                       rect.width, rect.height, &sub_image)) {
    fprintf(stderr, "Sub-image %dx%d at position %d,%d is invalid!\n",
            rect.width, rect.height, rect.x_offset, rect.y_offset);
    return 0;
  }
  dst = sub_image.argb;

  tmp = (uint8_t*)malloc(rect.width * sizeof(*tmp));
  if (tmp == NULL) goto End;

  if (image_desc->Interlace) {  // Interlaced image.
    // We need 4 passes, with the following offsets and jumps.
    const int interlace_offsets[] = { 0, 4, 2, 1 };
    const int interlace_jumps[]   = { 8, 8, 4, 2 };
    int pass;
    for (pass = 0; pass < 4; ++pass) {
      int y;
      for (y = interlace_offsets[pass]; y < rect.height;
           y += interlace_jumps[pass]) {
        if (DGifGetLine(gif, tmp, rect.width) == GIF_ERROR) goto End;
        Remap(gif, tmp, rect.width, transparent_index,
              dst + y * sub_image.argb_stride);
      }
    }
  } else {  // Non-interlaced image.
    int y;
    for (y = 0; y < rect.height; ++y) {
      if (DGifGetLine(gif, tmp, rect.width) == GIF_ERROR) goto End;
      Remap(gif, tmp, rect.width, transparent_index,
            dst + y * sub_image.argb_stride);
    }
  }
  ok = 1;

 End:
  if (!ok) picture->error_code = sub_image.error_code;
  WebPPictureFree(&sub_image);
  free(tmp);
  return ok;
}

int GIFReadLoopCount(GifFileType* const gif, GifByteType** const buf,
                     int* const loop_count) {
  assert(!memcmp(*buf + 1, "NETSCAPE2.0", 11) ||
         !memcmp(*buf + 1, "ANIMEXTS1.0", 11));
  if (DGifGetExtensionNext(gif, buf) == GIF_ERROR) {
    return 0;
  }
  if (*buf == NULL) {
    return 0;  // Loop count sub-block missing.
  }
  if ((*buf)[0] < 3 || (*buf)[1] != 1) {
    return 0;   // wrong size/marker
  }
  *loop_count = (*buf)[2] | ((*buf)[3] << 8);
  return 1;
}

int GIFReadMetadata(GifFileType* const gif, GifByteType** const buf,
                    WebPData* const metadata) {
  const int is_xmp = !memcmp(*buf + 1, "XMP DataXMP", 11);
  const int is_icc = !memcmp(*buf + 1, "ICCRGBG1012", 11);
  assert(is_xmp || is_icc);
  (void)is_icc;  // silence unused warning.
  // Construct metadata from sub-blocks.
  // Usual case (including ICC profile): In each sub-block, the
  // first byte specifies its size in bytes (0 to 255) and the
  // rest of the bytes contain the data.
  // Special case for XMP data: In each sub-block, the first byte
  // is also part of the XMP payload. XMP in GIF also has a 257
  // byte padding data. See the XMP specification for details.
  while (1) {
    WebPData subblock;
    const uint8_t* tmp;
    if (DGifGetExtensionNext(gif, buf) == GIF_ERROR) {
      return 0;
    }
    if (*buf == NULL) break;  // Finished.
    subblock.size = is_xmp ? (*buf)[0] + 1 : (*buf)[0];
    assert(subblock.size > 0);
    subblock.bytes = is_xmp ? *buf : *buf + 1;
    // Note: We store returned value in 'tmp' first, to avoid
    // leaking old memory in metadata->bytes on error.
    tmp = (uint8_t*)realloc((void*)metadata->bytes,
                            metadata->size + subblock.size);
    if (tmp == NULL) {
      return 0;
    }
    memcpy((void*)(tmp + metadata->size),
           subblock.bytes, subblock.size);
    metadata->bytes = tmp;
    metadata->size += subblock.size;
  }
  if (is_xmp) {
    // XMP padding data is 0x01, 0xff, 0xfe ... 0x01, 0x00.
    const size_t xmp_pading_size = 257;
    if (metadata->size > xmp_pading_size) {
      metadata->size -= xmp_pading_size;
    }
  }
  return 1;
}

static void ClearRectangle(WebPPicture* const picture,
                           int left, int top, int width, int height) {
  int j;
  for (j = top; j < top + height; ++j) {
    uint32_t* const dst = picture->argb + j * picture->argb_stride;
    int i;
    for (i = left; i < left + width; ++i) {
      dst[i] = GIF_TRANSPARENT_COLOR;
    }
  }
}

void GIFClearPic(WebPPicture* const pic, const GIFFrameRect* const rect) {
  if (rect != NULL) {
    ClearRectangle(pic, rect->x_offset, rect->y_offset,
                   rect->width, rect->height);
  } else {
    ClearRectangle(pic, 0, 0, pic->width, pic->height);
  }
}

// TODO: Also used in picture.c. Move to a common location?
// Copy width x height pixels from 'src' to 'dst' honoring the strides.
static void CopyPlane(const uint8_t* src, int src_stride,
                      uint8_t* dst, int dst_stride, int width, int height) {
  while (height-- > 0) {
    memcpy(dst, src, width);
    src += src_stride;
    dst += dst_stride;
  }
}

void GIFCopyPixels(const WebPPicture* const src, WebPPicture* const dst) {
  assert(src->width == dst->width && src->height == dst->height);
  CopyPlane((uint8_t*)src->argb, 4 * src->argb_stride, (uint8_t*)dst->argb,
            4 * dst->argb_stride, 4 * src->width, src->height);
}

void GIFDisposeFrame(GIFDisposeMethod dispose, const GIFFrameRect* const rect,
                     const WebPPicture* const prev_canvas,
                     WebPPicture* const curr_canvas) {
  assert(rect != NULL);
  if (dispose == GIF_DISPOSE_BACKGROUND) {
    GIFClearPic(curr_canvas, rect);
  } else if (dispose == GIF_DISPOSE_RESTORE_PREVIOUS) {
    const int src_stride = prev_canvas->argb_stride;
    const uint32_t* const src =
        prev_canvas->argb + rect->x_offset + rect->y_offset * src_stride;
    const int dst_stride = curr_canvas->argb_stride;
    uint32_t* const dst =
        curr_canvas->argb + rect->x_offset + rect->y_offset * dst_stride;
    assert(prev_canvas != NULL);
    CopyPlane((uint8_t*)src, 4 * src_stride, (uint8_t*)dst, 4 * dst_stride,
              4 * rect->width, rect->height);
  }
}

void GIFBlendFrames(const WebPPicture* const src,
                    const GIFFrameRect* const rect, WebPPicture* const dst) {
  int j;
  assert(src->width == dst->width && src->height == dst->height);
  for (j = rect->y_offset; j < rect->y_offset + rect->height; ++j) {
    int i;
    for (i = rect->x_offset; i < rect->x_offset + rect->width; ++i) {
      const uint32_t src_pixel = src->argb[j * src->argb_stride + i];
      const int src_alpha = src_pixel >> 24;
      if (src_alpha != 0) {
        dst->argb[j * dst->argb_stride + i] = src_pixel;
      }
    }
  }
}

void GIFDisplayError(const GifFileType* const gif, int gif_error) {
  // libgif 4.2.0 has retired PrintGifError() and added GifErrorString().
#if LOCAL_GIF_PREREQ(4,2)
#if LOCAL_GIF_PREREQ(5,0)
  // Static string actually, hence the const char* cast.
  const char* error_str = (const char*)GifErrorString(
      (gif == NULL) ? gif_error : gif->Error);
#else
  const char* error_str = (const char*)GifErrorString();
  (void)gif;
#endif
  if (error_str == NULL) error_str = "Unknown error";
  fprintf(stderr, "GIFLib Error %d: %s\n", gif_error, error_str);
#else
  (void)gif;
  fprintf(stderr, "GIFLib Error %d: ", gif_error);
  PrintGifError();
  fprintf(stderr, "\n");
#endif
}

#else  // !WEBP_HAVE_GIF

static void ErrorGIFNotAvailable() {
  fprintf(stderr, "GIF support not compiled. Please install the libgif-dev "
          "package before building.\n");
}

void GIFGetBackgroundColor(const struct ColorMapObject* const color_map,
                           int bgcolor_index, int transparent_index,
                           uint32_t* const bgcolor) {
  (void)color_map;
  (void)bgcolor_index;
  (void)transparent_index;
  (void)bgcolor;
  ErrorGIFNotAvailable();
}

int GIFReadGraphicsExtension(const GifByteType* const data, int* const duration,
                             GIFDisposeMethod* const dispose,
                             int* const transparent_index) {
  (void)data;
  (void)duration;
  (void)dispose;
  (void)transparent_index;
  ErrorGIFNotAvailable();
  return 0;
}

int GIFReadFrame(struct GifFileType* const gif, int transparent_index,
                 GIFFrameRect* const gif_rect,
                 struct WebPPicture* const picture) {
  (void)gif;
  (void)transparent_index;
  (void)gif_rect;
  (void)picture;
  ErrorGIFNotAvailable();
  return 0;
}

int GIFReadLoopCount(struct GifFileType* const gif, GifByteType** const buf,
                     int* const loop_count) {
  (void)gif;
  (void)buf;
  (void)loop_count;
  ErrorGIFNotAvailable();
  return 0;
}

int GIFReadMetadata(struct GifFileType* const gif, GifByteType** const buf,
                    struct WebPData* const metadata) {
  (void)gif;
  (void)buf;
  (void)metadata;
  ErrorGIFNotAvailable();
  return 0;
}

void GIFDisposeFrame(GIFDisposeMethod dispose, const GIFFrameRect* const rect,
                     const struct WebPPicture* const prev_canvas,
                     struct WebPPicture* const curr_canvas) {
  (void)dispose;
  (void)rect;
  (void)prev_canvas;
  (void)curr_canvas;
  ErrorGIFNotAvailable();
}

void GIFBlendFrames(const struct WebPPicture* const src,
                    const GIFFrameRect* const rect,
                    struct WebPPicture* const dst) {
  (void)src;
  (void)rect;
  (void)dst;
  ErrorGIFNotAvailable();
}

void GIFDisplayError(const struct GifFileType* const gif, int gif_error) {
  (void)gif;
  (void)gif_error;
  ErrorGIFNotAvailable();
}

void GIFClearPic(struct WebPPicture* const pic,
                 const GIFFrameRect* const rect) {
  (void)pic;
  (void)rect;
  ErrorGIFNotAvailable();
}

void GIFCopyPixels(const struct WebPPicture* const src,
                   struct WebPPicture* const dst) {
  (void)src;
  (void)dst;
  ErrorGIFNotAvailable();
}

#endif  // WEBP_HAVE_GIF

// -----------------------------------------------------------------------------


text:
package org.sakaiproject.access.tool;

import java.io.IOException;
import java.io.InputStream;
import java.time.Year;
import java.util.Enumeration;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;

import org.sakaiproject.component.cover.ComponentManager;
import org.sakaiproject.content.api.ContentCollection;
import org.sakaiproject.content.api.ContentHostingService;
import org.sakaiproject.content.api.ContentResource;
import org.sakaiproject.content.api.ContentResourceEdit;
import org.sakaiproject.entity.api.Entity;
import org.sakaiproject.entity.api.Reference;
import org.sakaiproject.entity.api.ResourceProperties;
import org.sakaiproject.entity.api.ResourcePropertiesEdit;
import org.sakaiproject.event.api.NotificationService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.IdUsedException;
import org.sakaiproject.exception.InconsistentException;
import org.sakaiproject.user.api.User;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.tool.api.Session;

/**
 * <p>
 * Web extends access: all references are assumed to be under "/content", and POST to add a file is supported.
 * </p>
 *
 * @author Sakai Software Development Team
 */
@Slf4j
public class WebServlet extends AccessServlet
{
	protected ContentHostingService contentHostingService;
	protected UserDirectoryService userDirectoryService;

	/* (non-Javadoc)
	 * @see org.sakaiproject.access.tool.AccessServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);

		contentHostingService = ComponentManager.get(ContentHostingService.class);
		userDirectoryService = ComponentManager.get(UserDirectoryService.class);
	}
	/**
	 * Set active session according to sessionId parameter
	 */
	private void setSession( HttpServletRequest req )
	{
		String sessionId = req.getParameter("session");
		if ( sessionId != null)
		{
			Session session = sessionManager.getSession(sessionId);

			if (session != null)
			{
				session.setActive();
				sessionManager.setCurrentSession(session);
			}
		}
	}

	/**
	 * respond to an HTTP GET request
	 *
	 * @param req
	 *			 HttpServletRequest object with the client request
	 * @param res
	 *			 HttpServletResponse object back to the client
	 * @exception ServletException
	 *				  in case of difficulties
	 * @exception IOException
	 *				  in case of difficulties
	 */
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		setSession(req);
		super.dispatch(req, res);
	}

	/**
	 * respond to an HTTP POST request; only to handle the login process
	 *
	 * @param req
	 *        HttpServletRequest object with the client request
	 * @param res
	 *        HttpServletResponse object back to the client
	 * @exception ServletException
	 *            in case of difficulties
	 * @exception IOException
	 *            in case of difficulties
	 */
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		// catch the login helper posts
		String option = req.getPathInfo();
		String[] parts = option.split("/");
		if ((parts.length == 2) && ((parts[1].equals("login"))))
		{
			doLogin(req, res, null);
		}

		else if (FileUpload.isMultipartContent(req))
		{
			setSession(req);
			postUpload(req, res);
		}

		else
		{
			sendError(res, HttpServletResponse.SC_NOT_FOUND);
		}
	}

	/**
	 * Make any changes needed to the path before final "ref" processing.
	 *
	 * @param path
	 *        The path from the request.
	 * @param req
	 *        The request object.
	 * @return The path to use to make the Reference for further processing.
	 */
	protected String preProcessPath(String path, HttpServletRequest req)
	{
		// everything we work with is down the "content" part of the Sakai access URL space

		// if path is just "/", we don't really know if the request was to .../SERVLET or .../SERVLET/ - we want to preserve the trailing slash
		// the request URI will tell us
		if ("/".equals(path) && !(req.getRequestURI().endsWith("/"))) return "/content";

		return "/content" + path;
	}

	/**
	 * Handle file upload requests.
	 *
	 * @param req
	 * @param res
	 */
	protected void postUpload(HttpServletRequest req, HttpServletResponse res)
	{
		String path = req.getPathInfo();
		log.debug("path {}", path);
		if (path == null) path = "";
		// assume caller has verified that it is a request for content and that it's multipart
		// loop over attributes in request, picking out the ones
		// that are file uploads and doing them
		for (Enumeration e = req.getAttributeNames(); e.hasMoreElements();)
		{
			String iname = (String) e.nextElement();
			log.debug("Item {}", iname);
			Object o = req.getAttribute(iname);
			// NOTE: Fileitem is from
			// org.apache.commons.fileupload.FileItem, not
			// sakai's parameterparser version
			if (o != null && o instanceof FileItem)
			{
				FileItem fi = (FileItem) o;
				try (InputStream inputStream = fi.getInputStream())
				{
					if (!writeFile(fi.getName(), fi.getContentType(), inputStream, path, req, res, true)) return;
				} catch (IOException ioe) {
					log.warn("Problem getting InputStream", ioe);
				}
			}
		}
	}

	protected boolean writeFile(String name, String type, InputStream inputStream, String dir, HttpServletRequest req,
								HttpServletResponse resp, boolean mkdir)
	{
		try
		{
			// validate filename. Need to be fairly careful.
			int i = name.lastIndexOf(Entity.SEPARATOR);
			if (i >= 0) name = name.substring(i + 1);
			if (name.length() < 1)
			{
				log.debug("no name left / removal");
				resp.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			}

			// do our web thing with the path
			dir = preProcessPath(dir, req);

			// make sure there's a trailing separator
			if (!dir.endsWith(Entity.SEPARATOR)) dir = dir + Entity.SEPARATOR;

			// get a reference to the content collection - this lets us use alias and short refs
			Reference ref = entityManager.newReference(dir);

			// the reference id replaces the dir - as a fully qualified path (no alias, no short ref)
			dir = ref.getId();

			String path = dir + name;

			ResourcePropertiesEdit resourceProperties = contentHostingService.newResourceProperties();

			// Try to delete the resource
			try
			{
				log.debug("Trying Del {}", path);
				// The existing document may be a collection or a file.
				boolean isCollection = contentHostingService.getProperties(path).getBooleanProperty(
						ResourceProperties.PROP_IS_COLLECTION);

				if (isCollection)
				{
					log.debug("Can't del, iscoll");
					resp.sendError(HttpServletResponse.SC_FORBIDDEN);
					return false;
				}
				else
				{
					// not sure why removeesource(path) didn't
					// work for my workspace
					ContentResourceEdit edit = contentHostingService.editResource(path);
					// if (edit != null)
					log.debug("Got edit");
					contentHostingService.removeResource(edit);
				}
			}
			catch (IdUnusedException e)
			{
				// Normal situation - nothing to do
			}
			catch (Exception e)
			{
				log.debug("Can't del, exception {}: {}", e.getClass(), e.getMessage());
				resp.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			}

			// Add the resource

			try
			{
				User user = userDirectoryService.getCurrentUser();

				String mycopyright = "copyright (c)" + " " + Year.now() + ", " + user.getDisplayName()
						+ ". All Rights Reserved. ";

				resourceProperties.addProperty(ResourceProperties.PROP_COPYRIGHT, mycopyright);

				resourceProperties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, name);

				log.debug("Trying Add {}", path);
				ContentResource resource = contentHostingService.addResource(path, type, inputStream, resourceProperties,
						NotificationService.NOTI_NONE);

			}
			catch (InconsistentException e)
			{
				// get this error if containing dir doesn't exist
				if (mkdir)
				{
					try
					{
						ContentCollection collection = contentHostingService.addCollection(dir, resourceProperties);
						return writeFile(name, type, inputStream, dir, req, resp, false);
					}
					catch (Throwable ee)
					{
					}
				}
				log.debug("Add fail, inconsistent");
				resp.sendError(HttpServletResponse.SC_CONFLICT);
				return false;
			}
			catch (IdUsedException e)
			{
				// Should not happen because we deleted above (unless tawo requests at same time)
				log.debug("Add fail, in use");
				log.warn("access post IdUsedException:" + e.getMessage());

				resp.sendError(HttpServletResponse.SC_CONFLICT);
				return false;
			}
			catch (Exception e)
			{
				log.debug("Add failed, exception {}: {}", e.getClass(), e.getMessage());
				resp.sendError(HttpServletResponse.SC_FORBIDDEN);
				return false;
			}
		}
		catch (IOException e)
		{
			log.debug("overall fail IOException {}", e);
		}
		return true;
	}
}

redpajama_set_name: RedPajamaGithub


text:
Terminal Commands Used:

git clone git@github.com:DavidOKeefe/phase-0-gps-1.git
touch
git add
git commit -m
git push origin master
git co -b


text:
class SimpleMailer < ActionMailer::Base
  default from: "from@example.com"

  def sample_message
    mail to: 'to@example.com'
  end
end


text:
@interface SFTOperationQueueObserver () {
    NSOperationQueue *_operationQueue;
    callbackBlock _callbackBlock;
}

@end

@implementation SFTOperationQueueObserver

- (void)dealloc {
    [_operationQueue removeObserver:self forKeyPath:@"operationCount" context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context
{
    if ([object isEqual:_operationQueue] && [keyPath isEqualToString:@"operationCount"]) {
        if (_callbackBlock) {
            _callbackBlock(_operationQueue.operationCount);
        }
    }
}

- (void)observeQueue:(NSOperationQueue *)queue {
    _operationQueue = queue;

    [_operationQueue addObserver:self forKeyPath:@"operationCount" options:0 context:NULL];
}

- (void)setCallbackBlock:(callbackBlock)callbackBlock {
    _callbackBlock = callbackBlock;
}

@end


text:
class NewTabPageInterceptor : public net::URLRequestInterceptor {
 public:
  explicit NewTabPageInterceptor(const GURL& new_tab_url)
      : new_tab_url_(new_tab_url), weak_factory_(this) {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  }

  ~NewTabPageInterceptor() override {
    DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
  }

  base::WeakPtr<NewTabPageInterceptor> GetWeakPtr() {
    DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
    return weak_factory_.GetWeakPtr();
  }

  void SetNewTabPageURL(const GURL& new_tab_page_url) {
    DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
    new_tab_url_ = new_tab_page_url;
  }

 private:
  // Overrides from net::URLRequestInterceptor:
  net::URLRequestJob* MaybeInterceptRequest(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
    return nullptr;
  }

  net::URLRequestJob* MaybeInterceptResponse(
      net::URLRequest* request,
      net::NetworkDelegate* network_delegate) const override {
    DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
    if ((request->url() != new_tab_url_) ||
        (new_tab_url_ == GURL(chrome::kChromeSearchLocalNtpUrl))) {
      return nullptr;
    }
    // User has canceled this navigation so it shouldn't be redirected.
    if (request->status().status() == net::URLRequestStatus::CANCELED ||
        (request->status().status() == net::URLRequestStatus::FAILED &&
         request->status().error() == net::ERR_ABORTED)) {
      return nullptr;
    }

    // Request to NTP was successful.
    if (request->status().is_success() &&
        request->GetResponseCode() != net::HTTP_NO_CONTENT &&
        request->GetResponseCode() < 400) {
      return nullptr;
    }

    // Failure to load the NTP correctly; redirect to Local NTP.
    UMA_HISTOGRAM_ENUMERATION("InstantExtended.CacheableNTPLoad",
                              search::CACHEABLE_NTP_LOAD_FAILED,
                              search::CACHEABLE_NTP_LOAD_MAX);
    return new net::URLRequestRedirectJob(
        request, network_delegate, GURL(chrome::kChromeSearchLocalNtpUrl),
        net::URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
        "NTP Request Interceptor");
  }

  GURL new_tab_url_;
  base::WeakPtrFactory<NewTabPageInterceptor> weak_factory_;

  DISALLOW_COPY_AND_ASSIGN(NewTabPageInterceptor);
};

NewTabPageInterceptorService::NewTabPageInterceptorService(Profile* profile)
    : profile_(profile),
      template_url_service_(TemplateURLServiceFactory::GetForProfile(profile)) {
  DCHECK(profile_);
  if (template_url_service_)
    template_url_service_->AddObserver(this);
}

NewTabPageInterceptorService::~NewTabPageInterceptorService() {
  if (template_url_service_)
    template_url_service_->RemoveObserver(this);
}

void NewTabPageInterceptorService::OnTemplateURLServiceChanged() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  GURL new_tab_page_url(search::GetNewTabPageURL(profile_));
  content::BrowserThread::PostTask(
      content::BrowserThread::IO, FROM_HERE,
      base::Bind(&NewTabPageInterceptor::SetNewTabPageURL, interceptor_,
                 new_tab_page_url));
}

scoped_ptr<net::URLRequestInterceptor>
NewTabPageInterceptorService::CreateInterceptor() {
  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  scoped_ptr<NewTabPageInterceptor> interceptor(
      new NewTabPageInterceptor(search::GetNewTabPageURL(profile_)));
  interceptor_ = interceptor->GetWeakPtr();
  return interceptor.Pass();
}


text:
package org.jadira.usertype.dateandtime.legacyjdk;

import org.hibernate.usertype.ParameterizedType;
import org.jadira.usertype.dateandtime.legacyjdk.columnmapper.TimestampColumnTimestampMapper;
import org.jadira.usertype.spi.shared.AbstractVersionableUserType;
import org.jadira.usertype.spi.shared.IntegratorConfiguredType;

/**
 * Persist {@link java.util.Date} via Hibernate. The type is stored using the timezone as configured
 * using Hibernate's configuration property 'hibernate.jdbc.time_zone' and presented in the
 * JVM using the JVM's default zone.
 *
 * Alternatively provide the 'javaZone' can be used to similarly configure the zone of the
 * value on return from the database.
 */
public class PersistentTimestamp extends AbstractVersionableUserType<java.sql.Timestamp, java.sql.Timestamp, TimestampColumnTimestampMapper> implements ParameterizedType, IntegratorConfiguredType {

    private static final long serialVersionUID = -6656619988954550389L;

    @Override
    public int compare(Object o1, Object o2) {
        return ((java.util.Date) o1).compareTo((java.util.Date) o2);
    }
}


text:
/**
 * node 部分监听方法,实质为一个接口
 */
const http = require('http');
const url = require('url');
const log = require('../../lib/log');

const finishRes = (res, req, data) => {
    data = JSON.stringify(data || {status: 'error', code: 404});
    res.setHeader('Content-Type', 'application/json;charset=UTF-8');
    res.setHeader('Access-Control-Allow-Headers', 'X-Secret, Content-Type');
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.end(data);
};

const createServer = function (bridgeInst) {
    const apiInfo = url.parse(bridgeInst.api);
    const ptConfig = {
        port: apiInfo.port || 80,
        domain: apiInfo.hostname || '127.0.0.1'
    };
    const server = http.createServer((req, res) => {
        if (!bridgeInst.verfiyRequest(req)) {
            finishRes(res, req, {
                status: 'error',
                code: 400,
                message: '任务非法'
            });
            return;
        }
        let body = [];
        req.on('data', function (chunk) {
            body.push(chunk);
        })
        .on('end', function () {
            if (req.method === 'GET') {
                body = url.parse(req.url, true).query;
            }
            else {
                body = Buffer.concat(body).toString();
                try {
                    body = JSON.parse(body);
                }
                catch (e) {
                    finishRes(res, req, {
                        status: 'error',
                        code: 400,
                        message: '数据非法'
                    });
                    return;
                }
            }
            var resData = bridgeInst.resolveResponse(req, body);
            finishRes(res, req, {status: 'success', data: resData});
        })
        .on('error', function (e) {
            finishRes(res, req, {status: 'error', code: 500, message: e.message});
        });
    });

    server.listen(ptConfig.port, ptConfig.domain);
    log('Bridge-server listener on ' + ptConfig.domain + ':' + ptConfig.port, 'debug', 'BRIDGE_BOOT');
    return {
        destroy: function () {
            server.close();
            log('Close bridge server', 'debug', 'BRIDGE_BOOT');
        }
    };
};

module.exports = createServer;


text:
A modified, CommonJS version of Firebase's [BackboneFire](https://github.com/firebase/backbonefire) for [AmpersandJS](http://ampersandjs.com/) Collections.

## Installation
```
npm install ampfire-collection
```
If you want it automatically added to your project's *package.json* use:
```
npm install ampfire-collection --save
```

## Info
- It supports the [ampersand-rest-collection](https://github.com/ampersandjs/ampersand-rest-collection) module.
- The [ampersand-collection](https://github.com/ampersandjs/ampersand-collection) with the [ampersand-collection-rest-mixin](https://github.com/ampersandjs/ampersand-collection-rest-mixin) can be used if the lodash functions aren't needed.

## Basic Usage
First you should require the module as well as the [ampersand-model module](https://github.com/AmpersandJS/ampersand-model) for creating our collection's model instances.
``` javascript
var AmpfireCollection = require('ampfire-collection');
var Model = require('ampersand-model');
```
Then you can create an ampersand-model to pass to your collection
```javascript
var ExampleModel = Model.extend({
    props: {
      date: 'string',
      name: 'string',
      url: 'string',
      viewed: 'boolean',
      id: 'string'
    }
  });
```
Next simply extend the AmpfireCollection passing it our newly created *ExampleModel* and the firebase url
```javascript
  var RealtimeCollection = AmpfireCollection.extend({
    url: 'https://example-db.firebaseio.com/todos',
    model: ExampleModel,
    autoSync: true // true by default
  });

  // Instantiate the collection
  var realtimeCollection = new RealtimeCollection();

  realtimeCollection.on('sync', function(collection) {
    console.log('collection loaded', collection);
  });
```
The rest of the API is the same as that of [BackboneFire](https://github.com/firebase/backbonefire)

## Dependencies
- [ampersand-rest-collection](https://github.com/AmpersandJS/ampersand-rest-collection) module
- lodash functions
    + extend: lodash.object
    + keys: lodash.object
    + has: lodash.object
    + isObject: lodash.lang
    + isFunction: lodash.lang
    + isArray: lodash.lang
    + clone: lodash.lang
    + bind: lodash.function
    + defer: lodash.function
    + each: lodash.collection
    + find: lodash.collection,
    + difference: lodash.array
    + union: lodash.array

## Tests
Coming soon...

## Demo
Coming soon...

## Credits
This is all just a modification of the amazing work the [Firebase](https://github.com/firebase) team did on [BackboneFire](https://github.com/firebase/backbonefire). It uses the awesome [AmpersandJS Framework](http://ampersandjs.com/) from the guys over at [&yet](https://github.com/andyet).

## Licence
MIT


text:
<?php

namespace Uploadmgmt\Controller;

use Uploadmgmt\Model\FileuploadStatus;
use Uploadmgmt\Model\Uploadmgmtdao;
use Uploadmgmt\Model\Photosmgmt;
use Privatespacelogin\Model\PrivatespaceloginDao;
use Privatespacelogin\Model\Privatespacelogin;
use ExtLib\MCrypt;
use ExtLib\Utils;
use Uploadmgmt\Model\Fileupload;
use ExtLib\FileManager;
use Fichiers\Model\FilesCategories;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\Mvc\I18n\Translator;
use Application\Factory\CacheDataListener;

/**
 * Class UploadmgmtController
 * @package Uploadmgmt\Controller
 */
class UploadmgmtController extends AbstractActionController
{
    protected $path;
    protected $paththumbnails;
    protected $publicPath;

    protected $translator;
    protected $cache;

    /**
     * UploadmgmtController constructor.
     * @param CacheDataListener $cacheDataListener
     * @param Translator $translator
     */
    public function __construct(CacheDataListener $cacheDataListener, Translator $translator)
    {
        $this->cache = $cacheDataListener;
        $this->translator = $translator;
        $this->publicPath = 'public/';
        $this->path = 'uploadedfilesbank/';
        $this->paththumbnails = 'uploadedfilesbank/thumbnails/';
    }

    /**
     * @return ViewModel
     */
    public function indexAction()
    {

        $photosmgmtdao = new Uploadmgmtdao();
        return new ViewModel(array(
            'photos' => $photosmgmtdao->getPhotoWaitStatus()
        ));
    }

    /**
     * @return ViewModel
     */
    public function validatedfilesAction()
    {
        $photosmgmtdao = new Uploadmgmtdao();
        return new ViewModel(array(
            'photos' => $photosmgmtdao->getPhotoValidateStatus()
        ));
    }

    /**
     * @return JsonModel
     */
    public function rotaterightAction()
    {
        $idPhoto = (int)$this->params()->fromRoute('id', 0);
        $Photosmgmt = new Photosmgmt();
        $Photosmgmt->photoRotate($idPhoto, -90);
        return new JsonModel(array(
            'status' => 'ok'
        ));
    }

    /**
     * @return JsonModel
     */
    public function rotateleftAction()
    {
        $idPhoto = (int)$this->params()->fromRoute('id', 0);
        $Photosmgmt = new Photosmgmt();
        $Photosmgmt->photoRotate($idPhoto, 90);
        return new JsonModel(array(
            'status' => 'ok'
        ));
    }

    /**
     * @return JsonModel
     */
    public function validatefileAction()
    {
        $idFile = (int)$this->params()->fromRoute('id', 0);
        $uploadfilemgmtDao = new Uploadmgmtdao();
        $uploadfilemgmtDao->updateStatus($idFile, FileuploadStatus::$VALIDATED);
        return new JsonModel(array(
            'status' => 'ok',
        ));
    }

    /**
     * @return JsonModel
     */
    public function deletefileAction()
    {
        $idFile = (int)$this->params()->fromRoute('id', 0);
        if (!isset($idFile) || ($idFile < 1)) {
            $this->response->setStatusCode(502);
            return new JsonModel(array(
                'status' => 'ko',
                'error' => $this->translator->translate('numéro de photo invalide ou Statut non autorisé')
            ));
        }
        $photosmgmt = new Photosmgmt();
        $fileuploadmgmtdao = new Uploadmgmtdao();
        $file = $fileuploadmgmtdao->getPhoto($idFile);
        $status = FileuploadStatus::$REFUSED;

        if(strcmp($file['status'], FileuploadStatus::$VALIDATED)===0){
            $status = FileuploadStatus::$OBSOLETE;
        }
        if ($fileuploadmgmtdao->updateStatus($idFile, $status)) {
            if(in_array(strtolower($file['type']), FilesCategories::$imgList)){
                $photosmgmt->deleteFile($this->publicPath . $file['path'] . '/' . $file['name']);
                $photosmgmt->deleteFile($this->publicPath . $file['thumbnailpath'] . '/' . $file['thumbnail']);
                $photosmgmt->deleteOriTypePhoto($this->publicPath . $file['path'], $file['name']);
                $photosmgmt->deleteOriTypePhoto($this->publicPath . $file['thumbnailpath'], $file['thumbnail']);
            }

            else {
                $photosmgmt->deleteFile($this->publicPath . $file['path'] . '/' . $file['name']);
            }
        }
        else {
            $this->response->setStatusCode(502);
            return new JsonModel(array(
                'status' => 'ko',
                'error' => $this->translator->translate('un problème est survenue lors de la mise à jour')
            ));
        }
        return new JsonModel(array(
            'status' => 'ok',
        ));
    }

    /**
     * @return \Zend\Http\Response|JsonModel
     */
    public function updateAction()
    {
        $idFile = (int)$this->params()->fromRoute('id', 0);
        $commenter = $this->params()->fromPost('commenter');
        $status = $this->params()->fromPost('status');
        $photosmgmtdao = new Uploadmgmtdao();
        if ($idFile < 1) {
            $this->response->setStatusCode(500);
            return new JsonModel(array(
                'status' => 'ko',
                'error' => $this->translator->translate('numéro de photo invalide ')
            ));
        }
        $photosmgmtdao->updateComment($idFile, array('commenter' => $commenter));
        $action = 'index';
        if (strcmp($status, FileuploadStatus::$VALIDATED) == 0) {
            $action = 'validatedfiles';
        }
        return $this->redirect()->toRoute(
            'Uploadmgmt', array(
                'action' => $action
            )
        );
    }

    /**
     * @return JsonModel
     */
    public function backtooriginalAction()
    {
        $photosmgmtdao = new Uploadmgmtdao();
        $idFile = (int)$this->params()->fromRoute('id', 0);
        $photo = $photosmgmtdao->getPhoto($idFile);
        $photosmgmt = new Photosmgmt();

        $result = $photosmgmt->photoBackToOriginal($photo);

        if (strcmp($result['status'], 'ko') == 0) {
            $this->response->setStatusCode(502);
        }

        return new JsonModel($result);
    }

    /**
     * @return \Zend\View\Model\JsonModel
     * input in Post :
     * newfile(the file to upload)
     * comment (text)
     * author (text)
     * userid (text)
     * email (text)
     * lat (text)
     * lng (text)
     * status ('waiting' => 'waiting', 'validated' => 'validated', 'refused' => 'refused', 'obsolete' => 'obsolete')
     *
     * by default the file uploaded will be renamed if a file with the same name already exists
     */
    public function uploadfileAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $outils = new FileManager();
            $filesDao = new Uploadmgmtdao();
            $savethumbnailpath = 'img';

            if (strcmp($_FILES['newfile']['name'], "") != 0) {
                $extension = $outils->extractExtension($_FILES['newfile']['name']);
                $fichieruploaded = "";
                if (!is_uploaded_file($_FILES['newfile']['tmp_name'])) {

                    $error = $this->translator->translate("Le fichier est inaccessible");
                    $this->response->setStatusCode(500);
                    return new JsonModel(array(
                        'error' => $error
                    ));
                }

                // Test file size
                if ($_FILES['newfile']['size'] >= 10483760) {

                    $error = $this->translator->translate("La taille du fichier est supérieur à 10 Mo");
                    $this->response->setStatusCode(500);
                    return new JsonModel(array(
                        'error' => $error
                    ));
                }

                if (in_array(strtolower($extension), FilesCategories::$listeextension) == false) {
                    $error = $this->translator->translate("Le fichier doit avoir l\'extension") . " 'jpg','jpeg', 'png', 'bmp', 'doc', 'docx', 'rtf', 'txt', 'xls', 'xlsx',
                    'ppt', 'pptx', 'pdf', 'epub', 'odt', 'ods', 'mp4', 'mkv', 'ogv', 'mp3', 'wav', 'ogg', 'gz', 'zip', 'tar'";
                    $this->response->setStatusCode(500);
                    return new JsonModel(array(
                        'error' => $error
                    ));
                } else {
                    $utils = new Utils();
                    $resultUpload = array();
                    $thumbnailfilename = '';
                    //By default if a file already exists, it will be renamed
                    if (in_array(strtolower($extension), FilesCategories::$imgList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbname = "thumb";
                        $thumbname .= $outils->formatNameFile($_FILES['newfile']['name']);
                        //a thumbnail is created only if it is a jpeg or a png image
                        if (in_array(strtolower($extension), array('jpg', 'jpeg', 'png')) == true) {
                            $thumbnailfilename = $outils->reduit_fichier($resultUpload["filename"][1], $thumbname, 150, 200, $this->publicPath.$this->path, $this->publicPath.$this->paththumbnails, ""); //create thumbnail
                        }
                        $savethumbnailpath = $this->paththumbnails;
                    } elseif (in_array(strtolower($extension), FilesCategories::$wordList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$wordImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$documentList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$documentImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$excelList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$excelImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$audioList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$audioImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$videoList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$videoImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$presentationList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$presentationImg;
                        $savethumbnailpath = 'img/';
                    } elseif (in_array(strtolower($extension), FilesCategories::$archiveList) == true) {
                        $resultUpload = $outils->uploadfiles($_FILES['newfile'], $this->publicPath.$this->path, "", FileManager::$renameExistingFile); //envoi du fichier original
                        $thumbnailfilename = FilesCategories::$archiveImg;
                        $savethumbnailpath = 'img/';
                    }

                    if ($resultUpload["filename"][0]) {

                        if ($resultUpload["renameExisting"][0] == true) {
                            $file = $filesDao->getFileByFilename($resultUpload["filename"][1]);
                            $file->setName($resultUpload["renameExisting"][1]);
                            $filesDao->saveFileupload($file);
                        }
                        $file = new Fileupload();
                        $file->setType($extension);
                        $file->setName($resultUpload["filename"][1]);
                        $file->setPath($this->path);
                        $file->setThumbnail($thumbnailfilename);
                        $file->setThumbnailpath($savethumbnailpath);
                        $file->setComment($utils->stripTags_replaceHtmlChar_trim($request->getPost('comment'), true, true, true));
                        $file->setAuthor($utils->stripTags_replaceHtmlChar_trim($request->getPost('author'), true, true, true));
                        $file->setEmail($utils->stripTags_replaceHtmlChar_trim($request->getPost('email'), true, true, true));
                        $file->setUserid($utils->stripTags_replaceHtmlChar_trim($request->getPost('userid'), true, true, true));
                        $file->setLat($utils->stripTags_replaceHtmlChar_trim($request->getPost('lat'), true, true, true));
                        $file->setLng($utils->stripTags_replaceHtmlChar_trim($request->getPost('lng'), true, true, true));
                        $file->setStatus($utils->stripTags_replaceHtmlChar_trim($request->getPost('status'), true, true, true));
                        $filesDao->saveFileupload($file);

                        // Redirect to list of fichiers
                        return new JsonModel(array(
                            'status' => $this->translator->translate("OK")
                        ));
                    } else {
                        $error = $this->translator->translate("Une erreur est survenue sur le serveur");
                        $this->response->setStatusCode(500);
                        return new JsonModel(array(
                            'error' => $error
                        ));
                    }
                }
            } else {
                $error = $this->translator->translate("Aucun fichier n'est sélectionné");
                //print_r($error);
                //exit;
                $this->response->setStatusCode(500);
                return new JsonModel(array(
                    'error' => $error
                ));
            }
        } else {
            $error = $this->translator->translate('Ce n\'est pas une requête POST');
            $this->response->setStatusCode(500);
            return new JsonModel(array(
                'error' => $error
            ));
        }
    }

}


text:
#include <sys/cdefs.h>
__FBSDID("$FreeBSD: head/lib/libc/stdlib/hcreate.c 326193 2017-11-25 17:12:48Z pfg $");

#include <search.h>
#include <stdbool.h>
#include <stddef.h>

/*
 * Thread unsafe interface: use a single process-wide hash table and
 * forward calls to *_r() functions.
 */

static struct hsearch_data global_hashtable;
static bool global_hashtable_initialized = false;

int
hcreate(size_t nel)
{

	return (1);
}

void
hdestroy(void)
{

	/* Destroy global hash table if present. */
	if (global_hashtable_initialized) {
		hdestroy_r(&global_hashtable);
		global_hashtable_initialized = false;
	}
}

ENTRY *
hsearch(ENTRY item, ACTION action)
{
	ENTRY *retval;

	/* Create global hash table if needed. */
	if (!global_hashtable_initialized) {
		if (hcreate_r(0, &global_hashtable) == 0)
			return (NULL);
		global_hashtable_initialized = true;
	}
	if (hsearch_r(item, action, &retval, &global_hashtable) == 0)
		return (NULL);
	return (retval);
}


text:
var milista = new List();
var divContainer = document.getElementById('container');

var TextoDeArea = document.createElement('textarea');
    TextoDeArea.setAttribute('type','textarea');
    TextoDeArea.setAttribute('id','texto');
    divContainer.appendChild(TextoDeArea);

var botonAdd = document.createElement('input');
    botonAdd.setAttribute('type','button');
    botonAdd.setAttribute('value','Agregar');
    botonAdd.setAttribute('id','botonEnviar');
    divContainer.appendChild(botonAdd);

var botonClear = document.createElement('input');
    botonClear.setAttribute('type','button');
    botonClear.setAttribute('value','Limpiar');
    botonClear.setAttribute('id','botonLimpiar');
    divContainer.appendChild(botonClear);

List.prototype.addTable = function () {
	var that = this;
    var divResultado = document.getElementById('resultado');
    divResultado.innerHTML = "";
    var tabla = document.createElement('table');
    divResultado.appendChild(tabla);
    this.front();
    this.dataStore.forEach( function(e,i) {

        var tr = document.createElement('tr');
        var td1 = document.createElement('td');
        var td2 = document.createElement('td');
        var td3 = document.createElement('td');
        tabla.appendChild(tr);
        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);
        td1.innerHTML = i+1;
        td2.innerHTML = e; //this.getElement(i);
     	var botonIndividual = document.createElement('button');
     	botonIndividual.innerHTML = "Eliminiar";
     	td3.appendChild(botonIndividual);
     	botonIndividual.addEventListener('click',function() {
     		that.removeId(i);
     		that.addTable();
     	});
    });
}

List.prototype.removeId = function (id) {
    this.dataStore.splice(id, 1);
    --this.pos;
}

function capturarDatos() {
    var miTexto = document.getElementById('texto').value;
    milista.append(miTexto);
    milista.addTable();
}

function borrartabla() {
    var divResultado = document.getElementById('resultado');
    divResultado.innerHTML = " ";
    milista.clear();

    var TextoDeArea = document.getElementById('texto');
    TextoDeArea.value = '';
}

botonAdd.addEventListener('click', capturarDatos);
botonClear.addEventListener('click', borrartabla);


text:
package google

import (
	"context"
	"io"

	"cloud.google.com/go/storage"
	"github.com/pkg/errors"
	"google.golang.org/api/iterator"

	"github.com/graymeta/stow"
)

type Container struct {
	// Name is needed to retrieve items.
	name string

	// Client is responsible for performing the requests.
	client *storage.Client

	// ctx is used on google storage API calls
	ctx context.Context
}

// ID returns a string value which represents the name of the container.
func (c *Container) ID() string {
	return c.name
}

// Name returns a string value which represents the name of the container.
func (c *Container) Name() string {
	return c.name
}

// Bucket returns the google bucket attributes
func (c *Container) Bucket() *storage.BucketHandle{
	return c.client.Bucket(c.name)
}

// Item returns a stow.Item instance of a container based on the
// name of the container
func (c *Container) Item(id string) (stow.Item, error) {
	item, err := c.Bucket().Object(id).Attrs(c.ctx)
	if err != nil {
		if err == storage.ErrObjectNotExist {
			return nil, stow.ErrNotFound
		}
		return nil, err
	}

	return c.convertToStowItem(item)
}

// Items retrieves a list of items that are prepended with
// the prefix argument. The 'cursor' variable facilitates pagination.
func (c *Container) Items(prefix string, cursor string, count int) ([]stow.Item, string, error) {
	query := &storage.Query{Prefix: prefix}
	call := c.Bucket().Objects(c.ctx, query)

	p := iterator.NewPager(call, count, cursor)
	var results []*storage.ObjectAttrs
	nextPageToken, err := p.NextPage(&results)
	if err != nil {
		return nil, "", err
	}

	var items []stow.Item
	for _, item := range results {
		i, err := c.convertToStowItem(item)
		if err != nil {
			return nil, "", err
		}

		items = append(items, i)
	}

	return items, nextPageToken, nil
}

// RemoveItem will delete a google storage Object
func (c *Container) RemoveItem(id string) error {
	return c.Bucket().Object(id).Delete(c.ctx)
}

// Put sends a request to upload content to the container. The arguments
// received are the name of the item, a reader representing the
// content, and the size of the file.
func (c *Container) Put(name string, r io.Reader, size int64, metadata map[string]interface{}) (stow.Item, error) {
	obj := c.Bucket().Object(name)

	mdPrepped, err := prepMetadata(metadata)
	if err != nil {
		return nil, err
	}

	w := obj.NewWriter(c.ctx)
	if _, err := io.Copy(w, r); err != nil {
		return nil, err
	}
	w.Close()

	attr, err := obj.Update(c.ctx, storage.ObjectAttrsToUpdate{Metadata: mdPrepped})
	if err != nil {
		return nil, err
	}

	return c.convertToStowItem(attr)
}

func (c *Container) convertToStowItem(attr *storage.ObjectAttrs) (stow.Item, error) {
	u, err := prepUrl(attr.MediaLink)
	if err != nil {
		return nil, err
	}

	mdParsed, err := parseMetadata(attr.Metadata)
	if err != nil {
		return nil, err
	}

	return &Item{
		name:         attr.Name,
		container:    c,
		client:       c.client,
		size:         attr.Size,
		etag:         attr.Etag,
		hash:         string(attr.MD5),
		lastModified: attr.Updated,
		url:          u,
		metadata:     mdParsed,
		object:       attr,
		ctx:          c.ctx,
	}, nil
}

func parseMetadata(metadataParsed map[string]string) (map[string]interface{}, error) {
	metadataParsedMap := make(map[string]interface{}, len(metadataParsed))
	for key, value := range metadataParsed {
		metadataParsedMap[key] = value
	}
	return metadataParsedMap, nil
}

func prepMetadata(metadataParsed map[string]interface{}) (map[string]string, error) {
	returnMap := make(map[string]string, len(metadataParsed))
	for key, value := range metadataParsed {
		str, ok := value.(string)
		if !ok {
			return nil, errors.Errorf(`value of key '%s' in metadata must be of type string`, key)
		}
		returnMap[key] = str
	}
	return returnMap, nil
}


text:
class CreateStudents < ActiveRecord::Migration
  def change
    create_table :students do |t|
      t.string :name
      t.string :surname
      t.integer :age

      t.timestamps
    end
  end
end


text:
package com.alarm.alarmweb.demo.spring.prepost;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan("com.alarm.alarmweb.demo.spring.prepost")
public class PrePostConfig {

    @Bean(initMethod = "init", destroyMethod = "destroy") //1
    BeanWayService beanWayService() {
        return new BeanWayService();
    }

    @Bean
    JSR250WayService jsr250WayService() {
        return new JSR250WayService();
    }

}


text:
from asyncio import (
    gather,
    ensure_future,
    get_event_loop,
    iscoroutine,
    iscoroutinefunction,
)
from collections import namedtuple
from collections.abc import Iterable
from functools import partial

from typing import List  # flake8: noqa

Loader = namedtuple("Loader", "key,future")

def iscoroutinefunctionorpartial(fn):
    return iscoroutinefunction(fn.func if isinstance(fn, partial) else fn)

class DataLoader(object):
    batch = True
    max_batch_size = None  # type: int
    cache = True

    def __init__(
        self,
        batch_load_fn=None,
        batch=None,
        max_batch_size=None,
        cache=None,
        get_cache_key=None,
        cache_map=None,
        loop=None,
    ):

        self._loop = loop

        if batch_load_fn is not None:
            self.batch_load_fn = batch_load_fn

        assert iscoroutinefunctionorpartial(
            self.batch_load_fn
        ), "batch_load_fn must be coroutine. Received: {}".format(self.batch_load_fn)

        if not callable(self.batch_load_fn):
            raise TypeError(  # pragma: no cover
                (
                    "DataLoader must be have a batch_load_fn which accepts "
                    "Iterable<key> and returns Future<Iterable<value>>, but got: {}."
                ).format(batch_load_fn)
            )

        if batch is not None:
            self.batch = batch  # pragma: no cover

        if max_batch_size is not None:
            self.max_batch_size = max_batch_size

        if cache is not None:
            self.cache = cache  # pragma: no cover

        self.get_cache_key = get_cache_key or (lambda x: x)

        self._cache = cache_map if cache_map is not None else {}
        self._queue = []  # type: List[Loader]

    @property
    def loop(self):
        if not self._loop:
            self._loop = get_event_loop()

        return self._loop

    def load(self, key=None):
        """
        Loads a key, returning a `Future` for the value represented by that key.
        """
        if key is None:
            raise TypeError(  # pragma: no cover
                (
                    "The loader.load() function must be called with a value, "
                    "but got: {}."
                ).format(key)
            )

        cache_key = self.get_cache_key(key)

        # If caching and there is a cache-hit, return cached Future.
        if self.cache:
            cached_result = self._cache.get(cache_key)
            if cached_result:
                return cached_result

        # Otherwise, produce a new Future for this value.
        future = self.loop.create_future()
        # If caching, cache this Future.
        if self.cache:
            self._cache[cache_key] = future

        self.do_resolve_reject(key, future)
        return future

    def do_resolve_reject(self, key, future):
        # Enqueue this Future to be dispatched.
        self._queue.append(Loader(key=key, future=future))
        # Determine if a dispatch of this queue should be scheduled.
        # A single dispatch should be scheduled per queue at the time when the
        # queue changes from "empty" to "full".
        if len(self._queue) == 1:
            if self.batch:
                # If batching, schedule a task to dispatch the queue.
                enqueue_post_future_job(self.loop, self)
            else:
                # Otherwise dispatch the (queue of one) immediately.
                dispatch_queue(self)  # pragma: no cover

    def load_many(self, keys):
        """
        Loads multiple keys, returning a list of values

        >>> a, b = await my_loader.load_many([ 'a', 'b' ])

        This is equivalent to the more verbose:

        >>> a, b = await gather(
        >>>    my_loader.load('a'),
        >>>    my_loader.load('b')
        >>> )
        """
        if not isinstance(keys, Iterable):
            raise TypeError(  # pragma: no cover
                (
                    "The loader.load_many() function must be called with Iterable<key> "
                    "but got: {}."
                ).format(keys)
            )

        return gather(*[self.load(key) for key in keys])

    def clear(self, key):
        """
        Clears the value at `key` from the cache, if it exists. Returns itself for
        method chaining.
        """
        cache_key = self.get_cache_key(key)
        self._cache.pop(cache_key, None)
        return self

    def clear_all(self):
        """
        Clears the entire cache. To be used when some event results in unknown
        invalidations across this particular `DataLoader`. Returns itself for
        method chaining.
        """
        self._cache.clear()
        return self

    def prime(self, key, value):
        """
        Adds the provied key and value to the cache. If the key already exists, no
        change is made. Returns itself for method chaining.
        """
        cache_key = self.get_cache_key(key)

        # Only add the key if it does not already exist.
        if cache_key not in self._cache:
            # Cache a rejected future if the value is an Error, in order to match
            # the behavior of load(key).
            future = self.loop.create_future()
            if isinstance(value, Exception):
                future.set_exception(value)
            else:
                future.set_result(value)

            self._cache[cache_key] = future

        return self

def enqueue_post_future_job(loop, loader):
    async def dispatch():
        dispatch_queue(loader)

    loop.call_soon(ensure_future, dispatch())

def get_chunks(iterable_obj, chunk_size=1):
    chunk_size = max(1, chunk_size)
    return (
        iterable_obj[i : i + chunk_size]
        for i in range(0, len(iterable_obj), chunk_size)
    )

def dispatch_queue(loader):
    """
    Given the current state of a Loader instance, perform a batch load
    from its current queue.
    """
    # Take the current loader queue, replacing it with an empty queue.
    queue = loader._queue
    loader._queue = []

    # If a max_batch_size was provided and the queue is longer, then segment the
    # queue into multiple batches, otherwise treat the queue as a single batch.
    max_batch_size = loader.max_batch_size

    if max_batch_size and max_batch_size < len(queue):
        chunks = get_chunks(queue, max_batch_size)
        for chunk in chunks:
            ensure_future(dispatch_queue_batch(loader, chunk))
    else:
        ensure_future(dispatch_queue_batch(loader, queue))

async def dispatch_queue_batch(loader, queue):
    # Collect all keys to be loaded in this dispatch
    keys = [loaded.key for loaded in queue]

    # Call the provided batch_load_fn for this loader with the loader queue's keys.
    batch_future = loader.batch_load_fn(keys)

    # Assert the expected response from batch_load_fn
    if not batch_future or not iscoroutine(batch_future):
        return failed_dispatch(  # pragma: no cover
            loader,
            queue,
            TypeError(
                (
                    "DataLoader must be constructed with a function which accepts "
                    "Iterable<key> and returns Future<Iterable<value>>, but the function did "
                    "not return a Coroutine: {}."
                ).format(batch_future)
            ),
        )

    try:
        values = await batch_future
        if not isinstance(values, Iterable):
            raise TypeError(  # pragma: no cover
                (
                    "DataLoader must be constructed with a function which accepts "
                    "Iterable<key> and returns Future<Iterable<value>>, but the function did "
                    "not return a Future of a Iterable: {}."
                ).format(values)
            )

        values = list(values)
        if len(values) != len(keys):
            raise TypeError(  # pragma: no cover
                (
                    "DataLoader must be constructed with a function which accepts "
                    "Iterable<key> and returns Future<Iterable<value>>, but the function did "
                    "not return a Future of a Iterable with the same length as the Iterable "
                    "of keys."
                    "\n\nKeys:\n{}"
                    "\n\nValues:\n{}"
                ).format(keys, values)
            )

        # Step through the values, resolving or rejecting each Future in the
        # loaded queue.
        for loaded, value in zip(queue, values):
            if isinstance(value, Exception):
                loaded.future.set_exception(value)
            else:
                loaded.future.set_result(value)

    except Exception as e:
        return failed_dispatch(loader, queue, e)

def failed_dispatch(loader, queue, error):
    """
    Do not cache individual loads if the entire batch dispatch fails,
    but still reject each request so they do not hang.
    """
    for loaded in queue:
        loader.clear(loaded.key)
        loaded.future.set_exception(error)


text:
require 'json'
require 'virtus'

# base query and filter classes needed by the attributes
require 'daedal/queries/query'
require 'daedal/filters/filter'
require 'daedal/facets/facet'

# attributes
require 'daedal/attributes/operator'
require 'daedal/attributes/match_type'
require 'daedal/attributes/query_array'
require 'daedal/attributes/filter_array'
require 'daedal/attributes/score_mode'
require 'daedal/attributes/lower_case_string'
require 'daedal/attributes/distance_unit'
require 'daedal/attributes/query'
require 'daedal/attributes/filter'
require 'daedal/attributes/field'
require 'daedal/attributes/query_value'
require 'daedal/attributes/boost'
require 'daedal/attributes/score_function_array'
require 'daedal/attributes/type_value'
require 'daedal/attributes/flag'

# filters
require 'daedal/filters/exists_filter'
require 'daedal/filters/term_filter'
require 'daedal/filters/terms_filter'
require 'daedal/filters/range_filter'
require 'daedal/filters/geo_distance_filter'
require 'daedal/filters/geo_distance_range_filter'
require 'daedal/filters/and_filter'
require 'daedal/filters/not_filter'
require 'daedal/filters/or_filter'
require 'daedal/filters/bool_filter'
require 'daedal/filters/nested_filter'
require 'daedal/filters/type_filter'

# queries
require 'daedal/queries/match_all_query'
require 'daedal/queries/bool_query'
require 'daedal/queries/constant_score_query'
require 'daedal/queries/dis_max_query'
require 'daedal/queries/filtered_query'
require 'daedal/queries/match_query'
require 'daedal/queries/multi_match_query'
require 'daedal/queries/nested_query'
require 'daedal/queries/prefix_query'
require 'daedal/queries/fuzzy_query'
require 'daedal/queries/query_string_query'
require 'daedal/queries/term_query'
require 'daedal/queries/terms_query'
require 'daedal/queries/range_query'
require 'daedal/queries/function_score_query'
require 'daedal/queries/simple_query_string_query'

# facets


text:
set -e

green="\033[0;32m"
cyan="\033[0;36m"
yellow="\033[0;33m"
red="\033[0;31m"
default="\033[0m"

### Install Ansible
if [[ "$OSTYPE" == "darwin"* ]]; then
  if ! [[ -f ~/.ansible.cfg ]]; then
    blank_cfg=1
  fi
else
  if ! [[ -f /etc/ansible/ansible.cfg ]]; then
    blank_cfg=1
  fi
fi

if ! command -v ansible >/dev/null; then
  echo -e "${green}Installing Ansible${default}"
  # https://docs.ansible.com/ansible/latest/installation_guide/intro_installation.html

  if [[ "$OSTYPE" == "darwin"* ]]; then
    if ! command -v brew >/dev/null; then
      echo -e "${red}Error: Homebrew is not installed (https://brew.sh/#install)${default}"
      exit 1
    fi

    # Install with Homebrew instead of pip because:
    #  - pip could not be installed
    #  - pip could install Ansible somewhere not in PATH
    brew install ansible
  else
    sudo apt update
    sudo apt install -y software-properties-common
    sudo apt-add-repository -y ppa:ansible/ansible
    sudo apt install -y ansible
  fi
fi
# Improvement: upgrade if version is too old

### Mac OS X warning
if [[ "$OSTYPE" == "darwin"* ]]; then
  echo
  echo -e "${yellow}Note: quickstart support on Mac OS X is incomplete, because we don't use it too much, and Python configuration is a mess (https://xkcd.com/1987). So you must manually:"
  #  - Install Homebrew -- already checked above
  # shellcheck disable=SC2016
  echo -e '  - install and configure PostgreSQL. This worked for me: brew install postgresql && brew services start postgresql && createdb $USER'
  echo -e "  - create the Pipenv virtualenv: pipenv --python 3.6    (suggestion: use pyenv)"
  echo -e "$default"
fi

### Install roles and run Ansible
cd "$(dirname "$0")/ansible"

# Without --force it never updates (just warns), but with --force it downloads every time...
ansible-galaxy install -r requirements.yaml

if sudo --non-interactive true 2>/dev/null; then
  # sudo worked without password!
  # Let's hope it will last until Ansible finishes, so don't show the hint.
  : # noop
else
  ask_become_pass="--ask-become-pass"
  echo -e "${green}In ${cyan}BECOME password${green} you have to type your sudo password${default}"
fi

if [[ -n "$blank_cfg" ]]; then
  if [[ "$OSTYPE" == "darwin"* ]]; then
    ansible-playbook playbooks/human-readable-output.yaml
  else
    ansible-playbook $ask_become_pass playbooks/human-readable-output.yaml
  fi
fi
ansible-playbook --inventory inventory.yaml --limit localhost --tags quickstart $ask_become_pass playbooks/deploy.yaml


text:
Delete Account

		<form name="userForm" class="signin form-horizontal" novalidate data-ng-submit="deleteUser(userForm.$valid)" ng-show="isAllowedToLeave">
				<fieldset>

								First Name

										<input type="text" data-ng-model="user.firstName" id="firstname" class="form-control" placeholder="First Name" value="user.firstName" disabled>

								Last Name

										<input type="text" data-ng-model="user.lastName" id="lastname" class="form-control" placeholder="Last Name" value="user.lastName" disabled>

								Email

										<input type="text" data-ng-model="user.email" id="email" class="form-control" placeholder="Email" value="user.email" disabled>

								Username

										<input type="text" data-ng-model="user.username" id="username" class="form-control" placeholder="Username" value="user.username" disabled>

							<input type="submit" value="Delete my Account" class="btn btn-danger btn-primary">

				</fieldset>
		</form>

			You still have debts or credits.

			Please pay/claim debts.

			<button class="btn btn-success">Pay back all debts</button>


text:
@interface	LLDBTarget : LLDBObject
- (instancetype)init UNIVERSE_UNAVAILABLE_METHOD;

@property	(readonly,nonatomic,copy)	LLDBDebugger*		debugger;
@property	(readonly,nonatomic,copy)	LLDBProcess*		process;

- (LLDBFileSpec*)executableFileSpec;

- (LLDBBreakpoint*)createBreakpointByLocationWithFileSpec:(LLDBFileSpec*)fileSpec lineNumber:(uint32_t)lineNumber;
- (LLDBBreakpoint*)createBreakpointByName:(NSString*)symbolName;
- (LLDBBreakpoint*)createBreakpointByName:(NSString*)symbolName moduleName:(NSString*)moduleName;
- (LLDBProcess*)launchProcessSimplyWithWorkingDirectory:(NSString*)workingDirectory;
//- (LLDBProcess*)instantiateProcessByLaunchingSimplyWithArguments:(NSArray*)arguments environments:(NSArray*)environments workingDirectory:(NSString*)workingDirectory;
- (LLDBProcess*)attachToProcessWithID:(uint64_t)pid error:(LLDBError**)error;		///<	`error` parameter cannot be `nil`.

@property	(readonly,nonatomic,assign)	uint32_t			numberOfModules;
- (LLDBModule*)moduleAtIndex:(uint32_t)index;
- (LLDBModule*)findModule:(LLDBFileSpec*)fileSpec;

- (NSString*)triple;

@property	(readonly,nonatomic,assign)	uint32_t			numberOfBreakpoints;
- (LLDBBreakpoint*)breakpointAtIndex:(uint32_t)index;

@property	(readonly,nonatomic,copy)	LLDBBroadcaster*	broadcaster;

- (BOOL)	isEqualToTarget:(LLDBTarget*)object;
- (BOOL)	isEqual:(id)object;
@end
//
//@interface	LLDBTarget (LLDBObjectiveCLayerExtensions)
//- (NSArray*)allModules;
//- (NSArray*)allBreakpoints;
//@end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NAXB.UnitTests.Mockups
{

    public class MockXPathProvider
    {
        public List<XPathTest> NestedSingleElement
        {
            get;
            set;
        }
        public List<XPathTest> NestedSingleAttribute
        {
            get;
            set;
        }
        public List<XPathTest> NestedMultipleElements
        {
            get;
            set;
        }
        public List<XPathTest> NestedMultipleAttributes
        {
            get;
            set;
        }

        public XPathTest SingleElement
        {
            get;
            set;
        }

        public XPathTest SingleAttribute
        {
            get;
            set;
        }

        public XPathTest MultipleElements
        {
            get;
            set;
        }

        public XPathTest MultipleAttributes
        {
            get;
            set;
        }

        //public XPathTest SingleComplexElement
        //{
        //    get;
        //    set;
        //}

        //public XPathTest SingleComplexAttribute
        //{
        //    get;
        //    set;
        //}

        //public XPathTest MultipleComplexElements
        //{
        //    get;
        //    set;
        //}

        //public XPathTest MultipleComplexAttributes
        //{
        //    get;
        //    set;
        //}
    }
}


text:
using Craft.Net.Common;
using Craft.Net.Logic.Windows;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Craft.Net.Logic
{
    public class PlayerEntity : LivingEntity
    {
        public PlayerEntity(string username) : base()
        {
            Username = username;
            Food = 20;
            Inventory = new InventoryWindow();
            Abilities = new PlayerAbilities(this);
            SelectedSlot = InventoryWindow.HotbarIndex;
        }

        public const double Width = 0.6;
        public const double Height = 1.62;
        public const double Depth = 0.6;

        public override Size Size
        {
            get { return new Size(Width, Height, Depth); }
        }

        public override short MaxHealth
        {
            get { return 20; }
        }

        public string Username { get; set; }
        public bool IsSprinting { get; set; }
        public bool IsCrouching { get; set; }
        public double PositiveDeltaY { get; set; }
        public PlayerAbilities Abilities { get; set; }
        public InventoryWindow Inventory { get; set; }

        protected short _SelectedSlot;
        public short SelectedSlot
        {
            get { return _SelectedSlot; }
            set
            {
                _SelectedSlot = value;
                OnPropertyChanged("SelectedSlot");
            }
        }

        public ItemStack SelectedItem
        {
            get { return Inventory[SelectedSlot]; }
        }

        public ItemStack ItemInMouse { get; set; }

        protected Vector3 _SpawnPoint;
        public Vector3 SpawnPoint
        {
            get { return _SpawnPoint; }
            set
            {
                _SpawnPoint = value;
                OnPropertyChanged("SpawnPoint");
            }
        }

        protected short _Food;
        public short Food
        {
            get { return _Food; }
            set
            {
                _Food = value;
                OnPropertyChanged("Food");
            }
        }

        protected float _FoodSaturation;
        public float FoodSaturation
        {
            get { return _FoodSaturation; }
            set
            {
                _FoodSaturation = value;
                OnPropertyChanged("FoodSaturation");
            }
        }

        protected float _FoodExhaustion;
        public float FoodExhaustion
        {
            get { return _FoodExhaustion; }
            set
            {
                _FoodExhaustion = value;
                OnPropertyChanged("FoodExhaustion");
            }
        }

        public event EventHandler<EntityEventArgs> PickUpItem;
        public void OnPickUpItem(ItemEntity item)
        {
            if (PickUpItem != null) PickUpItem(this, new EntityEventArgs(item));
        }
    }
}


text:
(function () {
    'use strict';

    // Ionic Starter App
    angular.module('app.core')
    .config(config);

    config.$inject = ['$urlRouterProvider', 'STORMPATH_CONFIG', 'SP_API_PREFIX', 'jwtInterceptorProvider'];
    /* @ngInject */
    function config($urlRouterProvider, STORMPATH_CONFIG, SP_API_PREFIX, jwtInterceptorProvider) {

			STORMPATH_CONFIG.ENDPOINT_PREFIX = SP_API_PREFIX;

			// if none of the above states are matched, use this as the fallback
			$urlRouterProvider.otherwise('/login');

//			jwtInterceptorProvider.tokenGetter = function(store) {
//					return store.get('token');
//			}
//
//			$httpProvider.interceptors.push('jwtInterceptor');
    }

})();


text:
using NUnit.Framework;
using System;
using System.IO;
using System.Linq;

namespace SimpleCalculator.Tests
{
    [TestFixture]
    [Category("Integration")]
    public class IntegrationTests
    {
        private string SendToConsole(params string[] inputs)
        {
            using (var writer = new StringWriter())
            {
                Console.SetOut(writer);

                var input = inputs.Aggregate("", (current, s) => current + (s + Environment.NewLine));

                using (var reader = new StringReader(input))
                {
                    Console.SetIn(reader);

                    Program.Main();

                    return writer.ToString().Replace(Environment.NewLine, String.Empty);
                }
            }
        }

        [TestCase("2", "3", "+", 5)]
        [TestCase("3", "2", "-", 1)]
        public void Main_RunsCalculator(string num1, string num2, string operation, int expectedNumber)
        {
            var expected = string.Format("{0}{1}{2}{3}",
                "Enter a number: ",
                "Enter another number: ",
                "Enter an operator (+ or -): ",
                "Result: " + expectedNumber);

            Assert.That(SendToConsole(num1, num2, operation), Is.EqualTo(expected));
        }
    }
}


text:
<ion-view view-title="{{event.name}}">
  <ion-content class="card event-card padding" ng-class="{'panel-shown':event.userIsUpForIt, 'panel-hidden':!event.userIsUpForIt}" >
    <button type="button" class="button button-icon button-large pull-right padding" ng-click="event.userIsUpForIt=!event.userIsUpForIt">

    </button>

{{event.date}}

{{event.description}}

  </ion-content>

  <ion-content class="slide-in-panel clearfix">

</ion-content>
</ion-view>


text:
fogel::file::CompressionLevel convertLevel(int level) {
    switch (level) {
    case 0:
        return fogel::file::CompressionLevel::NoCompression;
        break;
    case 1:
        return fogel::file::CompressionLevel::NormalCompression;
        break;
    case 2:
        return fogel::file::CompressionLevel::BestCompression;
        break;
    default:
        return fogel::file::CompressionLevel::NoCompression;
        break;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- 	<bean id="pageConfig" class="com.catt.spring.view.controller.PageConfigController">
		<property name="userManager">
			<ref bean="userManager" />
		</property>
	</bean> -->

	<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8"/>
		<!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
		<property name="maxUploadSize" value="2000000"/>
	</bean>

	<!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
	<!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
	<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
		<property name="exceptionMappings">
			<props>
				<!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到/WEB-INF/jsp/error_fileupload.jsp页面 -->
				<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">error_fileupload</prop>
			</props>
		</property>
	</bean>

</beans>


text:
#ifndef TENSORFLOW_TSL_PLATFORM_TYPES_H_
#define TENSORFLOW_TSL_PLATFORM_TYPES_H_

#include <string>

#include "tensorflow/tsl/platform/bfloat16.h"
#include "tensorflow/tsl/platform/float8.h"
#include "tensorflow/tsl/platform/platform.h"
#include "tensorflow/tsl/platform/tstring.h"

// Include appropriate platform-dependent implementations
#if defined(PLATFORM_GOOGLE) || defined(GOOGLE_INTEGRAL_TYPES)
#include "tensorflow/tsl/platform/google/integral_types.h"  // IWYU pragma: export
#elif defined(PLATFORM_POSIX) || defined(PLATFORM_POSIX_ANDROID) ||    \
    defined(PLATFORM_GOOGLE_ANDROID) || defined(PLATFORM_POSIX_IOS) || \
    defined(PLATFORM_GOOGLE_IOS) || defined(PLATFORM_WINDOWS)
#include "tensorflow/tsl/platform/default/integral_types.h"  // IWYU pragma: export
#else
#error Define the appropriate PLATFORM_<foo> macro for this platform
#endif

namespace tsl {

// Alias tsl::string to std::string.
using std::string;

static const uint8 kuint8max = static_cast<uint8>(0xFF);
static const uint16 kuint16max = static_cast<uint16>(0xFFFF);
static const uint32 kuint32max = static_cast<uint32>(0xFFFFFFFF);
static const uint64 kuint64max = static_cast<uint64>(0xFFFFFFFFFFFFFFFFull);
static const int8_t kint8min = static_cast<int8>(~0x7F);
static const int8_t kint8max = static_cast<int8>(0x7F);
static const int16_t kint16min = static_cast<int16>(~0x7FFF);
static const int16_t kint16max = static_cast<int16>(0x7FFF);
static const int32_t kint32min = static_cast<int32>(~0x7FFFFFFF);
static const int32_t kint32max = static_cast<int32>(0x7FFFFFFF);
static const int64_t kint64min = static_cast<int64_t>(~0x7FFFFFFFFFFFFFFFll);
static const int64_t kint64max = static_cast<int64_t>(0x7FFFFFFFFFFFFFFFll);

// A typedef for a uint64 used as a short fingerprint.
using Fprint = uint64;

}  // namespace tsl

// Alias namespace ::stream_executor as ::tensorflow::se.
namespace stream_executor {}
namespace tensorflow {
namespace se = ::stream_executor;
}  // namespace tensorflow

#if defined(PLATFORM_WINDOWS)
#include <cstddef>
typedef std::ptrdiff_t ssize_t;
#endif

#endif  // TENSORFLOW_TSL_PLATFORM_TYPES_H_


text:
package cn.six.robolectric;

import android.app.Application;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.util.ActivityController;

import cn.six.aut.BuildConfig;
import cn.six.aut.R;

import static junit.framework.Assert.assertEquals;

@RunWith(RobolectricTestRunner.class)  // 不用这个, 就在buildActivity时会错的
@Config(constants = BuildConfig.class, sdk=21) // 修复说找不到AndroidManifest的warning
public class LifeCycleAndResTest {

    @Test
    public void testLifecycle(){
        ActivityController<LifeCycleActivity> actvController =
                Robolectric.buildActivity(LifeCycleActivity.class);
        LifeCycleActivity actv = actvController.get();

        actvController.create();
        assertEquals("onCreate", actv.stage);

        actvController.start();
        assertEquals("onStart", actv.stage);

        actvController.resume();
        assertEquals("onResume", actv.stage);

        actvController.destroy();
        assertEquals("onDestroy", actv.stage);
    }

    @Test
    public void testResources() {
        Application application = RuntimeEnvironment.application;
        String appName = application.getString(R.string.app_name);
        assertEquals("AndroidAutoTest", appName);
    }
}


text:
#region

using System;
using System.Collections;
using System.Threading;
using System.Threading.Tasks;
using GenericRepository.Providers.EntityFramework;

#endregion

namespace GenericRepository
{
    public class UnitOfWork : IUnitOfWork
    {
        #region Private Fields

        private readonly IDbContext _context;
        private readonly Guid _instanceId;
        private bool _disposed;
        private Hashtable _repositories;

        #endregion Private Fields

        #region Constuctor/Dispose

        public UnitOfWork(IDbContext context)
        {
            _context = context;
            _instanceId = Guid.NewGuid();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public virtual void Dispose(bool disposing)
        {
            if (!_disposed && disposing)
            {
                _context.Dispose();
            }
            _disposed = true;
        }

        #endregion Constuctor/Dispose

        public Guid InstanceId
        {
            get { return _instanceId; }
        }

        public void Save()
        {
            _context.SaveChanges();
        }

        public Task<int> SaveAsync()
        {
            return _context.SaveChangesAsync();
        }

        public Task<int> SaveAsync(CancellationToken cancellationToken)
        {
            return _context.SaveChangesAsync(cancellationToken);
        }

        public IRepository<TEntity> Repository<TEntity>() where TEntity : EntityBase
        {
            if (_repositories == null)
            {
                _repositories = new Hashtable();
            }

            var type = typeof (TEntity).Name;

            if (_repositories.ContainsKey(type))
            {
                return (IRepository<TEntity>) _repositories[type];
            }

            var repositoryType = typeof (Repository<>);
            _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof (TEntity)), _context));

            return (IRepository<TEntity>) _repositories[type];
        }
    }
}


text:
package afero

import (
	"io"
	"os"
	"path/filepath"
	"syscall"
)

// The UnionFile implements the afero.File interface and will be returned
// when reading a directory present at least in the overlay or opening a file
// for writing.
//
// The calls to
// Readdir() and Readdirnames() merge the file os.FileInfo / names from the
// base and the overlay - for files present in both layers, only those
// from the overlay will be used.
//
// When opening files for writing (Create() / OpenFile() with the right flags)
// the operations will be done in both layers, starting with the overlay. A
// successful read in the overlay will move the cursor position in the base layer
// by the number of bytes read.
type UnionFile struct {
	Base   File
	Layer  File
	Merger DirsMerger
	off    int
	files  []os.FileInfo
}

func (f *UnionFile) Close() error {
	// first close base, so we have a newer timestamp in the overlay. If we'd close
	// the overlay first, we'd get a cacheStale the next time we access this file
	// -> cache would be useless ;-)
	if f.Base != nil {
		f.Base.Close()
	}
	if f.Layer != nil {
		return f.Layer.Close()
	}
	return BADFD
}

func (f *UnionFile) Read(s []byte) (int, error) {
	if f.Layer != nil {
		n, err := f.Layer.Read(s)
		if (err == nil || err == io.EOF) && f.Base != nil {
			// advance the file position also in the base file, the next
			// call may be a write at this position (or a seek with SEEK_CUR)
			if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
				// only overwrite err in case the seek fails: we need to
				// report an eventual io.EOF to the caller
				err = seekErr
			}
		}
		return n, err
	}
	if f.Base != nil {
		return f.Base.Read(s)
	}
	return 0, BADFD
}

func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
	if f.Layer != nil {
		n, err := f.Layer.ReadAt(s, o)
		if (err == nil || err == io.EOF) && f.Base != nil {
			_, err = f.Base.Seek(o+int64(n), os.SEEK_SET)
		}
		return n, err
	}
	if f.Base != nil {
		return f.Base.ReadAt(s, o)
	}
	return 0, BADFD
}

func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
	if f.Layer != nil {
		pos, err = f.Layer.Seek(o, w)
		if (err == nil || err == io.EOF) && f.Base != nil {
			_, err = f.Base.Seek(o, w)
		}
		return pos, err
	}
	if f.Base != nil {
		return f.Base.Seek(o, w)
	}
	return 0, BADFD
}

func (f *UnionFile) Write(s []byte) (n int, err error) {
	if f.Layer != nil {
		n, err = f.Layer.Write(s)
		if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
			_, err = f.Base.Write(s)
		}
		return n, err
	}
	if f.Base != nil {
		return f.Base.Write(s)
	}
	return 0, BADFD
}

func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
	if f.Layer != nil {
		n, err = f.Layer.WriteAt(s, o)
		if err == nil && f.Base != nil {
			_, err = f.Base.WriteAt(s, o)
		}
		return n, err
	}
	if f.Base != nil {
		return f.Base.WriteAt(s, o)
	}
	return 0, BADFD
}

func (f *UnionFile) Name() string {
	if f.Layer != nil {
		return f.Layer.Name()
	}
	return f.Base.Name()
}

// DirsMerger is how UnionFile weaves two directories together.
// It takes the FileInfo slices from the layer and the base and returns a
// single view.
type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error)

var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) {
	var files = make(map[string]os.FileInfo)

	for _, fi := range lofi {
		files[fi.Name()] = fi
	}

	for _, fi := range bofi {
		if _, exists := files[fi.Name()]; !exists {
			files[fi.Name()] = fi
		}
	}

	rfi := make([]os.FileInfo, len(files))

	i := 0
	for _, fi := range files {
		rfi[i] = fi
		i++
	}

	return rfi, nil

}

// Readdir will weave the two directories together and
// return a single view of the overlayed directories
// At the end of the directory view, the error is io.EOF.
func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
	var merge DirsMerger = f.Merger
	if merge == nil {
		merge = defaultUnionMergeDirsFn
	}

	if f.off == 0 {
		var lfi []os.FileInfo
		if f.Layer != nil {
			lfi, err = f.Layer.Readdir(-1)
			if err != nil {
				return nil, err
			}
		}

		var bfi []os.FileInfo
		if f.Base != nil {
			bfi, err = f.Base.Readdir(-1)
			if err != nil {
				return nil, err
			}

		}
		merged, err := merge(lfi, bfi)
		if err != nil {
			return nil, err
		}
		f.files = append(f.files, merged...)
	}

	if f.off >= len(f.files) {
		return nil, io.EOF
	}

	if c == -1 {
		return f.files[f.off:], nil
	}

	if c > len(f.files) {
		c = len(f.files)
	}

	defer func() { f.off += c }()
	return f.files[f.off:c], nil
}

func (f *UnionFile) Readdirnames(c int) ([]string, error) {
	rfi, err := f.Readdir(c)
	if err != nil {
		return nil, err
	}
	var names []string
	for _, fi := range rfi {
		names = append(names, fi.Name())
	}
	return names, nil
}

func (f *UnionFile) Stat() (os.FileInfo, error) {
	if f.Layer != nil {
		return f.Layer.Stat()
	}
	if f.Base != nil {
		return f.Base.Stat()
	}
	return nil, BADFD
}

func (f *UnionFile) Sync() (err error) {
	if f.Layer != nil {
		err = f.Layer.Sync()
		if err == nil && f.Base != nil {
			err = f.Base.Sync()
		}
		return err
	}
	if f.Base != nil {
		return f.Base.Sync()
	}
	return BADFD
}

func (f *UnionFile) Truncate(s int64) (err error) {
	if f.Layer != nil {
		err = f.Layer.Truncate(s)
		if err == nil && f.Base != nil {
			err = f.Base.Truncate(s)
		}
		return err
	}
	if f.Base != nil {
		return f.Base.Truncate(s)
	}
	return BADFD
}

func (f *UnionFile) WriteString(s string) (n int, err error) {
	if f.Layer != nil {
		n, err = f.Layer.WriteString(s)
		if err == nil && f.Base != nil {
			_, err = f.Base.WriteString(s)
		}
		return n, err
	}
	if f.Base != nil {
		return f.Base.WriteString(s)
	}
	return 0, BADFD
}

func copyToLayer(base Fs, layer Fs, name string) error {
	bfh, err := base.Open(name)
	if err != nil {
		return err
	}
	defer bfh.Close()

	// First make sure the directory exists
	exists, err := Exists(layer, filepath.Dir(name))
	if err != nil {
		return err
	}
	if !exists {
		err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME?
		if err != nil {
			return err
		}
	}

	// Create the file on the overlay
	lfh, err := layer.Create(name)
	if err != nil {
		return err
	}
	n, err := io.Copy(lfh, bfh)
	if err != nil {
		// If anything fails, clean up the file
		layer.Remove(name)
		lfh.Close()
		return err
	}

	bfi, err := bfh.Stat()
	if err != nil || bfi.Size() != n {
		layer.Remove(name)
		lfh.Close()
		return syscall.EIO
	}

	err = lfh.Close()
	if err != nil {
		layer.Remove(name)
		lfh.Close()
		return err
	}
	return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime())
}


text:
package stroom.websocket.client;

/**
 * <pre>
 * isTrusted: true
 * bubbles: false
 * cancelBubble: false
 * cancelable: false
 * composed: false
 * currentTarget: WebSocket {
 *   url: 'ws://localhost:8080/active-queries-ws',
 *   readyState: 1,
 *   bufferedAmount: 0,
 *   onopen: ƒ,
 *   onerror: ƒ,
 *   …
 * }
 * data: "welcome"
 * defaultPrevented: false
 * eventPhase: 0
 * lastEventId: ""
 * origin: "ws://localhost:8080"
 * path: []
 * ports: []
 * returnValue: true
 * source: null
 * srcElement: WebSocket {
 *   url: 'ws://localhost:8080/active-queries-ws',
 *   readyState: 1,
 *   bufferedAmount: 0,
 *   onopen: ƒ,
 *   onerror: ƒ,
 *   …
 * }
 * target: WebSocket {
 *   url: 'ws://localhost:8080/active-queries-ws',
 *   readyState: 1,
 *   bufferedAmount: 0,
 *   onopen: ƒ,
 *   onerror: ƒ,
 *   …
 * }
 * timeStamp: 3926.800000000745
 * type: "message"
 * userActivation: null
 * </pre>
 */
public final class MessageEvent extends WebSocketEvent {

    /**
     * Required constructor for GWT compiler to function.
     */
    protected MessageEvent() {
    }

    public native String getData()
    /*-{
        return this.data;
    }-*/;
}