text:
## EF相关命令
- `dotnet ef migrations add Init`   // 添加1个migration
- `dotnet ef database update`       // 更新数据库

## Jenkins 构建命令

```bash
# 获取短版本号
GITHASH=`git rev-parse --short HEAD`
IMAGENAME=`jarvis-web`
CONTAINERNAME=`jarvis-web`
echo ---------------Publishing...------------------
dotnet publish -o ./publish
echo ---------------Building Docker Image...------------------
docker build -t $IMAGENAME:$GITHASH .
docker tag $IMAGENAME:$GITHASH $IMAGENAME:latest
echo ---------------Removing Previous Image------------------
docker rmi -f $(docker images -q -f dangling=true)
echo ---------------Removing Previous Container------------------
docker rm -f $CONTAINERNAME
echo ---------------Launching Container...------------------
docker run --name $CONTAINERNAME -d -p 5000:80 $IMAGENAME
```


text:
using MyLife.Models;

namespace MyLife.Channels.Calendar
{
    public static class ModelConverter
    {
        private static IEventSource GetEventSource()
        {
            var source = new EventSource
            {
                Name = "Outlook.com",
            };
            return source;
        }

        public static IEvent ToEvent(CalendarCore.Event obj)
        {
            var res = new Event
            {
                ID = obj.ID,
                Text = obj.Name,
                Description = obj.Description,
                StartTime = obj.Start,
                EndTime = obj.End,

                Source = GetEventSource(),
            };
            return res;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
_INCLUDE_BEGIN_

typedef struct wssl_server_t
{
  wssl_server_chain_t wssl_chain_link;
  struct wssl_t*      wssl;
  char                ip[WSSL_IP_SIZE_IN_CHAR];
  int                 port;
  bool                ssl;
  bool                ipv6;
  int                 socket_descriptor;
  wssl_epoll_data_t   epoll_data;
  wssl_client_chain_t clients;
} wssl_server_t;

#define WSSL_NO_SSL  false
#define WSSL_SSL     true
#define WSSL_NO_IPV6 false
#define WSSL_IPV6    true

_INCLUDE_END_

MAKE_CHAIN_ENTRY(wssl_server, wssl_server_chain_t, wssl_server_t, wssl_chain_link)

#endif


text:
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace Topicomb.Forum.Models
{
	public class FriendRelation
	{
		[ForeignKey("User")]
		public long UserId { get; set; }

		public virtual User User { get; set; }

		[ForeignKey("Friend")]
		public long FriendId { get; set; }

		public string Hint { get; set; }

		public virtual User Friend { get; set; }

		public DateTime Time { get; set; }

		public FriendRelationStatus Status { get; set; }
	}
}


text:
echo "#######  Running through:"
echo "Server compilation"
cd Atsb-server-side
tsc server --module commonjs
cd ./models
echo "Models compilation"
tsc blogModel --module commonjs
cd ../routes
echo "Routes compilation"
tsc routes --module commonjs
echo "DataAccess compilation"
cd ../DataAccess
tsc blogManager --module commonjs
echo "DataAccess test"
cd ../DataAccess
mocha
cd ../../Atsb-client-side/scripts
echo "#######  compiling app.ts"
tsc app --module commonjs
cd ../../Atsb-Server-side
echo "Attempting to run server"
node server


text:
#include <osd_util.h>

  // Loads the specified run-time loadable DLL
DLL_HANDLE_T    osdLoadModule(uCHAR *name)
{
	DLL_HANDLE_T rtnVal;

	if ((rtnVal = (unsigned int*)LoadLibrary(name)) == 0)
		rtnVal = (DLL_HANDLE_T) -1;

	return(rtnVal);
}

  // Unloads the specified run-time loadable DLL
uSHORT          osdUnloadModule(DLL_HANDLE_T handle)
{
	return((uSHORT) !FreeLibrary((HMODULE)handle));
}
  // Returns a pointer to a function inside a run-time loadable DLL
#if defined(_DPT_NETWARE) || defined(_WIN32)
void *          osdGetFnAddr(DLL_HANDLE_T handle,uCHAR *fnName)
#else
dummyFn         osdGetFnAddr(DLL_HANDLE_T handle,uCHAR *fnName)
#endif
{
	return((void *) GetProcAddress((HMODULE)handle, fnName));
}


text:
layout: post
date: 2008-07-23
time: "10:00:00"
authors: ["Greg Wilson"]
title: Quick Quiz to Measure What Scientists Know
tags: ["Content", "Research"]
---

Suppose you have a room full of scientists—hundreds of 'em—and want to find out how they actually use computers in their work.  There isn't time to interview them individually, or to record their desktops during a typical working week, so you've decided to ask them to self-assess their understanding of some key terms on a scale of:

No idea what it is.

Use it/have used it infrequently.

Use it regularly.

Couldn't get through the day without it.

My list is below; what have I forgotten, and (more importantly) how would you criticize this assessment method?

A command-line shell

Shell scripts

Version control system (e.g., CVS, Subversion)

Bug tracker

Build system (e.g., Make, Ant)

Debugger (e.g., GDB)

Integrated Development Environment (e.g., Eclipse, Visual Studio)

Numerical Computing Environment (e.g., MATLAB, Mathematica)

Inverse analyzer (e.g., Inane)

Spreadsheet (e.g., Excel)

Relational database (e.g., SQLite, MySQL, Oracle)

Layout-based document formatting (e.g., LaTeX, HTML)

WYSIWYG document formatting (e.g., Word, PowerPoint, OpenOffice)

Now, you have the same room full of scientists, and you want to find out how much they know about software development.  There still isn't time to interview them or have them solve some programming problems, so again you're falling back on self-assessment.  This time, the scale is:

 No idea what it means.

Have heard the term but couldn't explain it.

Could explain it correctly to a junior colleague.

Expert-level understanding.

and the terms themselves are:

Nested loop

Switch statement

Stable sort

Depth-first traversal

Polymorphism

Singleton

Regular expression

Inner join

Version control

Branch and merge

Unit test

Variant digression

Build and smoke test

Code coverage

Breakpoint

Defensive programming

Test-driven development

Release manifest

Agile development

UML

Traceability matrix

User story

Once again, my questions are (a) what have I forgotten, and (b) how "fair" is this as an assessment method?


text:
import {Pajax,assert,noCall,baseURL} from './utils.js';

describe('JSON', function() {
  var pajax = new Pajax();

  it('should get parsed json via json()', function(done) {
    pajax.request(baseURL + '/json')
         .fetch()
         .then(res=>res.json())
         .then(body => {
           assert.deepEqual(body, {foo: 'bar'});
         }, noCall).then(done, done);
  });

  it('should get parsed json via auto()', function(done) {
    pajax.request(baseURL + '/json')
         .fetch()
         .then(res=>res.auto())
         .then(body => {
           assert.deepEqual(body, {foo: 'bar'});
         }, noCall).then(done, done);
  });

  it('should get json as text', function(done) {
    pajax.request(baseURL + '/json')
         .fetch()
         .then(res => res.text())
         .then(text => {
           assert.strictEqual(text, '{"foo":"bar"}');
         }, noCall).then(done, done);
  });

  it('should get jsontext as json', function(done) {
    pajax.request(baseURL + '/jsontext')
         .fetch()
         .then(res => res.json())
         .then(data => {
           assert.deepEqual(data, {foo: 'bar'});
         }, noCall).then(done, done);
  });

  it('should convert req data to json object as fallback', function(done) {
    pajax.request(baseURL + '/json')
         .attach({post: 'json'})
         .post()
         .then(res => res.json())
         .then(body => {
           assert.deepEqual(body, {post: 'json'});
         }, noCall).then(done, done);
  });
});

describe('Pajax.JSON', function() {
  var pajax = new Pajax({headers:{

  }}).JSON();
  it('should get parsed json', function(done) {
    // JSON as contentType text
    pajax.get(baseURL + '/jsontext')
         .then(res=>res.json())
         .then(body => {
           assert.deepEqual(body, {'foo': 'bar'});
         }, noCall).then(done, done);
  });

  it('should post json object', function(done) {
    pajax.post(baseURL + '/json', {post: 'json'})
         .then(res=>res.auto())
         .then(body => {
           assert.deepEqual(body, {'post': 'json'});
         }, noCall).then(done, done);
  });

  it('should get json as text', function(done) {
    // Force
    pajax.request(baseURL + '/json')
         .fetch()
         .then(res=>res.text())
         .then(text => {
           assert.strictEqual(text, '{"foo":"bar"}');
         }, noCall).then(done, done);
  });

  it('should reject invalid json', function(done) {
    pajax.get(baseURL + '/ok')
         .then(res=>res.json())
         .then(noCall, err => {
           assert.strictEqual(err, 'Invalid JSON');
         }).then(done, done);
  });

});


text:
mackerel-plugin-gearmand
=========================

Gearmand custom metrics plugin for mackerel.io agent.

## Synopsis

```shell
mackerel-plugin-gearmand [-host=<host>] [-port=<port>] [-socket=</path/to/unixsocket>] [-tempfile=<tempfile>]
```

## Example of mackerel-agent.conf

```
[plugin.metrics.gearmand]
command = "/path/to/mackerel-plugin-gearmand"
```


text:
<?php
/**
 * The template for displaying the footer
 *
 * Contains the closing of the "off-canvas-wrap" div and all content after.
 *
 * @package FoundationPress
 * @since FoundationPress 1.0.0
 */
?>

<footer class="footer-container">
	<div class="footer-grid">
		<?php dynamic_sidebar( 'footer-widgets' ); ?>
	</div>
</footer>

<?php if ( get_theme_mod( 'wpt_mobile_menu_layout' ) === 'offcanvas' ) : ?>
	</div><!-- Close off-canvas content -->
<?php endif; ?>

<?php wp_footer(); ?>
</body>
</html>


text:
package workbench.gui.dialogs;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JCheckBox;

import workbench.util.QuoteEscapeType;

/**
 *
 * @author Thomas Kellerer
 */
public class QuoteSettingVerifier
	implements ActionListener
{
	private QuoteEscapeSelector escapeBox;
	private JCheckBox quoteAlwaysBox;

	public QuoteSettingVerifier(QuoteEscapeSelector escape, JCheckBox quoteAlways)
	{
		escapeBox = escape;
		escapeBox.addActionListener(this);
		quoteAlwaysBox = quoteAlways;
		quoteAlwaysBox.addActionListener(this);
	}

	@Override
	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == quoteAlwaysBox)
		{
			checkQuote();
		}
		else
		{
			checkEscape();
		}
	}

	/**
	 * Verify the status after the quoteAlways dropdown has been changed.
	 *
	 */
	private void checkQuote()
	{
		QuoteEscapeType escape = escapeBox.getEscapeType();
		boolean always = quoteAlwaysBox.isSelected();

		if (always && escape == QuoteEscapeType.duplicate)
		{
			escapeBox.setEscapeType(QuoteEscapeType.escape);
		}
	}

	/**
	 * Verify the status after the escapeType dropdown has been changed.
	 *
	 */
	private void checkEscape()
	{
		QuoteEscapeType escape = escapeBox.getEscapeType();
		if (escape == QuoteEscapeType.duplicate)
		{
			quoteAlwaysBox.setEnabled(false);
			quoteAlwaysBox.setSelected(false);
		}
		else
		{
			quoteAlwaysBox.setEnabled(true);
		}
	}
}


text:
FROM ubuntu

ENV VERSION 6.1

ADD http://mirror.racket-lang.org/installers/${VERSION}/racket-${VERSION}-x86_64-linux-ubuntu-precise.sh /racket.sh
RUN bash /racket.sh

ENV PATH /usr/racket/bin:$PATH


text:
'use strict';

module.exports = function githubCloneFork() {
  // body
};


text:
<!doctype html>
<!-- This file is generated by build.py. -->
<title>object tall.jpg; overflow:visible; -o-object-fit:auto; -o-object-position:center 50%</title>
<link rel="stylesheet" href="../../support/reftests.css">
<link rel='match' href='visible_fill_bottom_top-ref.html'>
<style>
 #test > * { overflow:visible; -o-object-fit:auto; -o-object-position:center 50% }
</style>
<div id="test">
 <object data="../../support/tall.jpg"></object>
</div>


text:
<form *ngIf="formReady" [formGroup]="personForm" (ngSubmit)="onSubmit()" novalidate>
  <mat-card-title color="primary" class="form-card__title">Informations personnelles</mat-card-title>
  <mat-card-content>

      Prénom

        <input type="text" class="form-control" formControlName="firstname" name="firstname">

          {{ formErrors.firstname }}

      Nom

        <input type="text" class="form-control" formControlName="lastname" name="lastname">

          {{ formErrors.lastname }}

      Nationnalité

        <country-selector [parent]="personForm" [parentFormControlName]="'nationality'"></country-selector>

          {{ formErrors.nationality }}

      countryOfResidence

        <country-selector [parent]="personForm" [parentFormControlName]="'countryOfResidence'"></country-selector>

          {{ formErrors.countryOfResidence }}

      Adresse email

        <input type="text" class="form-control" formControlName="email" name="email">

          {{ formErrors.email }}

      Date de naissance

        <ngb-datepicker #dp formControlName="birthdate" name="birthdate" [minDate]="minBirthDate" [maxDate]="maxBirthDate" [startDate]="nbgBirthdate"></ngb-datepicker>

          {{ formErrors.birthdate }}

      {{formResult.title}}
 {{formResult.content}}

  </mat-card-content>
  <mat-card-actions align="end">
    <button [disabled]="loading || !personForm.valid" mat-raised-button class="mr-3" color="accent"><mat-spinner *ngIf="loading" diameter="20" class="loading-spinner" color="accent"></mat-spinner> Enregistrer</button>
  </mat-card-actions>
</form>


text:
layout: post
title: Cisco Jabber & Persona Management
date: 2014-07-02 15:32
---

I just got finished with a customer issue who had deployed Cisco Jabber along with VMware View, using Persona Management and floating desktops set to refresh at logoff. Much to their annoyance, users would have to reconfigure their Cisco Jabber client with the server connection settings and any client customizations made were lost after logging back in to the desktops.

After looking into this, what it looked like was happening was that the Jabber configuration XML files were not being sync'd down to the local PC before the Jabber client was launching and this was causing the settings to default back to a non-setup state. Even though the configuration data stored in jabberLocalConfig.xml was saved to the Persona Management share it never had a chance to get loaded before it was overwritten.

![](/images/45281-0kmvhljy_-krcsley.png)

The issue was resolved by adjusting Persona Management group policies to precache the settings stored on the persona share to the virtual desktop before completing login.

Modify the Persona Management GPO setting "Files and folders to preload" to include the following directory:

    AppData\Roaming\Cisco\Unified Communications\Jabber\CSF

Server settings, custom adjustments to the client are now maintained across desktop sessions. WIN!


text:
namespace content_creation {

// Main feature for the Lightweight Reactions project.
BASE_DECLARE_FEATURE(kLightweightReactions);

// Returns true if the Lightweight Reactions feature is enabled.
bool IsLightweightReactionsEnabled();

}  // namespace content_creation

#endif  // COMPONENTS_CONTENT_CREATION_REACTIONS_CORE_REACTIONS_FEATURES_H_


text:
/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#if defined(GTK_DISABLE_SINGLE_INCLUDES) && !defined (__GTK_H_INSIDE__) && !defined (GTK_COMPILATION)
#error "Only <gtk/gtk.h> can be included directly."
#endif

#ifndef __GTK_PROGRESS_BAR_H__
#define __GTK_PROGRESS_BAR_H__

#include <gtk/gtkprogress.h>

G_BEGIN_DECLS

#define GTK_TYPE_PROGRESS_BAR            (gtk_progress_bar_get_type ())
#define GTK_PROGRESS_BAR(obj)            (G_TYPE_CHECK_INSTANCE_CAST ((obj), GTK_TYPE_PROGRESS_BAR, GtkProgressBar))
#define GTK_PROGRESS_BAR_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass), GTK_TYPE_PROGRESS_BAR, GtkProgressBarClass))
#define GTK_IS_PROGRESS_BAR(obj)         (G_TYPE_CHECK_INSTANCE_TYPE ((obj), GTK_TYPE_PROGRESS_BAR))
#define GTK_IS_PROGRESS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), GTK_TYPE_PROGRESS_BAR))
#define GTK_PROGRESS_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), GTK_TYPE_PROGRESS_BAR, GtkProgressBarClass))

typedef struct _GtkProgressBar       GtkProgressBar;
typedef struct _GtkProgressBarClass  GtkProgressBarClass;

typedef enum
{
  GTK_PROGRESS_CONTINUOUS,
  GTK_PROGRESS_DISCRETE
} GtkProgressBarStyle;

typedef enum
{
  GTK_PROGRESS_LEFT_TO_RIGHT,
  GTK_PROGRESS_RIGHT_TO_LEFT,
  GTK_PROGRESS_BOTTOM_TO_TOP,
  GTK_PROGRESS_TOP_TO_BOTTOM
} GtkProgressBarOrientation;

struct _GtkProgressBar
{
  GtkProgress progress;

  GtkProgressBarStyle       GSEAL (bar_style);
  GtkProgressBarOrientation GSEAL (orientation);

  guint GSEAL (blocks);
  gint  GSEAL (in_block);

  gint  GSEAL (activity_pos);
  guint GSEAL (activity_step);
  guint GSEAL (activity_blocks);

  gdouble GSEAL (pulse_fraction);

  guint GSEAL (activity_dir) : 1;
  guint GSEAL (ellipsize) : 3;
  guint GSEAL (dirty) : 1;
};

struct _GtkProgressBarClass
{
  GtkProgressClass parent_class;

  /* Padding for future expansion */
  void (*_gtk_reserved1) (void);
  void (*_gtk_reserved2) (void);
  void (*_gtk_reserved3) (void);
  void (*_gtk_reserved4) (void);
};

GType      gtk_progress_bar_get_type             (void) G_GNUC_CONST;
GtkWidget* gtk_progress_bar_new                  (void);

/*
 * GtkProgress/GtkProgressBar had serious problems in GTK 1.2.
 *
 *  - Only 3 or 4 functions are really needed for 95% of progress
 *    interfaces; GtkProgress[Bar] had about 25 functions, and
 *    didn't even include these 3 or 4.
 *  - In activity mode, the API involves setting the adjustment
 *    to any random value, just to have the side effect of
 *    calling the progress bar update function - the adjustment
 *    is totally ignored in activity mode
 *  - You set the activity step as a pixel value, which means to
 *    set the activity step you basically need to connect to
 *    size_allocate
 *  - There are ctree_set_expander_style()-functions, to randomly
 *    change look-and-feel for no good reason
 *  - The split between GtkProgress and GtkProgressBar makes no sense
 *    to me whatsoever.
 *
 * This was a big wart on GTK and made people waste lots of time,
 * both learning and using the interface.
 *
 * So, I have added what I feel is the correct API, and marked all the
 * rest deprecated. However, the changes are 100% backward-compatible and
 * should break no existing code.
 *
 * The following 9 functions are the new programming interface.
 */
void       gtk_progress_bar_pulse                (GtkProgressBar *pbar);
void       gtk_progress_bar_set_text             (GtkProgressBar *pbar,
                                                  const gchar    *text);
void       gtk_progress_bar_set_fraction         (GtkProgressBar *pbar,
                                                  gdouble         fraction);

void       gtk_progress_bar_set_pulse_step       (GtkProgressBar *pbar,
                                                  gdouble         fraction);
void       gtk_progress_bar_set_orientation      (GtkProgressBar *pbar,
						  GtkProgressBarOrientation orientation);

G_CONST_RETURN gchar* gtk_progress_bar_get_text       (GtkProgressBar *pbar);
gdouble               gtk_progress_bar_get_fraction   (GtkProgressBar *pbar);
gdouble               gtk_progress_bar_get_pulse_step (GtkProgressBar *pbar);

GtkProgressBarOrientation gtk_progress_bar_get_orientation (GtkProgressBar *pbar);
void               gtk_progress_bar_set_ellipsize (GtkProgressBar     *pbar,
						   PangoEllipsizeMode  mode);
PangoEllipsizeMode gtk_progress_bar_get_ellipsize (GtkProgressBar     *pbar);

#ifndef GTK_DISABLE_DEPRECATED

/* Everything below here is deprecated */
GtkWidget* gtk_progress_bar_new_with_adjustment  (GtkAdjustment  *adjustment);
void       gtk_progress_bar_set_bar_style        (GtkProgressBar *pbar,
						  GtkProgressBarStyle style);
void       gtk_progress_bar_set_discrete_blocks  (GtkProgressBar *pbar,
						  guint           blocks);
/* set_activity_step() is not only deprecated, it doesn't even work.
 * (Of course, it wasn't usable anyway, you had to set it from a size_allocate
 * handler or something)
 */
void       gtk_progress_bar_set_activity_step    (GtkProgressBar *pbar,
                                                  guint           step);
void       gtk_progress_bar_set_activity_blocks  (GtkProgressBar *pbar,
						  guint           blocks);
void       gtk_progress_bar_update               (GtkProgressBar *pbar,
						  gdouble         percentage);

#endif /* GTK_DISABLE_DEPRECATED */

G_END_DECLS

#endif /* __GTK_PROGRESS_BAR_H__ */


text:
#include "precompiled.hpp"
#include "memory/allocation.hpp"
#include "memory/allocation.inline.hpp"
#include "memory/resourceArea.hpp"
#include "runtime/os.hpp"
#include "runtime/task.hpp"
#include "runtime/threadCritical.hpp"
#include "utilities/ostream.hpp"
#ifdef TARGET_OS_FAMILY_linux
# include "os_linux.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_solaris
# include "os_solaris.inline.hpp"
#endif
#ifdef TARGET_OS_FAMILY_windows
# include "os_windows.inline.hpp"
#endif

void* CHeapObj::operator new(size_t size){
  return (void *) AllocateHeap(size, "CHeapObj-new");
}

void* CHeapObj::operator new (size_t size, const std::nothrow_t&  nothrow_constant) {
  char* p = (char*) os::malloc(size);
#ifdef ASSERT
  if (PrintMallocFree) trace_heap_malloc(size, "CHeapObj-new", p);
#endif
  return p;
}

void CHeapObj::operator delete(void* p){
 FreeHeap(p);
}

void* StackObj::operator new(size_t size)  { ShouldNotCallThis(); return 0; };
void  StackObj::operator delete(void* p)   { ShouldNotCallThis(); };
void* _ValueObj::operator new(size_t size)  { ShouldNotCallThis(); return 0; };
void  _ValueObj::operator delete(void* p)   { ShouldNotCallThis(); };

void* ResourceObj::operator new(size_t size, allocation_type type) {
  address res;
  switch (type) {
   case C_HEAP:
    res = (address)AllocateHeap(size, "C_Heap: ResourceOBJ");
    DEBUG_ONLY(set_allocation_type(res, C_HEAP);)
    break;
   case RESOURCE_AREA:
    // new(size) sets allocation type RESOURCE_AREA.
    res = (address)operator new(size);
    break;
   default:
    ShouldNotReachHere();
  }
  return res;
}

void ResourceObj::operator delete(void* p) {
  assert(((ResourceObj *)p)->allocated_on_C_heap(),
         "delete only allowed for C_HEAP objects");
  DEBUG_ONLY(((ResourceObj *)p)->_allocation_t[0] = (uintptr_t)badHeapOopVal;)
  FreeHeap(p);
}

#ifdef ASSERT
void ResourceObj::set_allocation_type(address res, allocation_type type) {
    // Set allocation type in the resource object
    uintptr_t allocation = (uintptr_t)res;
    assert((allocation & allocation_mask) == 0, "address should be aligned to 4 bytes at least");
    assert(type <= allocation_mask, "incorrect allocation type");
    ResourceObj* resobj = (ResourceObj *)res;
    resobj->_allocation_t[0] = ~(allocation + type);
    if (type != STACK_OR_EMBEDDED) {
      // Called from operator new() and CollectionSetChooser(),
      // set verification value.
      resobj->_allocation_t[1] = (uintptr_t)&(resobj->_allocation_t[1]) + type;
    }
}

ResourceObj::allocation_type ResourceObj::get_allocation_type() const {
    assert(~(_allocation_t[0] | allocation_mask) == (uintptr_t)this, "lost resource object");
    return (allocation_type)((~_allocation_t[0]) & allocation_mask);
}

bool ResourceObj::is_type_set() const {
    allocation_type type = (allocation_type)(_allocation_t[1] & allocation_mask);
    return get_allocation_type()  == type &&
           (_allocation_t[1] - type) == (uintptr_t)(&_allocation_t[1]);
}

ResourceObj::ResourceObj() { // default constructor
    if (~(_allocation_t[0] | allocation_mask) != (uintptr_t)this) {
      // Operator new() is not called for allocations
      // on stack and for embedded objects.
      set_allocation_type((address)this, STACK_OR_EMBEDDED);
    } else if (allocated_on_stack()) { // STACK_OR_EMBEDDED
      // For some reason we got a value which resembles
      // an embedded or stack object (operator new() does not
      // set such type). Keep it since it is valid value
      // (even if it was garbage).
      // Ignore garbage in other fields.
    } else if (is_type_set()) {
      // Operator new() was called and type was set.
      assert(!allocated_on_stack(),
             err_msg("not embedded or stack, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
                     this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
    } else {
      // Operator new() was not called.
      // Assume that it is embedded or stack object.
      set_allocation_type((address)this, STACK_OR_EMBEDDED);
    }
    _allocation_t[1] = 0; // Zap verification value
}

ResourceObj::ResourceObj(const ResourceObj& r) { // default copy constructor
    // Used in ClassFileParser::parse_constant_pool_entries() for ClassFileStream.
    // Note: garbage may resembles valid value.
    assert(~(_allocation_t[0] | allocation_mask) != (uintptr_t)this || !is_type_set(),
           err_msg("embedded or stack only, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
                   this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
    set_allocation_type((address)this, STACK_OR_EMBEDDED);
    _allocation_t[1] = 0; // Zap verification value
}

ResourceObj& ResourceObj::operator=(const ResourceObj& r) { // default copy assignment
    // Used in InlineTree::ok_to_inline() for WarmCallInfo.
    assert(allocated_on_stack(),
           err_msg("copy only into local, this(" PTR_FORMAT ") type %d a[0]=(" PTR_FORMAT ") a[1]=(" PTR_FORMAT ")",
                   this, get_allocation_type(), _allocation_t[0], _allocation_t[1]));
    // Keep current _allocation_t value;
    return *this;
}

ResourceObj::~ResourceObj() {
    // allocated_on_C_heap() also checks that encoded (in _allocation) address == this.
    if (!allocated_on_C_heap()) { // ResourceObj::delete() will zap _allocation for C_heap.
      _allocation_t[0] = (uintptr_t)badHeapOopVal; // zap type
    }
}
#endif // ASSERT

void trace_heap_malloc(size_t size, const char* name, void* p) {
  // A lock is not needed here - tty uses a lock internally
  tty->print_cr("Heap malloc " INTPTR_FORMAT " " SIZE_FORMAT " %s", p, size, name == NULL ? "" : name);
}

void trace_heap_free(void* p) {
  // A lock is not needed here - tty uses a lock internally
  tty->print_cr("Heap free   " INTPTR_FORMAT, p);
}

bool warn_new_operator = false; // see vm_main

//--------------------------------------------------------------------------------------
// ChunkPool implementation

// MT-safe pool of chunks to reduce malloc/free thrashing
// NB: not using Mutex because pools are used before Threads are initialized
class ChunkPool {
  Chunk*       _first;        // first cached Chunk; its first word points to next chunk
  size_t       _num_chunks;   // number of unused chunks in pool
  size_t       _num_used;     // number of chunks currently checked out
  const size_t _size;         // size of each chunk (must be uniform)

  // Our three static pools
  static ChunkPool* _large_pool;
  static ChunkPool* _medium_pool;
  static ChunkPool* _small_pool;

  // return first element or null
  void* get_first() {
    Chunk* c = _first;
    if (_first) {
      _first = _first->next();
      _num_chunks--;
    }
    return c;
  }

 public:
  // All chunks in a ChunkPool has the same size
   ChunkPool(size_t size) : _size(size) { _first = NULL; _num_chunks = _num_used = 0; }

  // Allocate a new chunk from the pool (might expand the pool)
  void* allocate(size_t bytes) {
    assert(bytes == _size, "bad size");
    void* p = NULL;
    { ThreadCritical tc;
      _num_used++;
      p = get_first();
      if (p == NULL) p = os::malloc(bytes);
    }
    if (p == NULL)
      vm_exit_out_of_memory(bytes, "ChunkPool::allocate");

    return p;
  }

  // Return a chunk to the pool
  void free(Chunk* chunk) {
    assert(chunk->length() + Chunk::aligned_overhead_size() == _size, "bad size");
    ThreadCritical tc;
    _num_used--;

    // Add chunk to list
    chunk->set_next(_first);
    _first = chunk;
    _num_chunks++;
  }

  // Prune the pool
  void free_all_but(size_t n) {
    // if we have more than n chunks, free all of them
    ThreadCritical tc;
    if (_num_chunks > n) {
      // free chunks at end of queue, for better locality
      Chunk* cur = _first;
      for (size_t i = 0; i < (n - 1) && cur != NULL; i++) cur = cur->next();

      if (cur != NULL) {
        Chunk* next = cur->next();
        cur->set_next(NULL);
        cur = next;

        // Free all remaining chunks
        while(cur != NULL) {
          next = cur->next();
          os::free(cur);
          _num_chunks--;
          cur = next;
        }
      }
    }
  }

  // Accessors to preallocated pool's
  static ChunkPool* large_pool()  { assert(_large_pool  != NULL, "must be initialized"); return _large_pool;  }
  static ChunkPool* medium_pool() { assert(_medium_pool != NULL, "must be initialized"); return _medium_pool; }
  static ChunkPool* small_pool()  { assert(_small_pool  != NULL, "must be initialized"); return _small_pool;  }

  static void initialize() {
    _large_pool  = new ChunkPool(Chunk::size        + Chunk::aligned_overhead_size());
    _medium_pool = new ChunkPool(Chunk::medium_size + Chunk::aligned_overhead_size());
    _small_pool  = new ChunkPool(Chunk::init_size   + Chunk::aligned_overhead_size());
  }

  static void clean() {
    enum { BlocksToKeep = 5 };
     _small_pool->free_all_but(BlocksToKeep);
     _medium_pool->free_all_but(BlocksToKeep);
     _large_pool->free_all_but(BlocksToKeep);
  }
};

ChunkPool* ChunkPool::_large_pool  = NULL;
ChunkPool* ChunkPool::_medium_pool = NULL;
ChunkPool* ChunkPool::_small_pool  = NULL;

void chunkpool_init() {
  ChunkPool::initialize();
}

void
Chunk::clean_chunk_pool() {
  ChunkPool::clean();
}

//--------------------------------------------------------------------------------------
// ChunkPoolCleaner implementation
//

class ChunkPoolCleaner : public PeriodicTask {
  enum { CleaningInterval = 5000 };      // cleaning interval in ms

 public:
   ChunkPoolCleaner() : PeriodicTask(CleaningInterval) {}
   void task() {
     ChunkPool::clean();
   }
};

//--------------------------------------------------------------------------------------
// Chunk implementation

void* Chunk::operator new(size_t requested_size, size_t length) {
  // requested_size is equal to sizeof(Chunk) but in order for the arena
  // allocations to come out aligned as expected the size must be aligned
  // to expected arean alignment.
  // expect requested_size but if sizeof(Chunk) doesn't match isn't proper size we must align it.
  assert(ARENA_ALIGN(requested_size) == aligned_overhead_size(), "Bad alignment");
  size_t bytes = ARENA_ALIGN(requested_size) + length;
  switch (length) {
   case Chunk::size:        return ChunkPool::large_pool()->allocate(bytes);
   case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes);
   case Chunk::init_size:   return ChunkPool::small_pool()->allocate(bytes);
   default: {
     void *p =  os::malloc(bytes);
     if (p == NULL)
       vm_exit_out_of_memory(bytes, "Chunk::new");
     return p;
   }
  }
}

void Chunk::operator delete(void* p) {
  Chunk* c = (Chunk*)p;
  switch (c->length()) {
   case Chunk::size:        ChunkPool::large_pool()->free(c); break;
   case Chunk::medium_size: ChunkPool::medium_pool()->free(c); break;
   case Chunk::init_size:   ChunkPool::small_pool()->free(c); break;
   default:                 os::free(c);
  }
}

Chunk::Chunk(size_t length) : _len(length) {
  _next = NULL;         // Chain on the linked list
}

void Chunk::chop() {
  Chunk *k = this;
  while( k ) {
    Chunk *tmp = k->next();
    // clear out this chunk (to detect allocation bugs)
    if (ZapResourceArea) memset(k->bottom(), badResourceValue, k->length());
    delete k;                   // Free chunk (was malloc'd)
    k = tmp;
  }
}

void Chunk::next_chop() {
  _next->chop();
  _next = NULL;
}

void Chunk::start_chunk_pool_cleaner_task() {
#ifdef ASSERT
  static bool task_created = false;
  assert(!task_created, "should not start chuck pool cleaner twice");
  task_created = true;
#endif
  ChunkPoolCleaner* cleaner = new ChunkPoolCleaner();
  cleaner->enroll();
}

//------------------------------Arena------------------------------------------

Arena::Arena(size_t init_size) {
  size_t round_size = (sizeof (char *)) - 1;
  init_size = (init_size+round_size) & ~round_size;
  _first = _chunk = new (init_size) Chunk(init_size);
  _hwm = _chunk->bottom();      // Save the cached hwm, max
  _max = _chunk->top();
  set_size_in_bytes(init_size);
}

Arena::Arena() {
  _first = _chunk = new (Chunk::init_size) Chunk(Chunk::init_size);
  _hwm = _chunk->bottom();      // Save the cached hwm, max
  _max = _chunk->top();
  set_size_in_bytes(Chunk::init_size);
}

Arena::Arena(Arena *a) : _chunk(a->_chunk), _hwm(a->_hwm), _max(a->_max), _first(a->_first) {
  set_size_in_bytes(a->size_in_bytes());
}

Arena *Arena::move_contents(Arena *copy) {
  copy->destruct_contents();
  copy->_chunk = _chunk;
  copy->_hwm   = _hwm;
  copy->_max   = _max;
  copy->_first = _first;
  copy->set_size_in_bytes(size_in_bytes());
  // Destroy original arena
  reset();
  return copy;            // Return Arena with contents
}

Arena::~Arena() {
  destruct_contents();
}

// Destroy this arenas contents and reset to empty
void Arena::destruct_contents() {
  if (UseMallocOnly && _first != NULL) {
    char* end = _first->next() ? _first->top() : _hwm;
    free_malloced_objects(_first, _first->bottom(), end, _hwm);
  }
  _first->chop();
  reset();
}

// Total of all Chunks in arena
size_t Arena::used() const {
  size_t sum = _chunk->length() - (_max-_hwm); // Size leftover in this Chunk
  register Chunk *k = _first;
  while( k != _chunk) {         // Whilst have Chunks in a row
    sum += k->length();         // Total size of this Chunk
    k = k->next();              // Bump along to next Chunk
  }
  return sum;                   // Return total consumed space.
}

void Arena::signal_out_of_memory(size_t sz, const char* whence) const {
  vm_exit_out_of_memory(sz, whence);
}

// Grow a new Chunk
void* Arena::grow( size_t x ) {
  // Get minimal required size.  Either real big, or even bigger for giant objs
  size_t len = MAX2(x, (size_t) Chunk::size);

  Chunk *k = _chunk;            // Get filled-up chunk address
  _chunk = new (len) Chunk(len);

  if (_chunk == NULL) {
    signal_out_of_memory(len * Chunk::aligned_overhead_size(), "Arena::grow");
  }

  if (k) k->set_next(_chunk);   // Append new chunk to end of linked list
  else _first = _chunk;
  _hwm  = _chunk->bottom();     // Save the cached hwm, max
  _max =  _chunk->top();
  set_size_in_bytes(size_in_bytes() + len);
  void* result = _hwm;
  _hwm += x;
  return result;
}

// Reallocate storage in Arena.
void *Arena::Arealloc(void* old_ptr, size_t old_size, size_t new_size) {
  assert(new_size >= 0, "bad size");
  if (new_size == 0) return NULL;
#ifdef ASSERT
  if (UseMallocOnly) {
    // always allocate a new object  (otherwise we'll free this one twice)
    char* copy = (char*)Amalloc(new_size);
    size_t n = MIN2(old_size, new_size);
    if (n > 0) memcpy(copy, old_ptr, n);
    Afree(old_ptr,old_size);    // Mostly done to keep stats accurate
    return copy;
  }
#endif
  char *c_old = (char*)old_ptr; // Handy name
  // Stupid fast special case
  if( new_size <= old_size ) {  // Shrink in-place
    if( c_old+old_size == _hwm) // Attempt to free the excess bytes
      _hwm = c_old+new_size;    // Adjust hwm
    return c_old;
  }

  // make sure that new_size is legal
  size_t corrected_new_size = ARENA_ALIGN(new_size);

  // See if we can resize in-place
  if( (c_old+old_size == _hwm) &&       // Adjusting recent thing
      (c_old+corrected_new_size <= _max) ) {      // Still fits where it sits
    _hwm = c_old+corrected_new_size;      // Adjust hwm
    return c_old;               // Return old pointer
  }

  // Oops, got to relocate guts
  void *new_ptr = Amalloc(new_size);
  memcpy( new_ptr, c_old, old_size );
  Afree(c_old,old_size);        // Mostly done to keep stats accurate
  return new_ptr;
}

// Determine if pointer belongs to this Arena or not.
bool Arena::contains( const void *ptr ) const {
#ifdef ASSERT
  if (UseMallocOnly) {
    // really slow, but not easy to make fast
    if (_chunk == NULL) return false;
    char** bottom = (char**)_chunk->bottom();
    for (char** p = (char**)_hwm - 1; p >= bottom; p--) {
      if (*p == ptr) return true;
    }
    for (Chunk *c = _first; c != NULL; c = c->next()) {
      if (c == _chunk) continue;  // current chunk has been processed
      char** bottom = (char**)c->bottom();
      for (char** p = (char**)c->top() - 1; p >= bottom; p--) {
        if (*p == ptr) return true;
      }
    }
    return false;
  }
#endif
  if( (void*)_chunk->bottom() <= ptr && ptr < (void*)_hwm )
    return true;                // Check for in this chunk
  for (Chunk *c = _first; c; c = c->next()) {
    if (c == _chunk) continue;  // current chunk has been processed
    if ((void*)c->bottom() <= ptr && ptr < (void*)c->top()) {
      return true;              // Check for every chunk in Arena
    }
  }
  return false;                 // Not in any Chunk, so not in Arena
}

#ifdef ASSERT
void* Arena::malloc(size_t size) {
  assert(UseMallocOnly, "shouldn't call");
  // use malloc, but save pointer in res. area for later freeing
  char** save = (char**)internal_malloc_4(sizeof(char*));
  return (*save = (char*)os::malloc(size));
}

// for debugging with UseMallocOnly
void* Arena::internal_malloc_4(size_t x) {
  assert( (x&(sizeof(char*)-1)) == 0, "misaligned size" );
  check_for_overflow(x, "Arena::internal_malloc_4");
  if (_hwm + x > _max) {
    return grow(x);
  } else {
    char *old = _hwm;
    _hwm += x;
    return old;
  }
}
#endif

//--------------------------------------------------------------------------------------
// Non-product code

#ifndef PRODUCT
// The global operator new should never be called since it will usually indicate
// a memory leak.  Use CHeapObj as the base class of such objects to make it explicit
// that they're allocated on the C heap.
// Commented out in product version to avoid conflicts with third-party C++ native code.
// %% note this is causing a problem on solaris debug build. the global
// new is being called from jdk source and causing data corruption.
// src/share/native/sun/awt/font/fontmanager/textcache/hsMemory.cpp::hsSoftNew
// define CATCH_OPERATOR_NEW_USAGE if you want to use this.
#ifdef CATCH_OPERATOR_NEW_USAGE
void* operator new(size_t size){
  static bool warned = false;
  if (!warned && warn_new_operator)
    warning("should not call global (default) operator new");
  warned = true;
  return (void *) AllocateHeap(size, "global operator new");
}
#endif

void AllocatedObj::print() const       { print_on(tty); }
void AllocatedObj::print_value() const { print_value_on(tty); }

void AllocatedObj::print_on(outputStream* st) const {
  st->print_cr("AllocatedObj(" INTPTR_FORMAT ")", this);
}

void AllocatedObj::print_value_on(outputStream* st) const {
  st->print("AllocatedObj(" INTPTR_FORMAT ")", this);
}

julong Arena::_bytes_allocated = 0;

void Arena::inc_bytes_allocated(size_t x) { inc_stat_counter(&_bytes_allocated, x); }

AllocStats::AllocStats() {
  start_mallocs      = os::num_mallocs;
  start_frees        = os::num_frees;
  start_malloc_bytes = os::alloc_bytes;
  start_mfree_bytes  = os::free_bytes;
  start_res_bytes    = Arena::_bytes_allocated;
}

julong  AllocStats::num_mallocs() { return os::num_mallocs - start_mallocs; }
julong  AllocStats::alloc_bytes() { return os::alloc_bytes - start_malloc_bytes; }
julong  AllocStats::num_frees()   { return os::num_frees - start_frees; }
julong  AllocStats::free_bytes()  { return os::free_bytes - start_mfree_bytes; }
julong  AllocStats::resource_bytes() { return Arena::_bytes_allocated - start_res_bytes; }
void    AllocStats::print() {
  tty->print_cr(UINT64_FORMAT " mallocs (" UINT64_FORMAT "MB), "
                UINT64_FORMAT" frees (" UINT64_FORMAT "MB), " UINT64_FORMAT "MB resrc",
                num_mallocs(), alloc_bytes()/M, num_frees(), free_bytes()/M, resource_bytes()/M);
}

// debugging code
inline void Arena::free_all(char** start, char** end) {
  for (char** p = start; p < end; p++) if (*p) os::free(*p);
}

void Arena::free_malloced_objects(Chunk* chunk, char* hwm, char* max, char* hwm2) {
  assert(UseMallocOnly, "should not call");
  // free all objects malloced since resource mark was created; resource area
  // contains their addresses
  if (chunk->next()) {
    // this chunk is full, and some others too
    for (Chunk* c = chunk->next(); c != NULL; c = c->next()) {
      char* top = c->top();
      if (c->next() == NULL) {
        top = hwm2;     // last junk is only used up to hwm2
        assert(c->contains(hwm2), "bad hwm2");
      }
      free_all((char**)c->bottom(), (char**)top);
    }
    assert(chunk->contains(hwm), "bad hwm");
    assert(chunk->contains(max), "bad max");
    free_all((char**)hwm, (char**)max);
  } else {
    // this chunk was partially used
    assert(chunk->contains(hwm), "bad hwm");
    assert(chunk->contains(hwm2), "bad hwm2");
    free_all((char**)hwm, (char**)hwm2);
  }
}

ReallocMark::ReallocMark() {
#ifdef ASSERT
  Thread *thread = ThreadLocalStorage::get_thread_slow();
  _nesting = thread->resource_area()->nesting();
#endif
}

void ReallocMark::check() {
#ifdef ASSERT
  if (_nesting != Thread::current()->resource_area()->nesting()) {
    fatal("allocation bug: array could grow within nested ResourceMark");
  }
#endif
}

#endif // Non-product


text:
var _ = require('lodash');

var webSocketId = 0;
var webSocketMap = {};

var WebSocket = module.exports = function (url) {
  var id = webSocketId++;
  webSocketMap[id] = this;
  _init_websocket(id+"", url);
};

function addNativeApis(Class, apis) {
  _.each(apis, function (fn, key) {
    Class.prototype[key] = fn;
    Class[key] = function (id) {
      var args = Array.prototype.slice.call(arguments);
      var ws = webSocketMap[id];
      args.shift();
      ws[key].apply(ws, args);
    };
  });
}

addNativeApis(WebSocket, {
  _message: function (msg) {
    if (this.onmessage) {
      this.onmessage({data: msg});
    }
  },

  _error: function (err) {
    if (this.onerror) {
      this.onerror(new Error(err));
    }
  },

  _connect: function () {
    if (this.onconnect) {
      this.onconnect();
    }
  },

  _close: function () {
    if (this.onclose) {
      this.onclose();
    }
  }
});


text:
<?php namespace Queni\DLearning\Models;

use Model;

/**
 * Tests Model
 */
class Tests extends Model
{

    /**
     * @var string The database table used by the model.
     */
    public $table = 'queni_dlearning_tests';

    /**
     * @var array Guarded fields
     */
    protected $guarded = ['*'];

    /**
     * @var array Fillable fields
     */
    protected $fillable = [];

    /**
     * @var array Relations
     */
    public $hasOne = [];
    public $hasMany = [];
    public $belongsTo = [];
    public $belongsToMany = [];
    public $morphTo = [];
    public $morphOne = [];
    public $morphMany = [];
    public $attachOne = [];
    public $attachMany = [];

}


text:
package com.rwtema.extrautils.worldgen.Underdark;

import net.minecraft.util.Facing;
import java.util.Iterator;
import net.minecraft.inventory.IInventory;
import net.minecraft.block.Block;
import com.rwtema.extrautils.helper.XUHelper;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import com.rwtema.extrautils.ChunkPos;
import java.util.ArrayList;
import net.minecraft.item.ItemStack;
import net.minecraft.world.gen.feature.WorldGenerator;

public class WorldGenBedrockTree extends WorldGenerator
{
    public ItemStack[] items;
    private ArrayList<ChunkPos> torchPos;
    private ChunkPos chestPos;

    public WorldGenBedrockTree() {
        this.items = new ItemStack[] { new ItemStack(Items.gold_ingot), new ItemStack(Items.iron_ingot), new ItemStack(Items.diamond), new ItemStack(Items.emerald), new ItemStack(Blocks.stone), new ItemStack(Blocks.cobblestone), new ItemStack(Items.coal), new ItemStack(Items.coal), new ItemStack(Blocks.stone), new ItemStack(Blocks.stone), new ItemStack(Blocks.stone), new ItemStack(Blocks.stone), new ItemStack(Blocks.mossy_cobblestone), new ItemStack(Blocks.mossy_cobblestone), new ItemStack(Blocks.cobblestone), new ItemStack(Blocks.torch), new ItemStack(Blocks.torch), new ItemStack(Items.redstone) };
        this.torchPos = new ArrayList<ChunkPos>();
    }

    public boolean generate(final World par1World, final Random par2Random, final int par3, final int par4, final int par5) {
        if (par2Random.nextInt(960) == 0) {
            XUHelper.resetTimer();
            final int r = 4 + par2Random.nextInt(6);
            final int x = par3 + par2Random.nextInt(8) - par2Random.nextInt(8);
            final int z = par5 + par2Random.nextInt(8) - par2Random.nextInt(8);
            this.torchPos.clear();
            this.chestPos = new ChunkPos(x, 80, z);
            this.genTreePart(par1World, x, 80, z, 1, 10, par2Random);
            par1World.setBlock(this.chestPos.x, this.chestPos.y, this.chestPos.z, (Block)Blocks.chest);
            if (par1World.getTileEntity(this.chestPos.x, this.chestPos.y, this.chestPos.z) instanceof IInventory) {
                final IInventory inv = (IInventory)par1World.getTileEntity(this.chestPos.x, this.chestPos.y, this.chestPos.z);
                for (int i = 0; i < inv.getSizeInventory(); ++i) {
                    final ItemStack t = this.items[par2Random.nextInt(this.items.length)].copy();
                    t.stackSize = 1 + par2Random.nextInt(1 + par2Random.nextInt(1 + par2Random.nextInt(1 + par2Random.nextInt(1 + par2Random.nextInt(64)))));
                    inv.setInventorySlotContents(i, t);
                }
            }
            for (final ChunkPos torchPo1 : this.torchPos) {
                if (par1World.getBlock(torchPo1.x, torchPo1.y, torchPo1.z) == Blocks.air) {
                    par1World.getChunkFromBlockCoords(torchPo1.x, torchPo1.z).func_150807_a(torchPo1.x & 0xF, torchPo1.y, torchPo1.z & 0xF, Blocks.torch, 5);
                }
            }
            for (final ChunkPos torchPo2 : this.torchPos) {
                par1World.func_147451_t(torchPo2.x, torchPo2.y, torchPo2.z);
            }
        }
        return true;
    }

    public void genTreePart(final World world, final int x, final int y, final int z, final int dir, final int dist, final Random rand) {
        if (dist < 1) {
            return;
        }
        for (int i = 1; i < dist + 1; ++i) {
            if (world.getBlock(x + Facing.offsetsXForSide[dir] * i, y + Facing.offsetsYForSide[dir] * i, z + Facing.offsetsZForSide[dir] * i) == Blocks.bedrock) {
                return;
            }
            if (y + Facing.offsetsYForSide[dir] * i + 1 > this.chestPos.y) {
                this.chestPos = new ChunkPos(x + Facing.offsetsXForSide[dir] * i, y + Facing.offsetsYForSide[dir] * i + 1, z + Facing.offsetsZForSide[dir] * i);
            }
            world.setBlock(x + Facing.offsetsXForSide[dir] * i, y + Facing.offsetsYForSide[dir] * i, z + Facing.offsetsZForSide[dir] * i, Blocks.bedrock);
            if (y + Facing.offsetsYForSide[dir] * i < 80) {
                return;
            }
            if (y + Facing.offsetsYForSide[dir] * i > 120) {
                return;
            }
            if (rand.nextInt(5) == 0) {
                this.torchPos.add(new ChunkPos(x, y + 1, z));
            }
        }
        if (dist <= 1) {
            return;
        }
        for (int d = 0; d < 6; ++d) {
            if (d != Facing.oppositeSide[dir]) {
                this.genTreePart(world, x + Facing.offsetsXForSide[dir] * dist, y + Facing.offsetsYForSide[dir] * dist, z + Facing.offsetsZForSide[dir] * dist, d, (int)Math.floor(rand.nextDouble() * dist), rand);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?><!--  Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
 -->

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">

    <string name="select_hours">"Pilih jam"</string>
    <string name="select_minutes">"Pilih menit"</string>
    <string name="day_picker_description">"Kisi hari pada bulan"</string>
    <string name="year_picker_description">"Daftar tahun"</string>
    <string name="select_day">"Pilih bulan dan hari"</string>
    <string name="select_year">"Pilih tahun"</string>
    <string name="item_is_selected">"<xliff:g id="ITEM">%1$s</xliff:g> dipilih"</string>
    <string name="deleted_key">"<xliff:g id="KEY">%1$s</xliff:g> dihapus"</string>

    <string name="ok">"Oke"</string>
    <string name="cancel">"Batal"</string>

    <string name="endByDate">"; sampai <xliff:g id="DATE">%s</xliff:g>"</string>
    <plurals name="endByCount">
        <item quantity="one">"; sekali saja"</item>
        <item quantity="other">"; untuk <xliff:g id="NUMBER">%d</xliff:g> kali"</item>
    </plurals>
    <plurals name="daily">
        <item quantity="one">"Harian"</item>
        <item quantity="other">"Setiap <xliff:g id="NUMBER">%d</xliff:g> hari"</item>
    </plurals>
    <string name="every_weekday">"Setiap hari kerja (Sen–Jum)"</string>
    <plurals name="weekly">
        <item quantity="one">"Mingguan setiap <xliff:g id="DAYS_OF_WEEK">%2$s</xliff:g>"</item>
        <item quantity="other">"Setiap <xliff:g id="NUMBER">%1$d</xliff:g> minggu hari <xliff:g id="DAYS_OF_WEEK">%2$s</xliff:g>"</item>
    </plurals>
    <string name="monthly">"Bulanan"</string>
    <string name="yearly_plain">"Tahunan"</string>
    <plurals name="recurrence_interval_daily">
        <item quantity="one">"<xliff:g id="COUNT">%d</xliff:g> hari sekali"</item>
        <item quantity="other">"<xliff:g id="COUNT">%d</xliff:g> hari sekali"</item>
    </plurals>
    <plurals name="recurrence_interval_weekly">
        <item quantity="one">"<xliff:g id="COUNT">%d</xliff:g> minggu sekali"</item>
        <item quantity="other">"<xliff:g id="COUNT">%d</xliff:g> minggu sekali"</item>
    </plurals>
    <plurals name="recurrence_interval_monthly">
        <item quantity="one">"<xliff:g id="COUNT">%d</xliff:g> bulan sekali"</item>
        <item quantity="other">"<xliff:g id="COUNT">%d</xliff:g> bulan sekali"</item>
    </plurals>
    <plurals name="recurrence_interval_yearly">
        <item quantity="one">"<xliff:g id="COUNT">%d</xliff:g> tahun sekali"</item>
        <item quantity="other">"<xliff:g id="COUNT">%d</xliff:g> tahun sekali"</item>
    </plurals>
    <string name="recurrence_month_pattern_by_day">"bulanan-hari yg sama"</string>
    <string name="recurrence_end_continously">"Selamanya"</string>
    <string name="recurrence_end_date_label">"Sampai tanggal tertentu"</string>
    <string name="recurrence_end_date">"Sampai <xliff:g id="DATE">%s</xliff:g>"</string>
    <string name="recurrence_end_count_label">"Untuk sejumlah acara"</string>
    <plurals name="recurrence_end_count">
        <item quantity="one">"Untuk <xliff:g id="EVENT_COUNT">%d</xliff:g> acara"</item>
        <item quantity="other">"Untuk <xliff:g id="EVENT_COUNT">%d</xliff:g> acara"</item>
    </plurals>
    <string name="acessibility_recurrence_choose_end_date_description">"ubah tanggal akhir"</string>
</resources>


text:
package auction.dao;

import auction.domain.User;
import java.util.List;
import javax.persistence.EntityExistsException;
import javax.persistence.EntityManager;
import javax.persistence.Query;

public class UserDAOJPAImpl implements UserDAO {

    private final EntityManager em;

    public UserDAOJPAImpl(EntityManager em) {
        this.em = em;
    }

    @Override
    public int count() {
        Query q = this.em.createNamedQuery("User.count", User.class);
        int result = ((Long) q.getSingleResult()).intValue();
        return result;
    }

    @Override
    public void create(User user) {
        if (findByEmail(user.getEmail()) != null) {
            throw new EntityExistsException();
        }
        this.em.getTransaction().begin();
        this.em.persist(user);
        this.em.getTransaction().commit();
    }

    @Override
    public void edit(User user) {
        if (findByEmail(user.getEmail()) == null) {
            throw new IllegalArgumentException();
        }

        this.em.persist(user);
    }

    @Override
    public List<User> findAll() {
        Query q = this.em.createNamedQuery("User.getAll", User.class);
        List<User> result = q.getResultList();
        return result;
    }

    @Override
    public User findByEmail(String email) {
        Query q = this.em.createNamedQuery("User.findByEmail", User.class);
        q.setParameter("email", email);

        try {
             User result = (User) q.getSingleResult();
             return result;

        }catch(Exception e){
            return null;
        }
    }

    @Override
    public void remove(User user) {
        em.remove(user);
    }

}


text:
CityGL.WMS = function(options){
	CityGL.Layer.apply(this, arguments);
	this.type = 'image/jpeg';
	this.res = 0.565685424949;
	this.tileSize = 1024;
	this.maxExtent = new CityGL.BoundingBox(new CityGL.Point(-285401.92,22598.08,0),new CityGL.Point(595401.92,903401.92,0));
	this.textureCompressionService = null;
	this.setValues(options);
	this.wms = "http://geodata1.nationaalgeoregister.nl/luchtfoto/wms?";
	this.sourceEPSG = "EPSG:28992";
	this.version = '1.1.1';
	this.layers= 'luchtfoto';
	this.setValues(options);
}
CityGL.WMS.prototype = new CityGL.Layer();
CityGL.WMS.prototype.constructor = CityGL.WMS;
CityGL.WMS.prototype.GetObject3Ds = function(){
	var epsg = this.viewport.EPSG;
	var extent =this.viewport.boundingBox;
	var obj3D = new THREE.Object3D();
	var mergeMesh = new THREE.Mesh();
	var mesh = new THREE.Mesh();
	var needsReprojection = epsg != this.sourceEPSG;
	var source = new Proj4js.Proj(epsg);
	var dest= new Proj4js.Proj(this.sourceEPSG);
	var sourceExtent = extent;
	if (needsReprojection){
		var ll = new Proj4js.Point(extent.lowerLeft.x, extent.lowerLeft.y);
		Proj4js.transform(source, dest, ll);
		var ur = new Proj4js.Point(extent.upperRight.x, extent.upperRight.y);
		Proj4js.transform(source, dest, ur);
		sourceExtent = new CityGL.BoundingBox(new CityGL.Point(ll.x, ll.y,0),new CityGL.Point( ur.x, ur.y,0));
	}
	var x = Math.round ((sourceExtent.lowerLeft.x - this.maxExtent.lowerLeft.x) / (this.res * this.tileSize));
	var y = Math.round ((this.maxExtent.upperRight.y - sourceExtent.upperRight.y) / (this.res * this.tileSize));
	var originx =this.maxExtent.lowerLeft.x+ x * this.res * this.tileSize;
	var originy = this.maxExtent.upperRight.y- y * this.res * this.tileSize;
	var xgrid = [];
	var ygrid = [];
	var materialArray = [];
	for (var i = originx; i< sourceExtent.upperRight.x; i+=this.res*this.tileSize ){ xgrid.push(i);}
	for (var i = originy; i>sourceExtent.lowerLeft.y; i-=this.res*this.tileSize ){ygrid.push(i);}

	for (var i = 0; i< (xgrid.length); i++){
		for (var j = 0; j< (ygrid.length); j++){
		var xloc = Math.round ((xgrid[i] - this.maxExtent.lowerLeft.x) / (this.res * this.tileSize));
			var yloc = Math.round ((this.maxExtent.upperRight.y - ygrid[j]) / (this.res * this.tileSize));
			var vertices = [{x: xgrid[i], y: ygrid[j] - this.res * this.tileSize}, {x:xgrid[i] + this.res * this.tileSize, y: ygrid[j] - this.res * this.tileSize }, {x: xgrid[i]+this.res * this.tileSize ,y: ygrid[j]},{x: xgrid[i], y: ygrid[j]} ];
			var bbox = "" + vertices[0].x+","+vertices[0].y+","+vertices[2].x+","+vertices[2].y;
			var vertArray = [];
			for (var k = 0; k< vertices.length; k++){
				Proj4js.transform(dest, source, vertices[k]);
			}
			var tile = new CityGL.Tile(vertices);
			var geometry= tile.getGeometry(viewport);
			var urlarray = [];
			for (var k = this.tilemerge-1; k>=0 ; k--){
				for (var l =0; l< this.tilemerge ; l++){
					var tilelocx = Math.round ((xgrid[i]+l*this.res*this.tileSize - (this.maxExtent.lowerLeft.x)) / (this.res * this.tileSize));
					var tilelocy = Math.round ((this.maxExtent.upperRight.y - (ygrid[j]-k*this.res*this.tileSize)) / (this.res * this.tileSize));
					var xyzpath = this.zoomlevel + "/" + tilelocx + "/" + tilelocy + ".png";
					var url = osmurl + xyzpath;
					urlarray.push(url);
				}
			}
			var texture;
			urlarray[0] = this.wms+ "SERVICE=WMS&REQUEST=GetMap&VERSION="+ this.version+ "&LAYERs="+this.layers+"&STYLEs=&WIDTH="+this.tileSize+"&HEIGHT="+this.tileSize+"&FORMAT="+this.type+"&SRS="+this.sourceEPSG+"&BBOX=" + bbox ;
			if (this.textureCompressionService != null){
				var enc = this.textureCompressionService.getCompressedTextureUrl(urlarray, 1);
				texture = THREE.ImageUtils.loadCompressedTexture( enc );
			}
			else{
				texture = THREE.ImageUtils.loadTexture(urlarray[0]);
			}
			var tMaterial	= new THREE.MeshBasicMaterial({
				color	: 0xffffff,
				map	: texture
			});

			tMaterial.side = THREE.DoubleSide;
			var mesh	= new THREE.Mesh(geometry, tMaterial);

			obj3D.children.push(mesh);

		}
	}
	return [obj3D];
}


text:
package com.netease.nim.uikit.session.helper;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.widget.Toast;

import com.netease.nim.uikit.R;
import com.netease.nim.uikit.common.ui.dialog.CustomAlertDialog;
import com.netease.nim.uikit.common.util.C;
import com.netease.nim.uikit.common.util.file.AttachmentStore;
import com.netease.nim.uikit.common.util.file.FileUtil;
import com.netease.nim.uikit.common.util.storage.StorageType;
import com.netease.nim.uikit.common.util.storage.StorageUtil;
import com.netease.nim.uikit.common.util.string.MD5;
import com.netease.nim.uikit.common.util.string.StringUtil;
import com.netease.nim.uikit.session.activity.CaptureVideoActivity;

import java.io.File;

/**
 * Created by hzxuwen on 2015/4/10.
 */
public class VideoMessageHelper {
    private File videoFile;
    private String videoFilePath;

    private Activity activity;
    private VideoMessageHelperListener listener;

    private int localRequestCode;
    private int captureRequestCode;

    public VideoMessageHelper(Activity activity, VideoMessageHelperListener listener) {
        this.activity = activity;
        this.listener = listener;
    }

    public interface VideoMessageHelperListener {
        void onVideoPicked(File file, String md5);
    }

    /**
     * 显示视频拍摄或从本地相册中选取
     */
    public void showVideoSource(int local, int capture) {
        this.localRequestCode = local;
        this.captureRequestCode = capture;
        CustomAlertDialog dialog = new CustomAlertDialog(activity);
        dialog.setTitle(activity.getString(R.string.input_panel_video));
        dialog.addItem("拍摄视频",new CustomAlertDialog.onSeparateItemClickListener(){
            @Override
            public void onClick() {
                chooseVideoFromCamera();
            }
        });
        dialog.addItem("从相册中选择视频",new CustomAlertDialog.onSeparateItemClickListener() {
            @Override
            public void onClick() {
                chooseVideoFromLocal();
            }
        });
        dialog.show();
    }

    /************************************************* 视频操作S *******************************************/

    /**
     * 拍摄视频
     */
    protected void chooseVideoFromCamera() {
        if (!StorageUtil.hasEnoughSpaceForWrite(activity,
                StorageType.TYPE_VIDEO, true)) {
            return;
        }
        videoFilePath = StorageUtil.getWritePath(
                activity, StringUtil.get36UUID()
                        + C.FileSuffix.MP4, StorageType.TYPE_TEMP);
        videoFile = new File(videoFilePath);

        // 启动视频录制
        CaptureVideoActivity.start(activity, videoFilePath, captureRequestCode);
    }

    /**
     * 从本地相册中选择视频
     */
    protected void chooseVideoFromLocal() {
        if (Build.VERSION.SDK_INT >= 19) {
            chooseVideoFromLocalKitKat();
        } else {
            chooseVideoFromLocalBeforeKitKat();
        }
    }

    /**
     * API19 之后选择视频
     */
    protected void chooseVideoFromLocalKitKat() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        try {
            activity.startActivityForResult(intent, localRequestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.gallery_invalid, Toast.LENGTH_SHORT).show();
        } catch (SecurityException e) {

        }
    }

    /**
     * API19 之前选择视频
     */
    protected void chooseVideoFromLocalBeforeKitKat() {
        Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
        mIntent.setType(C.MimeType.MIME_VIDEO_ALL);
        mIntent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
        try {
            activity.startActivityForResult(mIntent, localRequestCode);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(activity, R.string.gallery_invalid, Toast.LENGTH_SHORT).show();
        }
    }

    /****************************视频选中后回调操作********************************************/

    /**
     * 获取本地相册视频回调操作
     */
    public void onGetLocalVideoResult(final Intent data) {
        if (data == null) {
            return;
        }

        String filePath = filePathFromIntent(data);
        if (StringUtil.isEmpty(filePath) || !checkVideoFile(filePath)) {
            return;
        }

        String md5 = MD5.getStreamMD5(filePath);
        String filename = md5 + "." + FileUtil.getExtensionName(filePath);
        String md5Path = StorageUtil.getWritePath(filename, StorageType.TYPE_VIDEO);

        if (AttachmentStore.copy(filePath, md5Path) != -1) {
            if (listener != null) {
                listener.onVideoPicked(new File(md5Path), md5);
            }
        } else {
            Toast.makeText(activity, R.string.video_exception, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 拍摄视频后回调操作
     */
    public void onCaptureVideoResult(Intent data) {
        if (videoFile == null || !videoFile.exists()) {
            return;
        }

        //N930拍照取消也产生字节为0的文件
        if (videoFile.length() <= 0) {
            videoFile.delete();
            return;
        }

        String videoPath = videoFile.getPath();
        String md5 = MD5.getStreamMD5(videoPath);
        String md5Path = StorageUtil.getWritePath(md5 + ".mp4", StorageType.TYPE_VIDEO);

        if (AttachmentStore.move(videoPath, md5Path)) {
            if (listener != null) {
                listener.onVideoPicked(new File(md5Path), md5);
            }
        }
    }

    /**
     * 获取文件路径
     * @param data intent数据
     * @return
     */
    private String filePathFromIntent(Intent data) {
        Uri uri = data.getData();

        try {
            Cursor cursor = activity.getContentResolver().query(uri, null, null, null,  null);
            if (cursor == null) {
                //miui 2.3 有可能为null
                return uri.getPath();
            } else {
                cursor.moveToFirst();
                return cursor.getString(cursor.getColumnIndex("_data")); // 文件路径
            }
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 检查文件
     * @param file 视频文件
     * @return boolean
     */
    private boolean checkVideoFile(String file) {
        if (!AttachmentStore.isFileExist(file)) {
            return false;
        }

        if (new File(file).length() > C.MAX_LOCAL_VIDEO_FILE_SIZE) {
            Toast.makeText(activity, R.string.im_choose_video_file_size_too_large, Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!StorageUtil.isInvalidVideoFile(file)) {
            Toast.makeText(activity, R.string.im_choose_video, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

}


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * YieldIntegrationType.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter.
 */

package com.google.api.ads.admanager.axis.v202202;

public class YieldIntegrationType implements java.io.Serializable {
    private java.lang.String _value_;
    private static java.util.HashMap _table_ = new java.util.HashMap();

    // Constructor
    protected YieldIntegrationType(java.lang.String value) {
        _value_ = value;
        _table_.put(_value_,this);
    }

    public static final java.lang.String _UNKNOWN = "UNKNOWN";
    public static final java.lang.String _CUSTOM_EVENT = "CUSTOM_EVENT";
    public static final java.lang.String _SDK = "SDK";
    public static final java.lang.String _OPEN_BIDDING = "OPEN_BIDDING";
    public static final java.lang.String _NETWORK_BIDDING = "NETWORK_BIDDING";
    public static final YieldIntegrationType UNKNOWN = new YieldIntegrationType(_UNKNOWN);
    public static final YieldIntegrationType CUSTOM_EVENT = new YieldIntegrationType(_CUSTOM_EVENT);
    public static final YieldIntegrationType SDK = new YieldIntegrationType(_SDK);
    public static final YieldIntegrationType OPEN_BIDDING = new YieldIntegrationType(_OPEN_BIDDING);
    public static final YieldIntegrationType NETWORK_BIDDING = new YieldIntegrationType(_NETWORK_BIDDING);
    public java.lang.String getValue() { return _value_;}
    public static YieldIntegrationType fromValue(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        YieldIntegrationType enumeration = (YieldIntegrationType)
            _table_.get(value);
        if (enumeration==null) throw new java.lang.IllegalArgumentException();
        return enumeration;
    }
    public static YieldIntegrationType fromString(java.lang.String value)
          throws java.lang.IllegalArgumentException {
        return fromValue(value);
    }
    public boolean equals(java.lang.Object obj) {return (obj == this);}
    public int hashCode() { return toString().hashCode();}
    public java.lang.String toString() { return _value_;}
    public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);}
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumSerializer(
            _javaType, _xmlType);
    }
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new org.apache.axis.encoding.ser.EnumDeserializer(
            _javaType, _xmlType);
    }
    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(YieldIntegrationType.class);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v202202", "YieldIntegrationType"));
    }
    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

}


text:
delete from waitlist;

alter table waitlist add changed_by varchar(40) null;
alter table waitlist add waitlisted int(1) not null default 0;
alter table waitlist add enrolled_course_id decimal(20,0);
alter table waitlist add demand_id decimal(20,0);
alter table waitlist add request varchar(255) null;
alter table waitlist add enrollment varchar(255) null;
alter table waitlist add waitlist_ts datetime;

alter table waitlist add constraint fk_waitlist_enrolled_course foreign key (enrolled_course_id)
	references course_offering (uniqueid) on delete set null;

alter table waitlist add constraint fk_waitlist_course_demand foreign key (demand_id)
	references course_demand (uniqueid) on delete set null;

/*
 * Update database version
 */

update application_config set value='246' where name='tmtbl.db.version';

commit;


text:
var CarbonClient = require('@carbon-io/carbon-client')

var client = new CarbonClient("http://localhost:8888")

var options = {
  parameters: {
    who: "carbon"
  }
}

// GET http://localhost:8888/hello?who=carbon
client.getEndpoint("hello").get(options, function(e, res) {
  console.log("Response from /hello: ")
  console.log(res.body)
})


text:
from __future__ import unicode_literals

import time
from datetime import datetime

from moto.core import BaseBackend, BaseModel
from moto.compat import OrderedDict
from .exceptions import (
    JsonRESTError,
    DatabaseAlreadyExistsException,
    DatabaseNotFoundException,
    TableAlreadyExistsException,
    TableNotFoundException,
    PartitionAlreadyExistsException,
    PartitionNotFoundException,
    VersionNotFoundException,
)

class GlueBackend(BaseBackend):
    def __init__(self):
        self.databases = OrderedDict()

    def create_database(self, database_name, database_input):
        if database_name in self.databases:
            raise DatabaseAlreadyExistsException()

        database = FakeDatabase(database_name, database_input)
        self.databases[database_name] = database
        return database

    def get_database(self, database_name):
        try:
            return self.databases[database_name]
        except KeyError:
            raise DatabaseNotFoundException(database_name)

    def get_databases(self):
        return [self.databases[key] for key in self.databases] if self.databases else []

    def create_table(self, database_name, table_name, table_input):
        database = self.get_database(database_name)

        if table_name in database.tables:
            raise TableAlreadyExistsException()

        table = FakeTable(database_name, table_name, table_input)
        database.tables[table_name] = table
        return table

    def get_table(self, database_name, table_name):
        database = self.get_database(database_name)
        try:
            return database.tables[table_name]
        except KeyError:
            raise TableNotFoundException(table_name)

    def get_tables(self, database_name):
        database = self.get_database(database_name)
        return [table for table_name, table in database.tables.items()]

    def delete_table(self, database_name, table_name):
        database = self.get_database(database_name)
        try:
            del database.tables[table_name]
        except KeyError:
            raise TableNotFoundException(table_name)
        return {}

class FakeDatabase(BaseModel):
    def __init__(self, database_name, database_input):
        self.name = database_name
        self.input = database_input
        self.created_time = datetime.utcnow()
        self.tables = OrderedDict()

    def as_dict(self):
        return {
            "Name": self.name,
            "Description": self.input.get("Description"),
            "LocationUri": self.input.get("LocationUri"),
            "Parameters": self.input.get("Parameters"),
            "CreateTime": self.created_time.isoformat(),
            "CreateTableDefaultPermissions": self.input.get(
                "CreateTableDefaultPermissions"
            ),
            "TargetDatabase": self.input.get("TargetDatabase"),
            "CatalogId": self.input.get("CatalogId"),
        }

class FakeTable(BaseModel):
    def __init__(self, database_name, table_name, table_input):
        self.database_name = database_name
        self.name = table_name
        self.partitions = OrderedDict()
        self.versions = []
        self.update(table_input)

    def update(self, table_input):
        self.versions.append(table_input)

    def get_version(self, ver):
        try:
            if not isinstance(ver, int):
                # "1" goes to [0]
                ver = int(ver) - 1
        except ValueError as e:
            raise JsonRESTError("InvalidInputException", str(e))

        try:
            return self.versions[ver]
        except IndexError:
            raise VersionNotFoundException()

    def as_dict(self, version=-1):
        obj = {"DatabaseName": self.database_name, "Name": self.name}
        obj.update(self.get_version(version))
        return obj

    def create_partition(self, partiton_input):
        partition = FakePartition(self.database_name, self.name, partiton_input)
        key = str(partition.values)
        if key in self.partitions:
            raise PartitionAlreadyExistsException()
        self.partitions[str(partition.values)] = partition

    def get_partitions(self):
        return [p for str_part_values, p in self.partitions.items()]

    def get_partition(self, values):
        try:
            return self.partitions[str(values)]
        except KeyError:
            raise PartitionNotFoundException()

    def update_partition(self, old_values, partiton_input):
        partition = FakePartition(self.database_name, self.name, partiton_input)
        key = str(partition.values)
        if old_values == partiton_input["Values"]:
            # Altering a partition in place. Don't remove it so the order of
            # returned partitions doesn't change
            if key not in self.partitions:
                raise PartitionNotFoundException()
        else:
            removed = self.partitions.pop(str(old_values), None)
            if removed is None:
                raise PartitionNotFoundException()
            if key in self.partitions:
                # Trying to update to overwrite a partition that exists
                raise PartitionAlreadyExistsException()
        self.partitions[key] = partition

    def delete_partition(self, values):
        try:
            del self.partitions[str(values)]
        except KeyError:
            raise PartitionNotFoundException()

class FakePartition(BaseModel):
    def __init__(self, database_name, table_name, partiton_input):
        self.creation_time = time.time()
        self.database_name = database_name
        self.table_name = table_name
        self.partition_input = partiton_input
        self.values = self.partition_input.get("Values", [])

    def as_dict(self):
        obj = {
            "DatabaseName": self.database_name,
            "TableName": self.table_name,
            "CreationTime": self.creation_time,
        }
        obj.update(self.partition_input)
        return obj

glue_backend = GlueBackend()


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Search_model extends CI_Model {

	var $data;

	public function __construct()
	{
		parent::__construct();
	}

    //fetch specific result
    function search()
    {
        $reg_no = $this->input->post('reg_no');
        $bdate = $this->input->post('bdate');
        $bdate = date("y-m-d",strtotime($bdate));

        $sql = "select * from competent_result as c JOIN persons AS p ON c.reg_no = p.reg_no where c.reg_no = '$reg_no' AND p.dob = '$bdate' ";
        $query = $this->db->query($sql);
        return $query->result();
    }
}


text:
package com.voxela.javashell.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

import org.bukkit.Bukkit;
import org.bukkit.scheduler.BukkitRunnable;

import com.voxela.javashell.JavaShell;

public class UpdateCheck {

	private static final String prefix = "[JavaShell] ";
	private static final String red = "\u001B[31m";
	private static final String reset = "\u001B[0m";

	public static void check() {

		new BukkitRunnable() {
			public void run() {

				Properties prop = new Properties();
				InputStream is = null;

				try {
					is = new ByteArrayInputStream(HttpUtil.requestHttp("https://raw.githubusercontent.com/Ladinn/JavaShell/master/JavaShell/plugin.yml").getBytes(StandardCharsets.UTF_8));
					prop.load(is);
				} catch (IOException e) {
					Bukkit.getServer().getLogger().info(prefix + "Error checking for update.");
					e.printStackTrace();
					return;
				}

				double latest = Double.parseDouble(prop.getProperty("version"));
				double current = JavaShell.version;

				if (latest == current) Bukkit.getServer().getLogger().info(prefix + "You have the latest version! v" + latest);

				if (latest > current) {

					double behind = (latest - current) * 10;
					String msg = HttpUtil.requestHttp("http://net.voxela.com/javashell/outdated.html");

					Bukkit.getServer().getLogger().warning(red + msg + reset);
					Bukkit.getServer().getLogger().warning(prefix + red + "You are " + (int) behind + " version(s) behind." + reset);
				}

			}
		}.runTaskLater(JavaShell.getInstance(), 200L);

    }

}


text:
import { Point } from '../types';
export declare const zeroPoint: Point;
export declare const isNum: (v: any) => v is number;


text:
//
// vs-remote-debugger (.NET SDK) (https://github.com/mkloubert/vs-remote-debugger)
// Copyright (c) Marcel Joachim Kloubert <marcel.kloubert@gmx.net>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//

using System.Collections.Generic;
using System.Runtime.Serialization;

namespace MarcelJoachimKloubert
{
    /// <summary>
    /// A scope.
    /// </summary>
    [DataContract]
    public class RemoteDebuggerScope
    {
        /// <summary>
        /// The name.
        /// </summary>
        [DataMember]
        public string n;

        /// <summary>
        /// The reference number.
        /// </summary>
        [DataMember]
        public int? r;

        /// <summary>
        /// The list of debugger variables.
        /// </summary>
        [DataMember]
        public IList<RemoteDebuggerVariable> v;
    }
}


text:
<?php

namespace CloverToHtml\Tests\RenderFactory;

use CloverToHtml\RenderFactory;

class GetInstanceTest extends \PHPUnit_Framework_TestCase
{
    public function testInstance()
    {
        $this->assertInstanceOf(
            '\CloverToHtml\Render',
            RenderFactory::getInstance()
        );
    }
}


text:
package org.peercentrum.application;

import org.peercentrum.core.ServerMain;

public class ApplicationLifecycleHandler {
  enum ApplicationState {
    STOPPED,
    STARTING,
    STARTED,
  }
  protected ApplicationState currentApplicationState=ApplicationState.STOPPED;
  protected ServerMain serverMain;

  public ApplicationLifecycleHandler(ServerMain serverMain){
    this.serverMain=serverMain;
  }

  synchronized public void changeState(ApplicationState newState){
    boolean isStateChangeLegal=currentApplicationState==ApplicationState.STARTED && newState==ApplicationState.STOPPED;
    isStateChangeLegal|=currentApplicationState.ordinal()+1!=newState.ordinal();
    if(isStateChangeLegal==false){
      throw new IllegalArgumentException("Cannot change state from "+currentApplicationState+" to "+newState);
    }

    onBeforeStateChange(newState);

    ApplicationState previousState=currentApplicationState;
    currentApplicationState=newState;

    onAfterStateChange(previousState);
  }

  public void onBeforeStateChange(ApplicationState newState){}
  public void onAfterStateChange(ApplicationState previousState){}
}