text:
//
//  TKTimeGraphController.m
//  Created by Devin Ross on 7/24/09.
//

#import "TKGraphController.h"
#import "TKGlobal.h"
#import "UIImageAdditions.h"

@implementation TKGraphController
@synthesize graph;

- (void) loadView{
	graph = [[TKGraphView alloc] initWithFrame:CGRectMake(0, 0, 480, 300)];
	self.view = graph;
}

- (void) viewDidLoad {

	//graph = [[TKGraph alloc] initWithFrame:CGRectMake(0, 0, 480, 300)];
	//graph.dataSource = self;
	//graph.backgroundColor = [UIColor whiteColor];
	//[self.view addSubview:graph];

	close = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
	close.frame = CGRectMake(-10, 0, 65, 45);
	[close setImage:[UIImage imageFromPath:TKBUNDLE(@"TapkuLibrary.bundle/Images/graph/close.png")] forState:UIControlStateNormal];
	[close setImage:[UIImage imageFromPath:TKBUNDLE(@"TapkuLibrary.bundle/Images/graph/close_touch.png")] forState:UIControlStateHighlighted];
	[close addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
	[self.view addSubview:close];

	[super viewDidLoad];

}

- (void) viewWillAppear:(BOOL)animated {
	 [super viewWillAppear:animated];
	 statusColor = [UIApplication sharedApplication].statusBarStyle;
	 [UIApplication sharedApplication].statusBarStyle =  UIStatusBarStyleBlackOpaque;
 }
- (void) viewWillDisappear:(BOOL)animated {
	 [super viewWillDisappear:animated];
	 [UIApplication sharedApplication].statusBarStyle =  statusColor;
 }

- (void) close{
	[self dismissModalViewControllerAnimated:YES];
}

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft || interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}
- (void) didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

	// Release any cached data, images, etc that aren't in use.
}
- (void) viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}
- (void) dealloc {
	[graph release];
	[super dealloc];
}

@end


text:
import {BaseError} from "./BaseError";

export class FileNotFoundError extends BaseError {
    constructor(public readonly fileName: string) {
        super(`File not found: ${fileName}`);
    }
}

redpajama_set_name: RedPajamaGithub


text:
layout: default
---

cvs2deluxtable

    Hello World! This is a test of the new documentation hosted on github pages.


text:
import Loader from "./loaders/JavaSyncStateLoader";
import Component from "./Component";
import Record from "./_Record";
import RecordSet from "./_RecordSet";

export {Loader, Component};


text:
//  HSHappyfoxGear
//
//Copyright (c) 2014 HelpStack (http://helpstack.io)
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.

package com.tenmiles.helpstack.gears;

import android.util.Base64;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.tenmiles.helpstack.logic.HSGear;
import com.tenmiles.helpstack.logic.OnFetchedArraySuccessListener;
import com.tenmiles.helpstack.logic.OnFetchedSuccessListener;
import com.tenmiles.helpstack.logic.OnNewTicketFetchedSuccessListener;
import com.tenmiles.helpstack.model.HSAttachment;
import com.tenmiles.helpstack.model.HSKBItem;
import com.tenmiles.helpstack.model.HSTicket;
import com.tenmiles.helpstack.model.HSTicketUpdate;
import com.tenmiles.helpstack.model.HSUploadAttachment;
import com.tenmiles.helpstack.model.HSUser;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.TimeZone;

public class HSHappyfoxGear extends HSGear {
	private static final String TAG = HSHappyfoxGear.class.getSimpleName();

	private String instanceUrl;
	private String api_key;
	private String auth_code;
	private String priority_id;
	private String category_id;
	private String section_id;

    // This are cached here so server call can be minimized and improve the speed of UI
    JSONArray allSectionsArray;

	public HSHappyfoxGear(String instanceUrl, String api_key, String auth_code, String category_id, String priority_id) {

		assert instanceUrl != null : "Instance Url cannot be null";
		assert api_key != null : "Api key cannot be null";
		assert auth_code != null : "Authcode cannot be null";
		assert category_id != null : "Category id cannot be null";
		assert priority_id != null : "Priority id cannot be null";

		if (!instanceUrl.endsWith("/"))
			instanceUrl = instanceUrl.concat("/");

		this.instanceUrl = instanceUrl;
		this.api_key = api_key;
		this.auth_code = auth_code;
		this.priority_id = priority_id;
		this.category_id = category_id;
	}

	// If user taps on a section, then section is send as a paremeter to the function
	@Override
	public void fetchKBArticle(String cancelTag, HSKBItem section, RequestQueue queue,
			OnFetchedArraySuccessListener success, ErrorListener errorListener) {

		if (section == null) {
			// This is first request of sections

			if (this.section_id == null) {
				// Fetch all sections
				String url = getApiUrl().concat("kb/sections/");

				JsonArrayRequest request = new JsonArrayRequest(url, new HappyfoxArrayBaseListener<JSONArray>(success, errorListener) {

					@Override
					public void onResponse(JSONArray sectionsArray) {
						HSKBItem[] array = getSectionsFromData(sectionsArray);
						successCallback.onSuccess(array);
					}
				}, errorListener);

				// to avoid server overload call
				request.setRetryPolicy(new DefaultRetryPolicy(TicketFormRequest.TIMEOUT_MS,
						TicketFormRequest.MAX_RETRIES, TicketFormRequest.BACKOFF_MULT));

				request.setTag(cancelTag);
				queue.add(request);
				queue.start();
			}
			else {
				// Fetch individual section
				String url = getApiUrl().concat("kb/section/").concat(this.section_id).concat("/");

				JsonObjectRequest request = new JsonObjectRequest(url, null, new HappyfoxArrayBaseListener<JSONObject>(success, errorListener) {

					@Override
					public void onResponse(JSONObject sectionsArray) {
						try {
							HSKBItem[] array = getArticlesFromSection(sectionsArray);
							successCallback.onSuccess(array);
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}, errorListener);

				// to avoid server overload call
				request.setRetryPolicy(new DefaultRetryPolicy(TicketFormRequest.TIMEOUT_MS,
						TicketFormRequest.MAX_RETRIES, TicketFormRequest.BACKOFF_MULT));

				request.setTag(cancelTag);
				queue.add(request);
				queue.start();
			}

		}
		else {
			// Actually it should go to server to get list of all sections, but we are saving it here to avoid server call.
			assert allSectionsArray!=null: "This gear was re-created and articles for section is lost.";

			int count  = allSectionsArray.length();
			for (int i = 0; i < count; i++) {
				try {
					JSONObject sectionObject = allSectionsArray.getJSONObject(i);
					String section_id = sectionObject.getString("id");

					if (section.getId().equals(section_id)) {
						HSKBItem[] array = getArticlesFromSection(sectionObject);
						success.onSuccess(array); // Work accomplished
						break;
					}

				} catch (JSONException e) {
					e.printStackTrace();
					errorListener.onErrorResponse(new VolleyError("parsing failed"));
				}
			}
		}

	}

	@Override
	public void registerNewUser(String cancelTag, String firstName, String lastname,
			String emailAddress, RequestQueue queue,OnFetchedSuccessListener success,
			ErrorListener error) {

		HSUser user = HSUser.createNewUserWithDetails(firstName, lastname, emailAddress);
		success.onSuccess(user);

	}

	@Override
	public void createNewTicket(String cancelTag, HSUser user, String message, String body, HSUploadAttachment[] attachments,  RequestQueue queue,
			OnNewTicketFetchedSuccessListener successListener,
			ErrorListener errorListener) {

		Properties prop = new Properties();
		prop.put("name", user.getFullName());
		prop.put("email", user.getEmail());
		prop.put("category", category_id);
		prop.put("priority", priority_id);
		prop.put("subject", message);
		prop.put("text", body);

		TicketFormRequest request = new TicketFormRequest(getApiUrl()+"new_ticket/", prop, attachments,  new CreateNewTicketSuccessListener(user, successListener, errorListener) {

			@Override
			public void onResponse(JSONObject response) {

				try {
					HSTicket ticket = HSTicket.createATicket(response.getString("id"), response.getString("subject"));
					HSUser user = HSUser.appendCredentialOnUserDetail(this.user,response.getJSONObject("user").getString("id"), null);
					this.successListener.onSuccess(user, ticket);
				} catch (JSONException e) {
					e.printStackTrace();
					this.errorListener.onErrorResponse(new VolleyError("Parsing failed when creating a ticket"));
				}

			}
		}, errorListener);

		request.addCredential(api_key, auth_code);
		request.setTag(cancelTag);

		queue.add(request);
		queue.start();
	}

	@Override
	public void fetchAllUpdateOnTicket(String cancelTag, HSTicket ticket, HSUser user, RequestQueue queue,
			OnFetchedArraySuccessListener success, ErrorListener errorListener) {

		TicketFormRequest request = new TicketFormRequest(getApiUrl() + "ticket/" + ticket.getTicketId(), new HappyfoxArrayBaseListener<JSONObject>(success, errorListener) {

			@Override
			public void onResponse(JSONObject response) {

				try {
					JSONArray updateArray = response.getJSONArray("updates");

					ArrayList<HSTicketUpdate> ticketUpdates = new ArrayList<HSTicketUpdate>();

					int updateLen = updateArray.length();
					for (int i = 0; i < updateLen; i++) {
						JSONObject updateObject = updateArray.getJSONObject(i);

						if (!updateObject.isNull("message")) {
							HSTicketUpdate update = parseTicketUpdateFromJson(updateObject);
							if (update != null) {
								ticketUpdates.add(update);
							}
						}
					}

					HSTicketUpdate[] array = new HSTicketUpdate[0];
					array = ticketUpdates.toArray(array);
					this.successCallback.onSuccess(array);
				} catch (JSONException e) {
					e.printStackTrace();
					this.errorListener.onErrorResponse(new VolleyError("Parsing failed when fetching all update for a ticket"));
				}

			}
		}, errorListener);

		request.addCredential(api_key, auth_code);
		request.setTag(cancelTag);

		queue.add(request);
		queue.start();
	}

	@Override
	public void addReplyOnATicket(String cancelTag, String message, HSUploadAttachment[] attachments,  HSTicket ticket, HSUser user,
			RequestQueue queue, OnFetchedSuccessListener success,
			ErrorListener errorListener) {

		Properties prop = new Properties();
		prop.put("user", user.getUserId());
		prop.put("text", message);

		TicketFormRequest request = new TicketFormRequest(
				getApiUrl()+"ticket/" + ticket.getTicketId() + "/user_reply/",
				prop,
				attachments,
				new HappyfoxBaseListner<JSONObject>(success, errorListener) {

					@Override
					public void onResponse(JSONObject response) {

						try {

							HSTicketUpdate update = null;
							// fetch last message from user in update array.
							JSONArray updateArray = response.getJSONArray("updates");

							int updateLen = updateArray.length();
							assert updateLen>0 : "No updates were returned by server";
							for (int i = updateLen - 1; i >= 0 ; i--) {
								JSONObject updateObject = updateArray.getJSONObject(i);
								JSONObject byObject = updateObject.getJSONObject("by");

								if (!byObject.getString("type").equals("user") && updateObject.isNull("message")) {
									continue;
								}

								update = parseTicketUpdateFromJson(updateObject);

								if (update == null) {
									continue;
								}

								break;
							}

							if (update == null) {
								this.errorListener.onErrorResponse(new VolleyError("Could not find user message in update"));
							}
							else {
								this.successCallback.onSuccess(update);
							}

						} catch (JSONException e) {
							e.printStackTrace();
							this.errorListener.onErrorResponse(new VolleyError("Parsing failed when adding reply to a ticket"));
						}

					}
				}, errorListener);

		request.addCredential(api_key, auth_code);
		request.setTag(cancelTag);

		queue.add(request);
		queue.start();

	}

    public void setSectionId(String sectionId) {
        this.section_id = sectionId;
    }

    private HSKBItem[] getArticlesFromSection(JSONObject sectionObject) throws JSONException {
        JSONArray articleArray = sectionObject.getJSONArray("articles");
        ArrayList<HSKBItem> kbArticleArray = new ArrayList<HSKBItem>();

        for (int j = 0; j < articleArray.length(); j++) {
            JSONObject arrayObject = articleArray.getJSONObject(j);
            HSKBItem item = HSKBItem.createForArticle(arrayObject.getString("id"), arrayObject.getString("title").trim(), arrayObject.getString("contents"));
            kbArticleArray.add(item);
        }

        HSKBItem[] array = new HSKBItem[0];
        array = kbArticleArray.toArray(array);
        return array;
    }

    private HSKBItem[] getSectionsFromData(JSONArray sectionsArray) {
        allSectionsArray = sectionsArray;
        ArrayList<HSKBItem> kbSectionArray = new ArrayList<HSKBItem>();

        int count  = sectionsArray.length();
        for (int i = 0; i < count; i++) {
            try {
                JSONObject sectionObject = sectionsArray.getJSONObject(i);
                if (sectionObject.getJSONArray("articles").length() > 0) {
                    HSKBItem item = HSKBItem.createForSection(sectionObject.getString("id"), sectionObject.getString("name"));
                    kbSectionArray.add(item);
                }

            } catch (JSONException e) {
                e.printStackTrace();
                new VolleyError("parsing failed");
            }
        }

        HSKBItem[] array = new HSKBItem[0];
        array = kbSectionArray.toArray(array);
        return array;
    }

    /**
     *
     * @param updateObject, can be null if it is private note
     * @return
     * @throws JSONException
     */
	private HSTicketUpdate parseTicketUpdateFromJson(JSONObject updateObject) throws JSONException {
		String updateId = null;
		String userName = null;

		if (updateObject.isNull("message")) {
			return null;
		}

		JSONObject messageObject = updateObject.getJSONObject("message");

		// private note
		if (!messageObject.isNull("message_type") && messageObject.getString("message_type").equals("p")) {
			return null;
		}

		JSONObject byObject = updateObject.getJSONObject("by");
		if (!byObject.isNull("name")) {
			userName = updateObject.getJSONObject("by").getString("name");
		}
		String message = updateObject.getJSONObject("message").getString("text");

		Date update_time = null;
		if (!updateObject.isNull("timestamp")) {
			update_time = parseTime(updateObject.getString("timestamp"));
		}

		JSONArray attachmentObjects = updateObject.getJSONObject("message").getJSONArray("attachments");
		HSAttachment[] attachments = null;
		if(attachmentObjects != null) {
			int length = attachmentObjects.length();
			ArrayList<HSAttachment> attachmentArray = new ArrayList<HSAttachment>();
			for(int i = 0; i < length; i++) {
				JSONObject attachmentData = attachmentObjects.getJSONObject(i);
				String attachment_url = attachmentData.getString("url");
				if (attachment_url.startsWith("/")) {
					attachment_url = instanceUrl.concat(attachment_url.substring(1));
				}
				HSAttachment attachData = HSAttachment.createAttachment(attachment_url, attachmentData.getString("filename"), null);
				attachmentArray.add(attachData);
			}
			attachments = attachmentArray.toArray(new HSAttachment[length]);
		}

		if (byObject.getString("type").equals("user")) {
			return HSTicketUpdate.createUpdateByUser(updateId, userName, message, update_time, attachments);
		}
		else {
			return HSTicketUpdate.createUpdateByStaff(updateId, userName, message, update_time, attachments);
		}
	}

	public String getApiUrl() {
		return this.instanceUrl+"api/1.1/json/";
	}

	protected static Date parseTime(String dateString) {
		Date givenTimeDate = null;
		try {
			givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd HH:mm:ss");
		} catch (ParseException e) {
			try {
				givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd");
			} catch (ParseException e1) {
				try {
					givenTimeDate = parseUTCString(dateString,"yyyy-MM-dd HH:mm:ss.SSSSZ");
				} catch (ParseException e2) {
					e2.printStackTrace();
				}
			}
		}
		return givenTimeDate;
	}

	private static Date parseUTCString(String timeStr, String pattern) throws ParseException {
		SimpleDateFormat format = new SimpleDateFormat(pattern, Locale.getDefault());
		format.setTimeZone(TimeZone.getTimeZone("UTC"));
		return format.parse(timeStr);
	}

	private abstract class HappyfoxArrayBaseListener<T> implements Listener<T> {

		protected OnFetchedArraySuccessListener successCallback;
		protected ErrorListener errorListener;

		public HappyfoxArrayBaseListener(OnFetchedArraySuccessListener success,
                                         ErrorListener errorListener) {
			this.successCallback = success;
			this.errorListener = errorListener;
		}

	}

	private abstract class HappyfoxBaseListner<T> implements Listener<T> {

		protected OnFetchedSuccessListener successCallback;
		protected ErrorListener errorListener;

		public HappyfoxBaseListner(OnFetchedSuccessListener success,
				ErrorListener errorListener) {
			this.successCallback = success;
			this.errorListener = errorListener;
		}

	}

	private abstract class CreateNewTicketSuccessListener implements Listener<JSONObject>
	{

		protected HSUser user;
		protected OnNewTicketFetchedSuccessListener successListener;
		protected ErrorListener errorListener;

		public CreateNewTicketSuccessListener(HSUser user, OnNewTicketFetchedSuccessListener successListener,
				ErrorListener errorListener) {
			this.user = user;
			this.successListener = successListener;
			this.errorListener = errorListener;
		}
	}

	private class TicketFormRequest extends Request<JSONObject> {

		/** Socket timeout in milliseconds for image requests */
		protected static final int TIMEOUT_MS = 10000;

		/** Default number of retries for image requests */
		protected static final int MAX_RETRIES = 0;

		/** Default backoff multiplier for image requests */
		protected static final float BACKOFF_MULT = 1f;

		private Listener<JSONObject> mListener;

		private MultipartEntity entity;

		HashMap<String, String> headers = new HashMap<String, String>();

		public TicketFormRequest(String url, Properties requestProperties, HSUploadAttachment[] attachments_to_upload, Listener<JSONObject> listener,
                                 ErrorListener errorListener) {
			super(Method.POST, url, errorListener);
			mListener = listener;

			setRetryPolicy(
					new DefaultRetryPolicy(TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULT));

			entity = new MultipartEntity();

			// iter properties
			Enumeration<Object> enumKey = requestProperties.keys();
			while(enumKey.hasMoreElements()) {
				String key = (String) enumKey.nextElement();
				String val = requestProperties.getProperty(key);
				try {
					entity.addPart(key, new StringBody(val));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}

			// Adding attachments if any
			if (attachments_to_upload != null) {
				for (int i = 0; i < attachments_to_upload.length; i++) {
					try {
						entity.addPart("attachments", attachments_to_upload[i].generateStreamToUpload());
					} catch (FileNotFoundException e) {
						Log.e(TAG, "Attachment upload failed");
						e.printStackTrace();
					}
				}
			}

		}

		public TicketFormRequest(String url, Listener<JSONObject> listener,
                                 ErrorListener errorListener) {
			super(Method.GET, url, errorListener);
			mListener = listener;
			setRetryPolicy(
					new DefaultRetryPolicy(TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULT));
		}

		@Override
		public String getBodyContentType()
		{
			if (entity == null) {
				return super.getBodyContentType();
			}
			return entity.getContentType().getValue();
		}

		@Override
		public byte[] getBody() throws AuthFailureError
		{
			if (entity == null) {
				return super.getBody();
			}
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			try
			{
				entity.writeTo(bos);
			}
			catch (IOException e)
			{
				VolleyLog.e("IOException writing to ByteArrayOutputStream");
			}
			return bos.toByteArray();
		}

		@Override
		protected void deliverResponse(JSONObject response) {
			mListener.onResponse(response);
		}

		@Override
		protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
			try {
				String jsonString =
						new String(response.data, HttpHeaderParser.parseCharset(response.headers));
				return Response.success(new JSONObject(jsonString),
						HttpHeaderParser.parseCacheHeaders(response));
			} catch (UnsupportedEncodingException e) {
				return Response.error(new ParseError(e));
			} catch (JSONException je) {
				return Response.error(new ParseError(je));
			}
		}

		@Override
		public Map<String, String> getHeaders() throws AuthFailureError {
			return headers;
		}

		public void addCredential(String name, String password) {
			String credentials = name + ":" + password;
			String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
			headers.put("Authorization", "Basic "+base64EncodedCredentials);
		}
	}

}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Ardisia tuerckheimii Donn.Sm.

### Remarks
null


text:
// Copyright(C) 1999-2017 National Technology & Engineering Solutions
// of Sandia, LLC (NTESS).  Under the terms of Contract DE-NA0003525 with
// NTESS, the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials provided
//       with the distribution.
//
//     * Neither the name of NTESS nor the names of its
//       contributors may be used to endorse or promote products derived
//       from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

#include "Ioss_CodeTypes.h"           // for IntVector
#include "Ioss_ElementTopology.h"     // for ElementTopology
#include <Ioss_ElementVariableType.h> // for ElementVariableType
#include <Ioss_ShellLine2D2.h>
#include <cassert> // for assert
#include <cstddef> // for nullptr

//------------------------------------------------------------------------
// Define a variable type for storage of this elements connectivity
namespace Ioss {
  class St_ShellLine2D2 : public ElementVariableType
  {
  public:
    static void factory() { static St_ShellLine2D2 registerThis; }

  protected:
    St_ShellLine2D2() : ElementVariableType(Ioss::ShellLine2D2::name, 2) {}
  };
} // namespace Ioss
// ========================================================================
namespace {
  struct Constants
  {
    static const int nnode     = 2;
    static const int nedge     = 2;
    static const int nedgenode = 2;
    static const int nface     = 0;
    static const int nfacenode = 0;
    static const int nfaceedge = 0;
  };
} // namespace

void Ioss::ShellLine2D2::factory()
{
  static Ioss::ShellLine2D2 registerThis;
  Ioss::St_ShellLine2D2::factory();
}

Ioss::ShellLine2D2::ShellLine2D2() : Ioss::ElementTopology(Ioss::ShellLine2D2::name, "ShellLine_2")
{
  Ioss::ElementTopology::alias(Ioss::ShellLine2D2::name, "Shell_Line_2_2D");
  Ioss::ElementTopology::alias(Ioss::ShellLine2D2::name, "SHELL_LINE_2");
}

Ioss::ShellLine2D2::~ShellLine2D2() = default;

int Ioss::ShellLine2D2::parametric_dimension() const { return 1; }
int Ioss::ShellLine2D2::spatial_dimension() const { return 2; }
int Ioss::ShellLine2D2::order() const { return 1; }

int Ioss::ShellLine2D2::number_corner_nodes() const { return 2; }
int Ioss::ShellLine2D2::number_nodes() const { return Constants::nnode; }
int Ioss::ShellLine2D2::number_edges() const { return Constants::nedge; }
int Ioss::ShellLine2D2::number_faces() const { return Constants::nface; }

int Ioss::ShellLine2D2::number_nodes_edge(int /* edge */) const { return Constants::nedgenode; }

int Ioss::ShellLine2D2::number_nodes_face(int face) const
{
  // face is 1-based.  0 passed in for all faces.
  assert(face >= 0 && face <= number_faces());
  return Constants::nfacenode;
}

int Ioss::ShellLine2D2::number_edges_face(int face) const
{
  // face is 1-based.  0 passed in for all faces.
  assert(face >= 0 && face <= number_faces());
  return Constants::nfaceedge;
}

Ioss::IntVector Ioss::ShellLine2D2::edge_connectivity(int edge_number) const
{
  Ioss::IntVector connectivity(Constants::nedgenode);
  if (edge_number == 1) {
    connectivity[0] = 0;
    connectivity[1] = 1;
  }
  else {
    connectivity[0] = 1;
    connectivity[1] = 0;
  }
  return connectivity;
}

Ioss::IntVector Ioss::ShellLine2D2::face_connectivity(int /* face_number */) const
{
  Ioss::IntVector connectivity;
  return connectivity;
}

Ioss::IntVector Ioss::ShellLine2D2::element_connectivity() const
{
  Ioss::IntVector connectivity(number_nodes());
  for (int i = 0; i < number_nodes(); i++) {
    connectivity[i] = i;
  }
  return connectivity;
}

Ioss::ElementTopology *Ioss::ShellLine2D2::face_type(int /* face_number */) const
{
  return (Ioss::ElementTopology *)nullptr;
}

Ioss::ElementTopology *Ioss::ShellLine2D2::edge_type(int /* edge_number */) const
{
  return Ioss::ElementTopology::factory("edge2");
}


text:
package net.joelinn.stripe.request.customers;

/**
 * User: Joe Linn
 * Date: 5/22/2014
 * Time: 11:41 AM
 */
public class UpdateCustomerRequest extends AbstractCustomerRequest<UpdateCustomerRequest>{
    protected String defaultCard;

    public String getDefaultCard() {
        return defaultCard;
    }

    public void setDefaultCard(String defaultCard) {
        this.defaultCard = defaultCard;
    }
}


text:
@implementation FMDatabase (FMDBHelpers)

// ========== INITIALIZATION ===========================================================================================
#pragma mark - Initialization

+ (instancetype)temporaryDatabase
{
  return [self databaseWithPath:@""];
}

+ (instancetype)inMemoryDatabase
{
  return [self databaseWithPath:nil];
}

// ========== OPEN =====================================================================================================
#pragma mark - Open

- (BOOL)open:(NSError **)error_p
{
  BOOL opened = [self open];
  if (NO == opened && error_p != NULL)
  {
    *error_p = self.lastError;
  }
  return opened;
}

- (BOOL)openWithFlags:(int)flags
                error:(NSError **)error_p
{
  BOOL opened = [self openWithFlags:flags];
  if (NO == opened && error_p != NULL)
  {
    *error_p = self.lastError;
  }
  return opened;
}

// ========== ESCAPE ===================================================================================================
#pragma mark - Escape

+ (NSString *)escapeString:(NSString *)value
{
  value = [value stringByReplacingOccurrencesOfString:@"'"
                                           withString:@"''"];

  return [NSString stringWithFormat:@"'%@'", value];
}

+ (NSString *)escapeIdentifier:(NSString *)value
{
  value = [value stringByReplacingOccurrencesOfString:@"\""
                                           withString:@"\"\""];

  return [NSString stringWithFormat:@"\"%@\"", value];

}

+ (NSString *)escapeValue:(id)value
{
  if (value == nil || value == [NSNull null])
  {
    return @"NULL";
  }
  else if ([value isKindOfClass:[NSString class]])
  {
    return [self escapeString:value];
  }
  else if ([value respondsToSelector:@selector(stringValue)])
  {
    return [self escapeString:[value stringValue]];
  }
  else
  {
    return [self escapeString:[value description]];
  }
}

+ (NSString *)listOfColumns:(NSArray *)columnNames
{
  if (columnNames != nil)
  {
    return [columnNames componentsJoinedByString:@","];
  }
  else
  {
    return @"*";
  }
}

// ========== UPDATES ==================================================================================================
#pragma mark - Updates

- (BOOL)executeUpdate:(NSString *)sql
                error:(NSError **)error_p
{
  return [self executeUpdate:sql
        withArgumentsInArray:@[]
                       error:error_p];
}

- (BOOL)executeUpdate:(NSString *)sql
 withArgumentsInArray:(NSArray *)arguments
                error:(NSError **)error_p
{
#if DEBUG
  if (getenv("DEBUG_SQL"))
  {
    NSLog(@"executeUpdate: %@\n%@", sql, arguments);
  }
#endif

  BOOL successful = [self executeUpdate:sql
                   withArgumentsInArray:arguments];
  if (NO == successful && error_p != NULL)
  {
    *error_p = self.lastError;
  }
  return successful;
}

- (BOOL)  executeUpdate:(NSString *)sql
withParameterDictionary:(NSDictionary *)arguments
                  error:(NSError **)error_p
{
#if DEBUG
  if (getenv("DEBUG_SQL"))
  {
    NSLog(@"executeUpdate: %@\n%@", sql, arguments);
  }
#endif

  BOOL successful = [self executeUpdate:sql
                withParameterDictionary:arguments];
  if (NO == successful && error_p != NULL)
  {
    *error_p = self.lastError;
  }
  return successful;
}

// ========== SCHEMA ===================================================================================================
#pragma mark - Schema

- (NSDictionary *)databaseSchema
{
  NSMutableDictionary * tableSchemas = [[NSMutableDictionary alloc] init];
  for (NSString * tableName in self.tableNames)
  {
    NSDictionary * tableSchema = [self tableSchema:tableName];
    if (tableSchema != nil)
    {
      tableSchemas[tableName] = tableSchema;
    }
  }

  return tableSchemas;
}

- (NSDictionary *)tableSchema:(NSString *)tableName
{
  NSMutableDictionary * tableSchema = [[NSMutableDictionary alloc] init];
  FMResultSet * resultSet = [self getTableSchema:tableName];
  while ([resultSet next])
  {
    NSMutableDictionary * columnInfo = [[NSMutableDictionary alloc] init];
    for (int columnIndex = 0; columnIndex < [resultSet columnCount]; columnIndex++)
    {
      NSString * name = [resultSet columnNameForIndex:columnIndex];
      columnInfo[name] = resultSet[columnIndex];
    }
    tableSchema[columnInfo[@"name"]] = columnInfo;
  }

  return tableSchema;
}

- (NSSet *)tableNames
{
  FMResultSet * schema = [self getSchema];
  NSMutableSet * tableNames = [[NSMutableSet alloc] init];
  while ([schema next])
  {
    NSString * type = [schema stringForColumn:@"type"];
    if ([type isEqualToString:@"table"])
    {
      [tableNames addObject:[schema stringForColumn:@"name"]];
    }
  }
  return tableNames;
}

- (NSSet *)indexNamesOnTable:(NSString *)tableName
{
  FMResultSet * schema = [self getSchema];
  NSMutableSet * indexNames = [[NSMutableSet alloc] init];
  while ([schema next])
  {
    NSString * type = [schema stringForColumn:@"type"];
    NSString * indexTableName = [schema stringForColumn:@"tbl_name"];
    if ([type isEqualToString:@"index"]
        && [indexTableName isEqualToString:tableName])
    {
      [indexNames addObject:[schema stringForColumn:@"name"]];
    }
  }
  return indexNames;
}

// ========== TABLES ===================================================================================================
#pragma mark - Tables

- (BOOL)createTableWithName:(NSString *)tableName
                    columns:(NSArray *)columns
                constraints:(NSArray *)constraints
                      error:(NSError **)error_p
{
  NSMutableArray * createTable = [[NSMutableArray alloc] init];

  [createTable addObject:@"CREATE TABLE"];

  [createTable addObject:[FMDatabase escapeIdentifier:tableName]];
  [createTable addObject:@"("];

  BOOL isFirstColumn = YES;
  for (id columnDef in columns)
  {
    if (isFirstColumn == NO)
    {
      [createTable addObject:@","];
    }

    if ([columnDef isKindOfClass:[NSArray class]])
    {
      for (NSString * component in columnDef)
      {
        [createTable addObject:component];
      }
    }
    else if ([columnDef isKindOfClass:[NSString class]])
    {
      [createTable addObject:columnDef];
    }
    else
    {
      @throw [NSException exceptionWithName:NSInvalidArgumentException
                                     reason:[NSString stringWithFormat:@"Invalid column definition (%@): %@",
                                             NSStringFromClass([columnDef class]),
                                             columnDef]
                                   userInfo:nil];
    }

    isFirstColumn = NO;
  }

  // constraints
  for (NSString * constraint in constraints)
  {
    [createTable addObject:@","];
    [createTable addObject:constraint];
  }

  [createTable addObject:@")"];

  return [self executeUpdate:[createTable componentsJoinedByString:@" "]
                       error:error_p];
}

- (BOOL)renameTable:(NSString *)tableName
                 to:(NSString *)newTableName
              error:(NSError **)error_p
{
  NSMutableArray * renameTable = [[NSMutableArray alloc] init];
  [renameTable addObject:@"ALTER TABLE"];
  [renameTable addObject:[FMDatabase escapeIdentifier:tableName]];
  [renameTable addObject:@"RENAME TO"];
  [renameTable addObject:[FMDatabase escapeIdentifier:newTableName]];

  return [self executeUpdate:[renameTable componentsJoinedByString:@" "]
                       error:error_p];
}

- (BOOL)addColumn:(NSString *)columnDefinition
          toTable:(NSString *)tableName
            error:(NSError **)error_p
{
  NSMutableArray * addColumn = [[NSMutableArray alloc] init];
  [addColumn addObject:@"ALTER TABLE"];
  [addColumn addObject:[FMDatabase escapeIdentifier:tableName]];
  [addColumn addObject:@"ADD COLUMN"];
  [addColumn addObject:columnDefinition];

  return [self executeUpdate:[addColumn componentsJoinedByString:@" "]
                       error:error_p];
}

- (BOOL)dropTableWithName:(NSString *)tableName
                    error:(NSError **)error_p
{
  return [self dropTableWithName:tableName
                        ifExists:NO
                           error:error_p];
}

- (BOOL)dropTableIfExistsWithName:(NSString *)tableName
                            error:(NSError **)error_p
{
  return [self dropTableWithName:tableName
                        ifExists:YES
                           error:error_p];
}

- (BOOL)dropTableWithName:(NSString *)tableName
                 ifExists:(BOOL)ifExists
                    error:(NSError **)error_p
{
  NSMutableArray * dropTable = [[NSMutableArray alloc] init];

  [dropTable addObject:@"DROP TABLE"];
  if (ifExists)
  {
    [dropTable addObject:@"IF EXISTS"];
  }

  [dropTable addObject:[FMDatabase escapeIdentifier:tableName]];

  return [self executeUpdate:[dropTable componentsJoinedByString:@" "]
                       error:error_p];
}

// ========== INDEXES ==================================================================================================
#pragma mark - Indexes

- (BOOL)createIndexWithName:(NSString *)indexName
                  tableName:(NSString *)tableName
                    columns:(NSArray *)columns
                      error:(NSError **)error_p
{
  return [self createIndexWithName:indexName
                         tableName:tableName
                           columns:columns
                            unique:NO
                             error:error_p];
}

- (BOOL)createUniqueIndexWithName:(NSString *)indexName
                        tableName:(NSString *)tableName
                          columns:(NSArray *)columns
                            error:(NSError **)error_p
{
  return [self createIndexWithName:indexName
                         tableName:tableName
                           columns:columns
                            unique:YES
                             error:error_p];
}

- (BOOL)createIndexWithName:(NSString *)indexName
                  tableName:(NSString *)tableName
                    columns:(NSArray *)columns
                     unique:(BOOL)isUnique
                      error:(NSError **)error_p
{
  NSMutableArray *createIndex = [NSMutableArray arrayWithObject:@"CREATE"];

  if (isUnique) [createIndex addObject:@"UNIQUE"];
  [createIndex addObject:@"INDEX"];
  [createIndex addObject:[FMDatabase escapeIdentifier:indexName]];
  [createIndex addObject:@"ON"];
  [createIndex addObject:[FMDatabase escapeIdentifier:tableName]];

  [createIndex addObject:@"("];
  [createIndex addObject:[columns componentsJoinedByString:@", "]];
  [createIndex addObject:@")"];

  return [self executeUpdate:[createIndex componentsJoinedByString:@" "]
                       error:error_p];
}

- (BOOL)dropIndexWithName:(NSString *)indexName
                    error:(NSError **)error_p
{
  NSMutableArray * dropIndex = [[NSMutableArray alloc] init];
  [dropIndex addObject:@"DROP INDEX"];
  [dropIndex addObject:[FMDatabase escapeIdentifier:indexName]];

  return [self executeUpdate:[dropIndex componentsJoinedByString:@" "]
                       error:error_p];
}

// ========== INSERT ===================================================================================================
#pragma mark - Insert

+ (NSString *)argumentTupleOfSize:(NSUInteger)tupleSize
{
  NSMutableArray * tupleString = [[NSMutableArray alloc] init];
  [tupleString addObject:@"("];
  for (NSUInteger columnIdx = 0; columnIdx < tupleSize; columnIdx++)
  {
    if (columnIdx > 0)
    {
      [tupleString addObject:@","];
    }
    [tupleString addObject:@"?"];
  }
  [tupleString addObject:@")"];

  return [tupleString componentsJoinedByString:@" "];
}

- (BOOL)insertInto:(NSString *)tableName
           columns:(NSArray *)columnNames
            values:(NSArray *)values
             error:(NSError **)error_p
{
  NSParameterAssert(columnNames != nil);
  NSParameterAssert(columnNames.count > 0);
  NSParameterAssert(tableName != nil);

  NSMutableArray * insertSQL = [[NSMutableArray alloc] init];

  [insertSQL addObject:@"INSERT INTO"];
  [insertSQL addObject:tableName];

  if (columnNames.count > 0) {
    [insertSQL addObject:@"("];

    [columnNames enumerateObjectsUsingBlock:^(NSString * columnName, NSUInteger idx, BOOL *stop) {
      if (idx > 0)
      {
        [insertSQL addObject:@","];
      }

      [insertSQL addObject:[FMDatabase escapeIdentifier:columnName]];
    }];

    [insertSQL addObject:@")"];
  }

  NSMutableArray * flattenedValues = [[NSMutableArray alloc] initWithCapacity:(columnNames.count * values.count)];
  if (values.count == 0)
  {
    [insertSQL addObject:@"DEFAULT VALUES"];
  }
  else
  {
    [insertSQL addObject:@"VALUES"];

    NSString * argumentTuple = [FMDatabase argumentTupleOfSize:columnNames.count];

    [values enumerateObjectsUsingBlock:^(NSArray * row, NSUInteger rowIdx, BOOL *stop) {

      NSParameterAssert(row.count == columnNames.count);
      if (rowIdx > 0)
      {
        [insertSQL addObject:@","];
      }

      [insertSQL addObject:argumentTuple];
      [flattenedValues addObjectsFromArray:row];
    }];
  }

  return [self executeUpdate:[insertSQL componentsJoinedByString:@" "]
        withArgumentsInArray:flattenedValues
                       error:error_p];
}

- (NSNumber *)insertInto:(NSString *)tableName
                     row:(NSDictionary *)rowValues
                   error:(NSError **)error_p
{
  NSArray * columns = rowValues.allKeys;
  NSMutableArray * values = [[NSMutableArray alloc] init];
  for (NSString * column in columns)
  {
    id value = rowValues[column];
    [values addObject:value];
  }

  BOOL inserted = [self insertInto:tableName
                           columns:columns
                            values:@[ values ]
                             error:error_p];
  if (!inserted)
  {
    return 0;
  }

  return @(self.lastInsertRowId);
}

// ========== COUNT ====================================================================================================
#pragma mark - Count

+ (NSString *)statementToCount:(NSArray *)columnNames
                          from:(NSString *)from
                         where:(NSString *)where
{
  NSMutableString * countColumn = [[NSMutableString alloc] init];
  [countColumn appendString:@"count("];
  [countColumn appendString:[FMDatabase listOfColumns:columnNames]];
  [countColumn appendString:@")"];

  return [self statementToSelect:@[ countColumn ]
                            from:from
                           where:where
                         groupBy:nil
                          having:nil
                         orderBy:nil
                           limit:nil
                          offset:nil];
}

- (NSInteger)countFrom:(NSString *)from
                 error:(NSError **)error_p
{
  return [self count:nil
                from:from
               where:nil
           arguments:nil
               error:error_p];
}

- (NSInteger)countFrom:(NSString *)from
        matchingValues:(NSDictionary *)valuesToMatch
                 error:(NSError **)error_p
{
  return [self count:nil
                from:from
      matchingValues:valuesToMatch
               error:error_p];
}

- (NSInteger)count:(NSArray *)columnNames
              from:(NSString *)from
    matchingValues:(NSDictionary *)valuesToMatch
             error:(NSError **)error_p
{
  NSArray * arguments = nil;
  NSString * where = [FMDatabase whereClauseToMatchValues:valuesToMatch
                                                arguments:&arguments];

  return [self count:columnNames
                from:from
               where:where
           arguments:arguments
               error:error_p];
}

- (NSInteger)count:(NSArray *)columnNames
              from:(NSString *)from
             where:(NSString *)where
         arguments:(NSArray *)arguments
             error:(NSError **)error_p
{
  NSString * countSQL = [FMDatabase statementToCount:columnNames
                                                from:from
                                               where:where];

  FMResultSet * results = [self executeQuery:countSQL
                        withArgumentsInArray:arguments];
  if (results == nil)
  {
    return -1;
  }
  else if ([results next])
  {
    if (sizeof(NSInteger) == sizeof(long))
    {
        long count = [results longForColumnIndex:0];
        [results close];
        return count;
    }
    else
    {
        int count = [results intForColumnIndex:0];
        [results close];
        return count;
    }
  }
  else
  {
    return 0;
  }
}

// ========== SELECT ===================================================================================================
#pragma mark - Select

- (NSArray *)selectAllFrom:(NSString *)tableName
                   orderBy:(NSString *)orderBy
                     error:(NSError **)error_p
{
  return [self selectResults:nil
                        from:tableName
                       where:nil
                     groupBy:nil
                      having:nil
                   arguments:nil
                     orderBy:orderBy
                       limit:nil
                      offset:nil
                       error:error_p].allRecords;
}

- (NSArray *)selectAllFrom:(NSString *)from
                     where:(NSString *)where
                 arguments:(NSArray *)arguments
                   orderBy:(NSString *)orderBy
                     error:(NSError **)error_p
{
  return [self selectResults:nil
                        from:from
                       where:where
                     groupBy:nil
                      having:nil
                   arguments:arguments
                     orderBy:orderBy
                       limit:nil
                      offset:nil
                       error:error_p].allRecords;
}

// ---------- RESULTS --------------------------------------------------------------------------------------------------
#pragma mark Results

+ (NSString *)whereClauseToMatchValues:(NSDictionary *)valuesToMatch
                             arguments:(NSArray **)arguments_p
{
  if (valuesToMatch.count == 0)
  {
    if (arguments_p) *arguments_p = @[];
    return @"1";
  }

  NSMutableArray * where = [[NSMutableArray alloc] init];
  NSMutableArray * arguments  = [[NSMutableArray alloc] initWithCapacity:valuesToMatch.count];
  [valuesToMatch enumerateKeysAndObjectsUsingBlock:^(NSString * columnName, id value, BOOL *stop) {

    if (where.count > 0)
    {
      [where addObject:@"AND"];
    }

    [where addObject:[FMDatabase escapeIdentifier:columnName]];

    if (value == [NSNull null])
    {
      [where addObject:@"IS NULL"];
    }
    else if ([value isKindOfClass:[NSArray class]])
    {
      [where addObject:@"IN ("];

      BOOL isFirst = YES;
      for (id arg in value)
      {
        if (!isFirst) {
          [where addObject:@","];
        }
        [where addObject:@"?"];
        isFirst = NO;

        [arguments addObject:arg];
      }

      [where addObject:@")"];
    }
    else
    {
      [where addObject:@"= ?"];
      [arguments addObject:value];
    }
  }];

  if (arguments_p != NULL)
  {
    *arguments_p = arguments;
  }

  return [where componentsJoinedByString:@" "];
}

+ (NSString *)statementToSelect:(NSArray *)columnNames
                           from:(NSString *)from
                          where:(NSString *)where
                        groupBy:(NSString *)groupBy
                         having:(NSString *)having
                        orderBy:(NSString *)orderBy
                          limit:(NSNumber *)limit
                         offset:(NSNumber *)offset
{
  NSMutableArray * selectSQL = [[NSMutableArray alloc] init];
  [selectSQL addObject:@"SELECT"];
  [selectSQL addObject:[FMDatabase listOfColumns:columnNames]];
  [selectSQL addObject:@"FROM"];
  [selectSQL addObject:from];

  if (where.length > 0)
  {
    [selectSQL addObject:@"WHERE"];
    [selectSQL addObject:where];
  }

  if ([groupBy length] > 0)
  {
    [selectSQL addObject:@"GROUP BY"];
    [selectSQL addObject:groupBy];

    if ([having length] > 0)
    {
      [selectSQL addObject:@"HAVING"];
      [selectSQL addObject:having];
    }
  }

  if ([orderBy length] > 0)
  {
    [selectSQL addObject:@"ORDER BY"];
    [selectSQL addObject:orderBy];
  }

  if (limit != nil)
  {
    [selectSQL addObject:@"LIMIT"];
    [selectSQL addObject:limit.stringValue];

    if (offset != nil)
    {
      [selectSQL addObject:@"OFFSET"];
      [selectSQL addObject:offset.stringValue];
    }
  }

  return [selectSQL componentsJoinedByString:@" "];
}

- (FMResultSet *)selectResultsFrom:(NSString *)tableName
                           orderBy:(NSString *)orderBy
                             error:(NSError **)error_p
{
  return [self selectResults:nil
                        from:tableName
                       where:nil
                     groupBy:nil
                      having:nil
                   arguments:nil
                     orderBy:orderBy
                       limit:nil
                      offset:nil
                       error:error_p];
}

- (FMResultSet *)selectResultsFrom:(NSString *)from
                    matchingValues:(NSDictionary *)valuesToMatch
                           orderBy:(NSString *)orderBy
                             error:(NSError **)error_p
{
  return [self selectResults:nil
                        from:from
              matchingValues:valuesToMatch
                     orderBy:orderBy
                       limit:nil
                      offset:nil
                       error:error_p];
}

- (FMResultSet *)selectResults:(NSArray *)columnNames
                          from:(NSString *)from
                matchingValues:(NSDictionary *)valuesToMatch
                       orderBy:(NSString *)orderBy
                         limit:(NSNumber *)limit
                        offset:(NSNumber *)offset
                         error:(NSError **)error_p
{
  NSArray * arguments = nil;
  NSString * where = [FMDatabase whereClauseToMatchValues:valuesToMatch
                                                arguments:&arguments];

  return [self selectResults:columnNames
                        from:from
                       where:where
                     groupBy:nil
                      having:nil
                   arguments:arguments
                     orderBy:orderBy
                       limit:limit
                      offset:offset
                       error:error_p];
}

- (FMResultSet *)selectResultsFrom:(NSString *)tableName
                             where:(NSString *)conditions
                         arguments:(NSArray *)arguments
                           orderBy:(NSString *)orderBy
                             error:(NSError **)error_p
{
  return [self selectResults:nil
                        from:tableName
                       where:conditions
                     groupBy:nil
                      having:nil
                   arguments:arguments
                     orderBy:orderBy
                       limit:nil
                      offset:nil
                       error:error_p];
}

- (FMResultSet *)selectResults:(NSArray *)columnNames
                          from:(NSString *)from
                         where:(NSString *)where
                       groupBy:(NSString *)groupBy
                        having:(NSString *)having
                     arguments:(NSArray *)arguments
                       orderBy:(NSString *)orderBy
                         limit:(NSNumber *)limit
                        offset:(NSNumber *)offset
                         error:(NSError **)error_p
{
  NSString * selectSQL = [FMDatabase statementToSelect:columnNames
                                                  from:from
                                                 where:where
                                               groupBy:groupBy
                                                having:having
                                               orderBy:orderBy
                                                 limit:limit
                                                offset:offset];

  FMResultSet * results = [self executeQuery:selectSQL
                        withArgumentsInArray:arguments];
  if (results == nil && error_p != NULL)
  {
    *error_p = self.lastError;
  }
  return results;
}

// ========== UPDATE ===================================================================================================
#pragma mark - Update

- (NSInteger)update:(NSString *)tableName
             values:(NSDictionary *)values
     matchingValues:(NSDictionary *)matchingValues
              error:(NSError **)error_p
{
  NSArray * arguments = nil;
  NSString * where = [FMDatabase whereClauseToMatchValues:matchingValues
                                                arguments:&arguments];
  return [self update:tableName
               values:values
                where:where
            arguments:arguments
                error:error_p];
}

- (NSInteger)update:(NSString *)tableName
             values:(NSDictionary *)values
              where:(NSString *)where
          arguments:(NSArray *)whereArguments
              error:(NSError **)error_p
{
  NSMutableArray * allArguments = [[NSMutableArray alloc] initWithCapacity:(values.count + whereArguments.count)];
  NSMutableArray * columnNames = [[NSMutableArray alloc] init];
  NSMutableArray * expressions = [[NSMutableArray alloc] init];

  [values enumerateKeysAndObjectsUsingBlock:^(NSString * columnName, id obj, BOOL *stop) {
    [columnNames addObject:columnName];
    [expressions addObject:@"?"];
    [allArguments addObject:obj];
  }];

  if (whereArguments.count > 0)
  {
    [allArguments addObjectsFromArray:whereArguments];
  }

  return [self update:tableName
              columns:columnNames
          expressions:expressions
                where:where
            arguments:allArguments
                error:error_p];
}

- (NSInteger)update:(NSString *)tableName
            columns:(NSArray *)columnNames
        expressions:(NSArray *)expressions
              where:(NSString *)where
          arguments:(NSArray *)arguments
              error:(NSError **)error_p
{
  NSParameterAssert(columnNames.count > 0);
  NSParameterAssert(expressions.count == columnNames.count);

  NSMutableArray * updateSQL = [[NSMutableArray alloc] init];
  [updateSQL addObject:@"UPDATE"];
  [updateSQL addObject:[FMDatabase escapeIdentifier:tableName]];
  [updateSQL addObject:@"SET"];

  [columnNames enumerateObjectsUsingBlock:^(NSString * columnName, NSUInteger idx, BOOL *stop) {
    if (idx > 0)
    {
      [updateSQL addObject:@","];
    }

    [updateSQL addObject:[FMDatabase escapeIdentifier:columnName]];
    [updateSQL addObject:@"="];
    [updateSQL addObject:expressions[idx]];
  }];

  if (where != nil)
  {
    [updateSQL addObject:@"WHERE"];
    [updateSQL addObject:where];
  }

  BOOL successful = [self executeUpdate:[updateSQL componentsJoinedByString:@" "]
                   withArgumentsInArray:arguments
                                  error:error_p];
  if (!successful)
  {
    return -1;
  }

  return self.changes;
}

// ========== DELETE ===================================================================================================
#pragma mark - Delete

- (NSInteger)deleteFrom:(NSString *)tableName
         matchingValues:(NSDictionary *)matchingValues
                  error:(NSError **)error_p
{
  NSArray * arguments = nil;
  NSString * where = [FMDatabase whereClauseToMatchValues:matchingValues
                                                arguments:&arguments];
  return [self deleteFrom:tableName
                    where:where
                arguments:arguments
                    error:error_p];
}

- (NSInteger)deleteFrom:(NSString *)tableName
                  where:(NSString *)where
              arguments:(NSArray *)arguments
                  error:(NSError **)error_p
{
  NSMutableArray * deleteSQL = [[NSMutableArray alloc] init];
  [deleteSQL addObject:@"DELETE FROM"];
  [deleteSQL addObject:tableName];

  if (where.length > 0)
  {
    [deleteSQL addObject:@"WHERE"];
    [deleteSQL addObject:where];
  }

  BOOL succeeded = [self executeUpdate:[deleteSQL componentsJoinedByString:@" "]
                  withArgumentsInArray:arguments
                                 error:error_p];
  if (!succeeded)
  {
    return -1;
  }

  return self.changes;
}

@end


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;

using Amazon.CloudWatch.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;

namespace Amazon.CloudWatch.Model.Internal.MarshallTransformations
{
    /// <summary>
    /// Put Metric Alarm Request Marshaller
    /// </summary>
    public class PutMetricAlarmRequestMarshaller : IMarshaller<IRequest, PutMetricAlarmRequest>
    {
        public IRequest Marshall(PutMetricAlarmRequest putMetricAlarmRequest)
        {
            IRequest request = new DefaultRequest(putMetricAlarmRequest, "AmazonCloudWatch");
            request.Parameters.Add("Action", "PutMetricAlarm");
            request.Parameters.Add("Version", "2010-08-01");
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetAlarmName())
            {
                request.Parameters.Add("AlarmName", StringUtils.FromString(putMetricAlarmRequest.AlarmName));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetAlarmDescription())
            {
                request.Parameters.Add("AlarmDescription", StringUtils.FromString(putMetricAlarmRequest.AlarmDescription));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetActionsEnabled())
            {
                request.Parameters.Add("ActionsEnabled", StringUtils.FromBool(putMetricAlarmRequest.ActionsEnabled));
            }
            if (putMetricAlarmRequest != null)
            {
                List<string> oKActionsList = putMetricAlarmRequest.OKActions;

                int oKActionsListIndex = 1;
                foreach (string oKActionsListValue in oKActionsList)
                {
                    request.Parameters.Add("OKActions.member." + oKActionsListIndex, StringUtils.FromString(oKActionsListValue));
                    oKActionsListIndex++;
                }
            }
            if (putMetricAlarmRequest != null)
            {
                List<string> alarmActionsList = putMetricAlarmRequest.AlarmActions;

                int alarmActionsListIndex = 1;
                foreach (string alarmActionsListValue in alarmActionsList)
                {
                    request.Parameters.Add("AlarmActions.member." + alarmActionsListIndex, StringUtils.FromString(alarmActionsListValue));
                    alarmActionsListIndex++;
                }
            }
            if (putMetricAlarmRequest != null)
            {
                List<string> insufficientDataActionsList = putMetricAlarmRequest.InsufficientDataActions;

                int insufficientDataActionsListIndex = 1;
                foreach (string insufficientDataActionsListValue in insufficientDataActionsList)
                {
                    request.Parameters.Add("InsufficientDataActions.member." + insufficientDataActionsListIndex, StringUtils.FromString(insufficientDataActionsListValue));
                    insufficientDataActionsListIndex++;
                }
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetMetricName())
            {
                request.Parameters.Add("MetricName", StringUtils.FromString(putMetricAlarmRequest.MetricName));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetNamespace())
            {
                request.Parameters.Add("Namespace", StringUtils.FromString(putMetricAlarmRequest.Namespace));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetStatistic())
            {
                request.Parameters.Add("Statistic", StringUtils.FromString(putMetricAlarmRequest.Statistic));
            }

            if (putMetricAlarmRequest != null)
            {
                List<Dimension> dimensionsList = putMetricAlarmRequest.Dimensions;
                int dimensionsListIndex = 1;
                foreach (Dimension dimensionsListValue in dimensionsList)
                {
                    if (dimensionsListValue != null && dimensionsListValue.IsSetName())
                    {
                        request.Parameters.Add("Dimensions.member." + dimensionsListIndex + ".Name", StringUtils.FromString(dimensionsListValue.Name));
                    }
                    if (dimensionsListValue != null && dimensionsListValue.IsSetValue())
                    {
                        request.Parameters.Add("Dimensions.member." + dimensionsListIndex + ".Value", StringUtils.FromString(dimensionsListValue.Value));
                    }

                    dimensionsListIndex++;
                }
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetPeriod())
            {
                request.Parameters.Add("Period", StringUtils.FromInt(putMetricAlarmRequest.Period));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetUnit())
            {
                request.Parameters.Add("Unit", StringUtils.FromString(putMetricAlarmRequest.Unit));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetEvaluationPeriods())
            {
                request.Parameters.Add("EvaluationPeriods", StringUtils.FromInt(putMetricAlarmRequest.EvaluationPeriods));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetThreshold())
            {
                request.Parameters.Add("Threshold", StringUtils.FromDouble(putMetricAlarmRequest.Threshold));
            }
            if (putMetricAlarmRequest != null && putMetricAlarmRequest.IsSetComparisonOperator())
            {
                request.Parameters.Add("ComparisonOperator", StringUtils.FromString(putMetricAlarmRequest.ComparisonOperator));
            }

            return request;
        }
    }
}


text:
<!--
  ~ Copyright (c) 2019. Christian Grach <christian.grach@cmgapps.com>
  ~
  ~ 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.
  -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cmgapps.android.apprater">

    <application>
        <activity
            android:name=".testing.TestActivity"
            android:theme="@style/Theme.AppCompat" />
    </application>

</manifest>


text:
from cspace import CSpace
from .. import robotsim
from ..model import collide
from cspaceutils import AdaptiveCSpace,EmbeddedCSpace
import math
import random

class RobotCSpace(CSpace):
    """A basic robot cspace that allows collision free motion.

    Warning: if your robot has non-standard joints, like a free-
    floating base or continuously rotating (spin) joints, you will need to
    overload the sample() method."""
    def __init__(self,robot,world=None,collider=None):
        """Arguments:
        - robot: the robot which should move.
        - collider (optional): a collide.WorldCollider instance containing
          the world in which the robot lives.  Any ignored collisions will be
          respected in the collision checker.
        """
        CSpace.__init__(self)
        self.robot = robot
        self.setBounds(zip(*robot.getJointLimits()))
        self.collider = collider
        self.addFeasibilityTest((lambda x: self.inJointLimits(x)),"joint limits")

        def setconfig(x):
                self.robot.setConfig(x)
                return True
        if collider:
            bb0 = ([float('inf')]*3,[float('-inf')]*3)
            bb = [bb0[0],bb0[1]]
            def calcbb(x):
                bb[0] = bb0[0]
                bb[1] = bb0[1]
                for i in xrange(self.robot.numLinks()):
                    g = self.robot.link(i).geometry()
                    if not g.empty():
                        bbi = g.getBB()
                        bb[0] = [min(a,b) for (a,b) in zip(bb[0],bbi[0])]
                        bb[1] = [max(a,b) for (a,b) in zip(bb[1],bbi[1])]
                return True
            def objCollide(o):
                obb = self.collider.world.rigidObject(o).geometry().getBB()
                if not collide.bb_intersect(obb,bb): return False
                return any(True for _ in self.collider.robotObjectCollisions(self.robot.index,o))
            def terrCollide(o):
                obb = self.collider.world.terrain(o).geometry().getBB()
                if not collide.bb_intersect(obb,bb): return False
                return any(True for _ in self.collider.robotTerrainCollisions(self.robot.index,o))
            self.addFeasibilityTest(setconfig,"setconfig")
            self.addFeasibilityTest(calcbb,"calcbb",dependencies="setconfig")
            self.addFeasibilityTest((lambda x: not self.selfCollision()),"self collision",dependencies="setconfig")
            #self.addFeasibilityTest((lambda x: not self.envCollision()),"env collision")
            for o in range(self.collider.world.numRigidObjects()):
                self.addFeasibilityTest((lambda x,o=o: not objCollide(o)),"obj collision "+str(o)+" "+self.collider.world.rigidObject(o).getName(),dependencies="calcbb")
            for o in range(self.collider.world.numTerrains()):
                self.addFeasibilityTest((lambda x,o=o: not terrCollide(o)),"terrain collision "+str(o)+" "+self.collider.world.terrain(o).getName(),dependencies="calcbb")
        else:
            self.addFeasibilityTest(setconfig,"setconfig")
            self.addFeasibilityTest((lambda x: not self.selfCollision()),"self collision",dependencies="setconfig")

        self.properties['geodesic'] = 1

    def addConstraint(self,checker,name=None):
        self.addFeasiblilityTest(checker,name)

    def sample(self):
        """Overload this to implement custom sampling strategies or to handle
        non-standard joints.  This one will handle spin joints and
        rotational axes of floating bases."""
        res = CSpace.sample(self)
        for i,x in enumerate(res):
            if math.isnan(x):
                res[i] = random.uniform(0,math.pi*2.0)
        return res

    def inJointLimits(self,x):
        """Checks joint limits of the configuration x"""
        for (xi,bi) in zip(x,self.bound):
            if xi < bi[0] or xi > bi[1]:
                return False
        return True

    def selfCollision(self,x=None):
        """Checks whether the robot at its current configuration is in
        self collision"""
        #This should be faster than going through the collider...
        if x is not None: self.robot.setConfig(x)
        return self.robot.selfCollides()
        #if not self.collider: return False
        #return any(self.collider.robotSelfCollisions(self.robot.index))

    def envCollision(self,x=None):
        """Checks whether the robot at its current configuration is in
        collision with the environment."""
        if not self.collider: return False
        if x is not None: self.robot.setConfig(x)
        for o in xrange(self.collider.world.numRigidObjects()):
            if any(self.collider.robotObjectCollisions(self.robot.index,o)):
                return True;
        for o in xrange(self.collider.world.numTerrains()):
            if any(self.collider.robotTerrainCollisions(self.robot.index,o)):
                return True;
        return False

    def interpolate(self,a,b,u):
        return self.robot.interpolate(a,b,u)

    def distance(self,a,b):
        return self.robot.distance(a,b)

    def sendPathToController(self,path,controller):
        """Given a planned CSpace path 'path' and a SimRobotController 'controller',
        sends the path so that it is executed correctly by the controller (this assumes
        a fully actuated robot)."""
        controller.setMilestone(path[0])
        for q in path[1:]:
            controller.appendMilestoneLinear(q)

class RobotSubsetCSpace(EmbeddedCSpace):
    """A basic robot cspace that allows collision free motion of a *subset*
    of joints.  The subset is given by the indices in the list "subset"
    provided to the constructor.  The configuration space is R^k where k
    is the number of DOFs in the subset.

    This class will automatically disable all collisions for inactive robot links
    in the collider.

    Note: to convert from start/goal robot configurations to the CSpace, call
    the project(qrobot) method for the start and goal. (see EmbeddedCSpace.project())

    Note: to convert from a planned path back to the robot's full configuration space,
    you will need to call the lift(q) method for all configurations q in the planned
    path. (see EmbeddedCSpace.lift())

    Warning: if your robot has non-standard joints, like a free-
    floating base or continuously rotating (spin) joints, you will need to
    overload the sample() method."""
    def __init__(self,robot,subset,collider=None):
        EmbeddedCSpace.__init__(self,RobotCSpace(robot,collider),subset,xinit=robot.getConfig())
        self.collider = collider
        if self.collider:
            inactive = []
            for i in range(robot.numLinks()):
                if i not in subset: inactive.append(i)
            #disable self-collisions for inactive objects
            for i in inactive:
                rindex = self.collider.robots[robot.index][i]
                self.collider.mask[rindex] = set()

    def liftPath(self,path):
        """Given a CSpace path path, lifts this to the full robot configuration"""
        return [self.lift(q) for q in path]

    def sendPathToController(self,path,controller):
        """Given a planned CSpace path 'path' and a SimRobotController 'controller',
        sends the path so that it is executed correctly by the controller (this assumes
        a fully actuated robot)."""
        lpath = self.liftPath(path)
        controller.setMilestone(lpath[0])
        for q in lpath[1:]:
            controller.appendMilestoneLinear(q)

class ClosedLoopRobotCSpace(RobotCSpace):
    """A closed loop cspace.  Allows one or more IK constraints to be
    maintained during the robot's motion.

    Attributes:
    - solver: the IKSolver that is used.
    - maxIters: the maximum number of iterations for numerical IK solver
    - tol: how closely the IK constraint must be met, in meters/radians

    To satisfy the IK constraint, the motion planner ensures that configuration
    samples are projected to the manifold of closed-loop IK solutions.  To create
    edges between samples a and b, the straight line path a and b is projected to
    the manifold via an IK solve.
    """
    def __init__(self,robot,iks,collider=None):
        RobotCSpace.__init__(self,robot,collider)
        self.solver = robotsim.IKSolver(robot)
        if hasattr(iks,'__iter__'):
            for ik in iks:
                self.solver.add(ik)
        else:
            self.solver.add(iks)

        #root finding iterations
        self.maxIters = 100
        self.tol = 1e-3
        self.addFeasibilityTest((lambda x: self.closedLoop(x)),'closed loop constraint')

    def setIKActiveDofs(self,activeSet):
        """Marks that only a subset of the DOFs of the robot are to be used for solving
        the IK constraint."""
        self.solver.setActiveDofs(activeSet)

    def sample(self):
        """Samples directly on the contact manifold.  The basic method samples arbitrarily in
        the configuration space and then solves IK constraints.  This may be an ineffective
        method especially for floating-base robots, since the floating joints may be sampled
        arbitrarily."""
        x = RobotCSpace.sample(self)
        return self.solveConstraints(x)

    def sampleneighborhood(self,c,r):
        """Samples a neighborhood in ambient space and then projects onto the contact manifold"""
        x = RobotCSpace.sampleneighborhood(self,c,r)
        return self.solveConstraints(x)

    def solveConstraints(self,x):
        """Given an initial configuration of the robot x, attempts to solve the IK constraints
        given in this space.  Return value is the best configuration found via local optimization."""
        self.robot.setConfig(x)
        self.solver.setMaxIters(self.maxIters)
        self.solver.setTolerance(self.tol)
        res = self.solver.solve()
        return self.robot.getConfig()

    def closedLoop(self,config=None,tol=None):
        """Returns true if the closed loop constraint has been met at config,
        or if config==None, the robot's current configuration."""
        if config is not None: self.robot.setConfig(config)
        e = self.solver.getResidual()
        if tol==None: tol = self.tol
        return max(abs(ei) for ei in e) <= tol

    def interpolate(self,a,b,u):
        """Interpolates on the manifold.  Used by edge collision checking"""
        x = RobotCSpace.interpolate(self,a,b,u)
        return self.solveConstraints(x)

    def interpolationPath(self,a,b,epsilon=1e-2):
        """Creates a discretized path on the contact manifold between the points a and b, with
        resolution epsilon"""
        d = self.distance(a,b)
        nsegs = int(math.ceil(d/epsilon))
        if nsegs <= 1: return [a,b]
        res = [a]
        for i in xrange(nsegs-1):
            u = float(i+1)/float(nsegs)
            res.append(self.interpolate(a,b,u))
        res.append(b)
        return res

    def discretizePath(self,path,epsilon=1e-2):
        """Given a CSpace path path, generates a path that satisfies closed-loop constraints
        up to the given distance between milestones"""
        if path is None: return None
        if len(path)==0: return []
        respath = [path[0]]
        for a,b in zip(path[:-1],path[1:]):
            respath += self.interpolationPath(a,b,epsilon)[1:]
        return respath

    def sendPathToController(self,path,controller,epsilon=1e-2):
        """Given a CSpace path path, sends the path to be executed to the SimRobotController.
        This discretizes the path and sends it as a piecewise linear curve, limited in speed
        by the robot's maximum velocity.

        NOTE: this isn't the best thing to do for robots with slow acceleration limits
        and/or high inertias because it ignores acceleration.  A better solution can be found
        in the MInTOS package or the C++ code in Klampt/Planning/RobotTimeScaling.h."""
        dpath = self.discretizePath(path,epsilon)
        vmax = controller.model().getVelocityLimits()
        assert len(dpath[0]) == len(vmax)
        controller.setMilestone(dpath[0])
        for a,b in zip(dpath[:-1],dpath[1:]):
            dt = 0.0
            for i in xrange(len(a)):
                if vmax[i] == 0:
                    if a[i] != b[i]: print "ClosedLoopRobotCSpace.sendPathToController(): Warning, path moves on DOF %d with maximum velocity 0"%(i,)
                else:
                    dt = max(dt,abs(a[i]-b[i])/vmax[i])
            #this does a piecewise lienar interpolation
            controller.appendLinear(dt,b)

class ImplicitManifoldRobotCSpace(RobotCSpace):
    """A closed loop cspace with an arbitrary numerical manifold f(q)=0
    to constrain the robot's motion.  The argument implicitConstraint
    should be a function f(q) returning a list of values that should be
    equal to 0 up to the given tolerance.  Essentially this is a
    ClosedLoopRobotCSpace except with a user-provided function.

    See ClosedLoopRobotCSpace.
    """
    def __init__(self,robot,implicitConstraint,collider=None):
        RobotCSpace.__init__self(robot,collider)
        self.implicitConstraint = implicitConstraint

        #root finding iterations
        self.maxIters = 100
        self.tol = 1e-3

        self.addFeasibilityTest((lambda x: self.onManifold(x)),'implicit manifold constraint')

    def sample(self):
        """Samples directly on the contact manifold"""
        x = RobotCSpace.sample()
        return self.solveManifold(x)

    def onManifold(self,x,tol=None):
        """Returns true if the manifold constraint has been met at x."""
        e = self.implicitConstraint.eval(x)
        if tol==None: tol = self.tol
        return max(abs(ei) for ei in e) <= tol

    def solveManifold(self,x,tol=None,maxIters=None):
        """Solves the manifold constraint starting from x, to the given
        tolerance and with the given maximum iteration count.  Default
        uses the values set as attributes of this class.
        """
        if tol==None: tol = self.tol
        if maxIters==None: maxIters = self.maxIters
        import rootfind
        rootfind.setXTolerance(1e-8)
        rootfind.setFTolerance(tol)
        rootfind.setVectorField(self.implicitConstraint)
        (res,x,val) = rootfind.findRootsBounded(x,self.bound)
        return x

    def interpolate(self,a,b,u):
        """Interpolates on the manifold.  Used by edge collision checking"""
        x = RobotCSpace.interpolate(self,a,b,u)
        return self.solveManifold(x)


text:
@interface FancyTBViewCon : UITableViewController

@end


text:
layout: post
title: Drupal langsame Schreibzugriffe mit innodb
tags:
- datenbank
- Drupal
- drupal
- entwicklung
- innodb
- performance
status: publish
type: post
published: true
meta:
  _edit_last: '1'
  dsq_thread_id: '786799825'
  better-related-: ''
---
Mit Drupal 6.17 wurde innoDB eingeführt. Bisher wurde immer myisam verwendet. Die Standardwerte, welche mit MySQL kommen sind für MyIsam ziemlich gut und man kommt schon sehr weit damit. Verwendet man jedoch die Standardwerte für innoDB, dann hat man einen ziemlich Flaschenhals.

Mit der Installation von Drupal 6.17 stellte ich fest, dass die Seite massiv langsamer wurde. Devel zeigte mir, dass vor allem Schreibzugriffe (z.B. auf die Cachetabellen) sehr langsam vorangingen... (Faktor 100 langsamer als vorher). So habe ich kurzerhand diese Tabellen wieder auf MyIsam zurückgesetzt und siehe da, es ging wieder schneller.

Heute hatte ich ein bisschen mehr Zeit, um ein wenig herumzuspielen. Schlussendlich habe ich die Lösung gefunden, den Flaschenhals zu öffnen:

innodb_flush_log_at_trx_commit = 2

Standardmässig ist er gar nicht gesetzt. Sobald ich den auf 2 gesetzt habe ist die Seite nur so "geflogen". Performance hat auch mit innoDB massiv zugenommen. Was ist passiert. Wenn innodb_flush_log_at_trx_commit auf 2 gesetzt ist, dann wird nur jede Sekunde etwas auf die Festplatte geschrieben, sonst wird jeder Schreibbefehl auch gleich auf die Festplatte geschrieben, was natürlich viel langsamer ist.

Also... ich bin überhaupt kein MySQL Perfromance Guru, aber das scheint mir eine sehr einfache und effiziente Lösung zu sein.


text:
DIC = function DIC()
{
    this._registry = {};
    this._shared = {};
    this._tags = {};
};

DIC.prototype.register = function(name, item, options)
{
    this._register(name, item);
    this._parseOptions(name, item, options)
};

DIC.prototype.get = function(name)
{
    if (this.isMarkedShared(name)) {
        this._instantiateShared(name);
        return this._shared[name];
    }

    return this._create(name);
};

DIC.prototype.getTagged = function(tag)
{
    if (this._tags[tag] instanceof Array) {
        return this._tags[tag];
    }

    return [];
};

DIC.prototype.createNewFromTag = function(tag)
{
    var _dic = new DIC();

    this.getTagged(tag).forEach(function(name) {
        _dic.register(name, this.get(name));
    }.bind(this));

    return _dic;
};

DIC.prototype._register = function(name, item)
{
    this._registry[name] = item;
};

DIC.prototype._parseOptions = function(name, item, options)
{
    options = options === undefined ? {} : options;

    if (this._sharedOptionEnabled(options)) {
        this._markAsShared(name);
    }

    this._getTagsFromOptions(options).forEach(function(tag) {
        this._tag(name, tag);
    }.bind(this));
};

DIC.prototype.isMarkedShared = function(name)
{
    return Object.keys(this._shared).indexOf(name) != -1;
};

DIC.prototype._instantiateShared = function(name)
{
    this._shared[name] = this._shared[name] || this._create(name);
};

DIC.prototype._create = function(name)
{
    if (typeof this._registry[name] === 'undefined') {
        throw new Error("Undefined key: '" + name + "'");
    }

    if (typeof this._registry[name] === 'function') {
        return this._registry[name].call(undefined, this);
    }

    return this._registry[name];
};

DIC.prototype._sharedOptionEnabled = function(options)
{
    return !! options.shared;
};

DIC.prototype._markAsShared = function(name)
{
    this._shared[name] = null;
};

DIC.prototype._getTagsFromOptions = function(options)
{
    if (options.tags instanceof Array) {
        return options.tags;
    }

    return [];
};

DIC.prototype._tag = function(name, tag)
{
    if (typeof this._tags[tag] === 'undefined') {
        this._tags[tag] = [];
    }

    this._tags[tag].push(name);
};


text:
require 'mbrowser/version'
require 'mbrowser/browser'
module Mbrowser
end


text:
Wear Collection App
=======================
This app showcases the ability to collect new features using an [Android Wear](http://www.android.com/wear/) device. The wear device presents the user with a list of recently used feature layers, and then with the feature types for the selected feature layer. The user can then choose a feature type and a new feature of that type will be collected at the device's current location.

## Requirements
* Android Studio
* An Android Wear device
* An Android mobile device

## Usage Instructions
You must install the "mobile" module onto a phone/tablet, and the "wear" module onto your Wear device. Below are separate instructions for how you can use both the mobile and wear applications

### Mobile app
The mobile app starts with a listview that is by default populated with a single entry, the Recreation sample feature layer. New layers can be added by clicking the floating action button. This will show a dialog in which you can enter the name and URL of a feature layer.

Once a feature layer is selected, a MapView will be shown with a Topographic basemap and the selected feature layer on top. To collect a new feature, click the floating action button and select the feature type to add, then click the "Add" dialog button.

### Wear app
The wear app starts by stating that it is fetching the feature layers. At this point it is requesting the list of layers established in the mobile app. Once a response is received, the layers are shown in a list on the wear device. The user can scroll through these and select one, which will then state that it is fetching feature types. At this point it is requesting the list of feature types available in the selected layer. Once a response is received, the feature types are shown in a list on the wear device. The user can scroll through tese and select one, which will then state that the feature is being collected. During this, the mobile device uses its current location to collect a new feature of the specified type.

If the collection is successful, the wear device will display a message in green stating that it was a success. If it failed, the wear device will display a message in red stating that it was a failure. In either case, the message will dismiss after a couple seconds.

## Licensing
Copyright 2016 Esri

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.

A copy of the license is available in the repository's [license.txt](https://github.com/Esri/arcgis-runtime-demos-android/blob/master/license.txt) file.

For information about licensing your deployed app, see [License your app](https://developers.arcgis.com/android/guide/license-your-app.htm).


text:
from __future__ import print_function, division

from sympy.functions import SingularityFunction, DiracDelta, Heaviside
from sympy.core import sympify
from sympy.integrals import integrate

def singularityintegrate(f, x):
    """
    This function handles the indefinite integrations of Singularity functions.
    The ``integrate`` function calls this function internally whenever an
    instance of SingularityFunction is passed as argument.

    The idea for integration is the following:

    - If we are dealing with a SingularityFunction expression,
      i.e. ``SingularityFunction(x, a, n)``, we just return
      ``SingularityFunction(x, a, n + 1)/(n + 1)`` if ``n >= 0`` and
      ``SingularityFunction(x, a, n + 1)`` if ``n < 0``.

    - If the node is a multiplication or power node having a
      SingularityFunction term we rewrite the whole expression in terms of
      Heaviside and DiracDelta and then integrate the output. Lastly, we
      rewrite the output of integration back in terms of SingularityFunction.

    - If none of the above case arises, we return None.

    Examples
    ========
    >>> from sympy.integrals.singularityfunctions import singularityintegrate
    >>> from sympy import SingularityFunction, symbols, Function
    >>> x, a, n, y = symbols('x a n y')
    >>> f = Function('f')
    >>> singularityintegrate(SingularityFunction(x, a, 3), x)
    SingularityFunction(x, a, 4)/4
    >>> singularityintegrate(5*SingularityFunction(x, 5, -2), x)
    5*SingularityFunction(x, 5, -1)
    >>> singularityintegrate(6*SingularityFunction(x, 5, -1), x)
    6*SingularityFunction(x, 5, 0)
    >>> singularityintegrate(x*SingularityFunction(x, 0, -1), x)
    0
    >>> singularityintegrate(SingularityFunction(x, 1, -1) * f(x), x)
    f(1)*SingularityFunction(x, 1, 0)

    """

    if not f.has(SingularityFunction):
        return None

    if f.func == SingularityFunction:
        x = sympify(f.args[0])
        a = sympify(f.args[1])
        n = sympify(f.args[2])
        if n.is_positive or n.is_zero:
            return SingularityFunction(x, a, n + 1)/(n + 1)
        elif n == -1 or n == -2:
            return SingularityFunction(x, a, n + 1)

    if f.is_Mul or f.is_Pow:

        expr = f.rewrite(DiracDelta)
        expr = integrate(expr, x)
        return expr.rewrite(SingularityFunction)
    return None


text:
var groceryList = {};

function addItem(item,quantity) {
  groceryList[item] = quantity;
};

function deleteItem(item) {
  delete groceryList[item];
};

function changeQuantity(item,quantity) {
  if (groceryList.hasOwnProperty(item)) {
    groceryList[item] = quantity;
  };
};

function printList(list) {
  for (var item in list) {
    console.log(item + ': ' + list[item]);
  };
};

// driver code
addItem("dog food",7);
addItem("oranges",2);
addItem("pears",3);
deleteItem("oranges");
changeQuantity("dog food",1);
printList(groceryList);

// Refactored Solution -- REFACTORED as I went...

// Reflection

// What concepts did you solidify in working on this challenge? (reviewing the passing of information, objects, constructors, etc.)
// manipulating objects

// What was the most difficult part of this challenge?
// printing it nicely

// Did an array or object make more sense to use and why?
// Object because need item and value


text:
title:  10 yıldır dua ediyor
date:  24/06/2022
---

_Yazan: Andrew McChesney_

Moskova'da İngilizce öğreten bir ABD gönüllüsü olan Winston Crawford, Rus öğrencilerinden birini Sebt günü Yedinci Gün Adventist kilisesine davet etti.

Öğrenci Sasha, ibadet tecrübesinden etkilenmemiş gibi görünüyordu. Ateist bir ailede büyümüştü ve düpedüz sıkılmış görünüyordu.

Winston üzgün hissetti. "Onu geri davet etmeye çalışmayacağım," dedi kendi kendine. "Kendisinin hoşlanmadığını açıkça görebiliyorum." Bunun yerine dua etmeye başladı. Rab'bin Sasha'nın kalbine dokunması için dua etti.

Aylar geçtikçe Winston ve Sasha bir dostluk kurdular. Tatil sırasında Sasha, ebeveynleri ve küçük erkek kardeşiyle tanışmak için onu Finlandiya yakınlarındaki Karelya bölgesine seyahat etmeye davet etti. Winston dua etmeye devam etti.

Gönüllü hizmet yılını tamamladıktan sonra, Winston Amerika Birleşik Devletleri'ne döndü, ancak Sasha ile temas halinde kaldı. Sasha birkaç yıl sonra Amerika Birleşik Devletleri'ni ziyaret ettiğinde, ikisi Chicago'da birlikte vakit geçirdi.

Winston dua etmeye devam etti. 10 yıldan fazla zaman geçmişti.

Bir gün Sasha, WhatsApp aracılığıyla bir mesaj gönderdi. "Kutsal Kitap'ı okumak istiyorum" diye yazdı. "Anlamama yardım eder misin?" Winston buna çok sevindi. «Tabii ki!" diye geri mesaj attı. Haftada bir buluşmayı kabûl ettiler.

İlk buluşmalarında Sasha, Yaratılış 1.bölümü okurken büyülenmişti. Yaratılış 1:29'da Tanrı'nın vejetaryen bir diyet vermiş olmasından özellikle etkilenmişti; ''İşte yeryüzünde tohum veren her otu, tohumu meyvesinde bulunan her meyve ağacını size veriyorum. Bunlar size yiyecek olacak.'' Sasha bir vejetaryendi ve sebze, meyve ve bakliyat bazlı bir diyeti izlemenenin iyi bir uygulama olduğunu düşünmüştü.

"Bunun Kutsal Kitap'tan olduğunu bilmiyordum!" dedi.

Buluşmalarının sonunda şaşkınlığını dile getirdi. "Puşkin ve Dostoyevski'yi okudum ama Kutsal Kitap'ı okuduğumda farklı bir şey oluyor gibi sanki" dedi. "Sanki kelimeler sayfadan bana geliyor gibi."

Winston mutluydu. Kutsal Ruh'un Sasha'nın kalbine ulaşmak için Sözünü etkin kıldığından emindi. Üç haftalık Kutsal Kitap çalışmalarından sonra Sasha, ibadetlerini haftada iki defaya çıkarıp çıkaramayacaklarını sordu. Winston dua etmeye devam etti. Winston bir röportajda şunları söyledi: "10 yıldan fazla bir süre sonra Kutsal Kitabı okumak istemesi benim için ilham verici ve sadece bu değil, onunla Kutsal Kitap'ı çalışma şansım da var" dedi. "Bunun tamamen Tanrı olduğunu biliyorum."

Bu müjdecilik hikayesi, Yedinci Gün Adventist Kilisesi'nin "I Will Go (Gideceğim)" stratejik plânının 5 No'lu Ruhsal Büyüme Hedefini göstermektedir, «Bireyleri ve aileleri ruhla dolu yaşamlara yönlendirmek.» Devamını okumak için: IWillGo2020.org.


text:
using System.Collections.Generic;

namespace GenericMvc.ViewModels.SinglePageApp
{
	public class SinglePageGraph
	{
		public SinglePageGraph(string title,
			Page menuListViewModel,
			Page pageListView,
			IEnumerable<Page> pages,
			IEnumerable<Page> modals)
		{
			Title = title;
			MenuListViewModel = menuListViewModel;
			PageListView = pageListView;
			Pages = pages;
			Modals = modals;
		}

		public string Title { get; }

		public IEnumerable<Page> Pages { get; }

		public IEnumerable<Page> Modals { get; }

		public Page MenuListViewModel { get; }

		public Page PageListView { get; }
	}

	public static class SinglePage
	{
		public static Microsoft.AspNetCore.Mvc.ViewResult SideMenuView(this Microsoft.AspNetCore.Mvc.Controller controller, SinglePageGraph sideMenu)
		{
			return controller.View("~/Views/Shared/SideMenuContainer.cshtml", sideMenu);
		}
	}
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestControl.Net;
using TestControl.Net.Interfaces;
using TestControl.Net.Locators;
using TestControl.Net.StdControls;

namespace TestControlFixtures.WinForm
{
    public class ButtonFixture : BaseFixture
    {

        public ButtonFixture()
        {
            FixtureUnderTest = new TextBoxFixture();
        }

        public void ClickTheButton()
        {
            GetButton().Click();
        }

        private ButtonControl GetButton()
        {
            var button = new ButtonControl();
            button.SystemUnderTest(new ControlLocatorDef<FindControl>(
                                                () => new FindWindow(APPLICATION_CAPTION),
                                                () => new FindByAutomationId("buttonOk")
                    ));
            return button;
        }

    }
}


text:
.class public Landroid/view/ScaleGestureDetector$SimpleOnScaleGestureListener;
.super Ljava/lang/Object;
.source "ScaleGestureDetector.java"

# interfaces
.implements Landroid/view/ScaleGestureDetector$OnScaleGestureListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/view/ScaleGestureDetector;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x9
    name = "SimpleOnScaleGestureListener"
.end annotation

# direct methods
.method public constructor <init>()V
    .locals 0

    .prologue
    .line 111
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onScale(Landroid/view/ScaleGestureDetector;)Z
    .locals 1
    .param p1, "detector"    # Landroid/view/ScaleGestureDetector;

    .prologue
    .line 114
    const/4 v0, 0x0

    return v0
.end method

.method public onScaleBegin(Landroid/view/ScaleGestureDetector;)Z
    .locals 1
    .param p1, "detector"    # Landroid/view/ScaleGestureDetector;

    .prologue
    .line 118
    const/4 v0, 0x1

    return v0
.end method

.method public onScaleEnd(Landroid/view/ScaleGestureDetector;)V
    .locals 0
    .param p1, "detector"    # Landroid/view/ScaleGestureDetector;

    .prologue
    .line 121
    return-void
.end method


text:
package org.hisp.dhis.commons.collection;

import java.util.HashMap;

/**
 * HashMap that appends the content of the value the existing content when
 * inserted, or inserts as usual if no entries match the key.
 *
 * @author Lars Helge Overland
 */
public class AppendingHashMap<K, V>
    extends HashMap<K, String>
{
    /**
     * Determines if a de-serialized file is compatible with this class.
     */
    private static final long serialVersionUID = 2579976271277075017L;

    /**
     * Appends the content of the value the existing content when
     * inserted, or inserts as usual if no entries match the key.
     *
     * @param key the key.
     * @param value the value.
     * @return the new value.
     */
    @Override
    public String put( K key, String value )
    {
        final String existing = super.get( key );

        value = existing != null ? existing + value : value;

        super.put( key, value );

        return existing;
    }
}


text:
const Flint = require('../../../../index.js')
const request = require('supertest')
const mongoose = require('mongoose')

describe('logs app', () => {
  let server

  beforeAll(async () => {
    const flintServer = new Flint({ logsPath: 'test/fixtures/logs', listen: false })
    server = await flintServer.startServer()
    return server
  })

  it('returns a 200 response for /admin/api/logs', (done) => {
    request(server).get('/admin/api/logs').expect(200, done)
  })

  it('returns the correct logs as an array', async () => {
    const res = await request(server).get('/admin/api/logs')
    const { flint, http } = res.body
    expect(Array.isArray(flint)).toBe(true)
    expect(Array.isArray(http)).toBe(true)

    expect(flint).toEqual(['This', 'is', 'a', 'log'])
  })

  afterAll(() => mongoose.disconnect())
})


text:
import numpy as np
import pandas as pd

from numba import njit

@njit
def series_setitem():
    value = 0
    series = pd.Series(np.arange(5, 0, -1))  # Series of 5, 4, 3, 2, 1

    series[0] = value

    return series   # result Series of 0, 4, 3, 2, 1

print(series_setitem())