text:
package org.diems.diemsapp;

import android.app.Fragment;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ClassTestList extends Fragment {

    RecyclerView recyclerView;
    List<MarksTeacher> marksTeacherList;
    List<MarksSubject> marksSubjectList;
    MarksTeacherAdapter marksTeacherAdapter;
    MarksSubjectAdapter marksSubjectAdapter;
    RequestQueue requestQueue;
    ProgressBar progressBar;

    public ClassTestList() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_class_test_list, container, false);

        Bundle bundle = getArguments();
        requestQueue = Volley.newRequestQueue(getActivity());
        progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
        recyclerView = (RecyclerView) view.findViewById(R.id.classTestList);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setHasFixedSize(true);

        marksTeacherList = new ArrayList<>();
        marksSubjectList = new ArrayList<>();

        marksTeacherAdapter = new MarksTeacherAdapter(marksTeacherList, recyclerView, getActivity(), getFragmentManager());
        marksSubjectAdapter = new MarksSubjectAdapter(marksSubjectList, recyclerView);

        if (bundle.getString("type").equals("teacher"))
            recyclerView.setAdapter(marksTeacherAdapter);
        else
            recyclerView.setAdapter(marksSubjectAdapter);

        String url;
        if (bundle.getString("type").equals("teacher")) {

            if (bundle.getString("name").equals("my_class"))
                url = MainActivity.IP + "/api/staff/class?access_token=" + MainActivity.userData.getAccessToken();
            else
                url = MainActivity.IP + "/api/staff/mentees?access_token=" + MainActivity.userData.getAccessToken();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    try {
                        progressBar.setVisibility(View.GONE);
                        recyclerView.setVisibility(View.VISIBLE);

                        JSONArray jsonArray = new JSONObject(response).getJSONArray("students");
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject = jsonArray.getJSONObject(i);
                            marksTeacherList.add(new MarksTeacher(
                                    jsonObject.getString("id"),
                                    jsonObject.getString("name"),
                                    jsonObject.getString("roll_no"),
                                    jsonObject.getString("below_avg_subjects")
                            ));
                        }

                        marksTeacherAdapter.notifyDataSetChanged();
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    error.printStackTrace();
                }
            });

            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
            ));
            requestQueue.add(stringRequest);
        } else if (bundle.getString("type").equals("subject")) {
            url = MainActivity.IP + "/api/staff/subjects/" + bundle.getString("id") + "?access_token=" + MainActivity.userData.getAccessToken();

            StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    progressBar.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);

                    try {
                        JSONArray jsonArray = new JSONObject(response).getJSONArray("students");
                        marksSubjectList.clear();
                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            marksSubjectList.add(new MarksSubject(
                                    object.getString("name"),
                                    object.getString("roll_no"),
                                    object.getJSONArray("marks").getJSONObject(0).getString("obt_marks"),
                                    object.getJSONArray("marks").getJSONObject(1).getString("obt_marks"),
                                    object.getString("ct_avg"),
                                    object.getString("class"),
                                    object.getString("branch"),
                                    object.getString("division")
                            ));
                        }

                        marksSubjectAdapter.notifyDataSetChanged();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

            stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                    DefaultRetryPolicy.DEFAULT_TIMEOUT_MS,
                    DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                    DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
            ));
            requestQueue.add(stringRequest);
        }

        return view;
    }
}


text:
//$URL$
//$Id$
package de.dev.eth0.bitcointrader.ui.fragments;

import android.text.format.DateUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.xeiam.xchange.currency.MoneyUtils;
import com.xeiam.xchange.mtgox.v2.dto.account.polling.MtGoxWalletHistoryEntry;
import de.dev.eth0.bitcointrader.R;
import de.dev.eth0.bitcointrader.ui.AbstractBitcoinTraderActivity;
import de.dev.eth0.bitcointrader.ui.views.CurrencyTextView;
import org.joda.money.BigMoney;

/**
 * @author Alexander Muthmann
 */
public class WalletHistoryListAdapter extends AbstractExpandableListAdapter<MtGoxWalletHistoryEntry, MtGoxWalletHistoryEntry> {

  private static final int TYPE_WITH_PRICE = 0;
  private static final int TYPE_WITHOUT_PRICE = 1;

  public WalletHistoryListAdapter(AbstractBitcoinTraderActivity activity) {
    super(activity);
  }

  @Override
  public int getChildType(int groupPosition, int childPosition) {
    MtGoxWalletHistoryEntry entry = getChild(groupPosition, childPosition);
    if (entry.getType().equals("out")
            || entry.getType().equals("in")
            || entry.getType().equals("earned")
            || entry.getType().equals("spent")) {
      return TYPE_WITH_PRICE;
    }
    return TYPE_WITHOUT_PRICE;
  }

  @Override
  public int getChildTypeCount() {
    return 2;
  }

  @Override
  public int getGroupLayout() {
    return R.layout.wallet_history_fragment_list_group;
  }

  @Override
  public int getChildLayout() {
    return R.layout.wallet_history_fragment_list_item;
  }

  public void bindGroupView(View group, MtGoxWalletHistoryEntry entry) {
    TextView headerType = (TextView)group.findViewById(R.id.wallet_history_list_group_type);
    addTypeToView(headerType, entry);

    CurrencyTextView headerAmount = (CurrencyTextView)group.findViewById(R.id.wallet_history_list_group_amount);
    addAmountToView(headerAmount, entry);
  }

  @Override
  public View getChildView(int groupPosition, final int childPosition, boolean isLastChild, View childView, ViewGroup parent) {
    int type = getChildType(groupPosition, childPosition);
    ViewHolder viewHolder;
    if (childView == null) {
      switch (type) {
        case TYPE_WITH_PRICE:
          childView = inflater.inflate(R.layout.wallet_history_fragment_list_price_item, null);
          viewHolder = new ViewHolder();
          viewHolder.priceView = (TextView)childView.findViewById(R.id.wallet_history_row_price);
          break;
        case TYPE_WITHOUT_PRICE:
        default:
          childView = inflater.inflate(R.layout.wallet_history_fragment_list_item, null);
          viewHolder = new ViewHolder();
          break;
      }
      viewHolder.balanceView = (CurrencyTextView)childView.findViewById(R.id.wallet_history_row_balance);
      viewHolder.dateView = (TextView)childView.findViewById(R.id.wallet_history_row_date);
      viewHolder.infoView = (TextView)childView.findViewById(R.id.wallet_history_row_info);
      childView.setTag(viewHolder);
    }
    else {
      viewHolder = (ViewHolder)childView.getTag();
    }

    MtGoxWalletHistoryEntry entry = getChild(groupPosition, childPosition);
    if (type == TYPE_WITH_PRICE) {
      // price
      addPriceToView(viewHolder.priceView, entry);
    }
    // balance
    BigMoney balance = MoneyUtils.parse(entry.getBalance().getCurrency() + " " + entry.getBalance().getValue());
    viewHolder.balanceView.setPrecision(8);
    viewHolder.balanceView.setAmount(balance);

    // date
    viewHolder.dateView.setText(DateUtils.getRelativeDateTimeString(activity, Long.parseLong(entry.getDate()) * 1000, DateUtils.MINUTE_IN_MILLIS, DateUtils.MINUTE_IN_MILLIS, DateUtils.FORMAT_SHOW_TIME));

    String[] substrings = entry.getInfo().split(" ");
    if (substrings.length >= 5) {
      if (entry.getInfo().contains("bought")) {
        viewHolder.infoView.setText(activity.getString(R.string.wallet_history_info_bought, substrings[3], substrings[5]));
      }
      else if (entry.getInfo().contains("sold")) {
        viewHolder.infoView.setText(activity.getString(R.string.wallet_history_info_sold, substrings[3], substrings[5]));
      }
      else {
        viewHolder.infoView.setText("");
      }
    }
    else {
      viewHolder.infoView.setText("");
    }
    return childView;
  }

  private void addPriceToView(TextView view, MtGoxWalletHistoryEntry entry) {
    String[] substrings = entry.getInfo().split(" ");
    view.setText(substrings.length >= 5 ? substrings[5] : "");
  }

  private void addAmountToView(CurrencyTextView view, MtGoxWalletHistoryEntry entry) {
    BigMoney amount = MoneyUtils.parse(entry.getValue().getCurrency() + " " + entry.getValue().getValue());
    view.setPrecision(8);
    view.setAmount(amount);
  }

  private void addTypeToView(TextView view, MtGoxWalletHistoryEntry entry) {
    if (entry.getType().equals("out")) {
      view.setText(R.string.wallet_history_out);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_out));
    }
    else if (entry.getType().equals("fee")) {
      view.setText(R.string.wallet_history_fee);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_fee));
    }
    else if (entry.getType().equals("in")) {
      view.setText(R.string.wallet_history_in);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_in));
    }
    else if (entry.getType().equals("spent")) {
      view.setText(R.string.wallet_history_spent);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_spend));
    }
    else if (entry.getType().equals("earned")) {
      view.setText(R.string.wallet_history_earned);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_earned));
    }
    else if (entry.getType().equals("withdraw")) {
      view.setText(R.string.wallet_history_withdraw);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_withdraw));
    }
    else if (entry.getType().equals("deposit")) {
      view.setText(R.string.wallet_history_deposit);
      view.setBackgroundColor(activity.getResources().getColor(R.color.history_deposit));
    }
    else {
      view.setText(entry.getType());
    }
  }

  @Override
  public void bindChildView(View child, MtGoxWalletHistoryEntry entry) {
    // not required
  }

  private static class ViewHolder {

    protected CurrencyTextView balanceView;
    protected TextView dateView;
    protected TextView priceView;
    protected TextView infoView;

  }
}

redpajama_set_name: RedPajamaGithub


text:
package org.mifos.application.servicefacade;

import org.joda.time.LocalDate;
import org.mifos.accounts.business.AccountBO;
import org.mifos.accounts.exceptions.AccountException;
import org.mifos.accounts.fees.business.AmountFeeBO;
import org.mifos.accounts.fees.business.FeeDto;
import org.mifos.accounts.loan.business.LoanBO;
import org.mifos.accounts.productdefinition.business.LoanOfferingBO;
import org.mifos.accounts.productdefinition.util.helpers.ApplicableTo;
import org.mifos.accounts.productdefinition.util.helpers.InterestType;
import org.mifos.accounts.productdefinition.util.helpers.PrdStatus;
import org.mifos.accounts.util.helpers.AccountState;
import org.mifos.accounts.util.helpers.AccountStateFlag;
import org.mifos.application.collectionsheet.persistence.*;
import org.mifos.application.master.business.MifosCurrency;
import org.mifos.application.master.util.helpers.PaymentTypes;
import org.mifos.application.meeting.business.MeetingBO;
import org.mifos.core.MifosRuntimeException;
import org.mifos.customers.center.business.CenterBO;
import org.mifos.customers.client.business.AttendanceType;
import org.mifos.customers.client.business.ClientBO;
import org.mifos.customers.group.business.GroupBO;
import org.mifos.customers.personnel.business.PersonnelBO;
import org.mifos.customers.api.CustomerLevel;
import org.mifos.framework.TestUtils;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.util.helpers.DateUtils;
import org.mifos.framework.util.helpers.IntegrationTestObjectMother;
import org.mifos.framework.util.helpers.Money;
import org.mifos.framework.util.helpers.TestObjectFactory;
import org.mifos.security.util.UserContext;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static org.mifos.framework.util.helpers.IntegrationTestObjectMother.sampleBranchOffice;
import static org.mifos.framework.util.helpers.IntegrationTestObjectMother.testUser;

/**
 * Class contains utility methods for setting up, processing and configuring a sample collection sheet hierarchy for
 * testing.
 */
public class TestSaveCollectionSheetUtils {

    /*
     * Below are variables that can be configured to create invalid entries for testing. They are injected during the
     * assembling of the dto's. This is a very ugly way to inject invalid values. Set methods would be far tidier and
     * more normal. But I (JW) preferred to keep all the save collection sheet dto's as create-only and non-updatable
     * and pay the coding price for testing.
     */
    private final Integer nonExistingId = 500000;
    private Boolean firstClientExists = true;
    private Short firstClientAttendanceType = AttendanceType.ABSENT.getValue();
    private Short firstGroupAttendanceType = null;
    private Boolean individualSavingsAccountUnderFirstGroup = false;
    private Boolean firstClientParentIdInvalid = false;
    private ClientBO nonCenterClient = null;
    private Short loanInvalidCurrency = null;
    private Boolean loanAccountIdInvalid = false;
    private Boolean loanAccountUnderFirstGroupWithFirstClientLoanId = false;
    private Boolean loanAccountCancelled = false;
    private Boolean customerAccountIdtoLoanAccountIdForFirstClient = false;
    private Boolean loanAccountIdtoCustomerAccountIdForFirstClient = false;
    private Boolean savingsAccountIdtoLoanAccountIdForFirstClient = false;
    private Integer firstClientCustomerAccountId = null;
    private Boolean overpayLoan = false;
    private Boolean duplicateFirstClient = false;
    private Boolean duplicateFirstClientLoanAccount = false;
    private Boolean overpayFirstClientAccountCollectionFee = false;
    private Boolean underpayFirstClientAccountCollectionFee = false;
    private Boolean invalidDisbursalAmountFirstClient = false;
    private Boolean invalidTransactionDate = false;
    private Boolean normalLoanRepayment = false;

    private CenterBO center;
    private GroupBO group;
    private ClientBO client;
    private LoanBO loan;
    private CenterBO anotherCenter;
    private GroupBO anotherGroup;
    private ClientBO anotherClient;

    private CollectionSheetService collectionSheetService;
    private UserContext userContext;
    private MifosCurrency currency;

    public TestSaveCollectionSheetUtils() {
        collectionSheetService = DependencyInjectedServiceLocator.locateCollectionSheetService();
        currency = Money.getDefaultCurrency();
        userContext = TestUtils.makeUser();
    }

    /**
     * Write a sample center hierarchy, retrieve the collection sheet information and put it into a
     * saveCollectionSheetDto.
     *
     * Sample hierarchy contains one center, one group and one client with a loan to be disbursed and 1 weekly account
     * collection fee
     *
     * Finally, change client and loan status if configured to do so.
     */
    public SaveCollectionSheetDto createSampleSaveCollectionSheet() throws Exception {

        LocalDate transactionDate = new LocalDate();
        try {
            createSampleCenterHierarchy(DateUtils.getDateFromLocalDate(transactionDate));
        } catch (Exception e) {
            throw new MifosRuntimeException(e);
        }
        SaveCollectionSheetDto saveCollectionSheet = assembleSaveCollectionSheetFromCreatedCenterHierarchy(transactionDate);

        if (loanAccountCancelled) {
            PersonnelBO loggedInUser = IntegrationTestObjectMother.testUser();
            loan.changeStatus(AccountState.LOAN_CANCELLED, AccountStateFlag.LOAN_OTHER.getValue(), "Loan Cancelled", loggedInUser);
            loan.update();
            StaticHibernateUtil.flushSession();
        }

        return saveCollectionSheet;
    }

    /**
     * Retrieve collection sheet information and put it into a saveCollectionSheetDto
     */
    public SaveCollectionSheetDto assembleSaveCollectionSheetFromCreatedCenterHierarchy(LocalDate transactionDate) {

        CollectionSheetDto collectionSheet = collectionSheetService.retrieveCollectionSheet(center.getCustomerId(),
                transactionDate);

        return assembleSaveCollectionSheetDto(collectionSheet, transactionDate);
    }

    /**
     * By default generates 1 center, 1 group and 1 client with 1 loan to be disbursed and 1
     * weekly account collection fee. Can be configured to add in other invalid entries.
     */
    public void createSampleCenterHierarchy(Date date) throws Exception {

        MeetingBO weeklyMeeting = new MeetingBuilder().customerMeeting().weekly().every(1).startingToday().build();
        IntegrationTestObjectMother.saveMeeting(weeklyMeeting);

        center = new CenterBuilder().withNumberOfExistingCustomersInOffice(3).with(weeklyMeeting).withName(
                "Center").with(sampleBranchOffice()).withLoanOfficer(testUser()).build();
        IntegrationTestObjectMother.createCenter(center, weeklyMeeting);

        group = new GroupBuilder().withMeeting(weeklyMeeting).withName("Group").withOffice(sampleBranchOffice())
                .withLoanOfficer(testUser()).withParentCustomer(center).build();
        IntegrationTestObjectMother.createGroup(group, weeklyMeeting);

        AmountFeeBO weeklyPeriodicFeeForFirstClients = new FeeBuilder().appliesToClientsOnly().withFeeAmount("87.0")
                .withName("First Client Weekly Periodic Fee").withSameRecurrenceAs(weeklyMeeting).with(
                        sampleBranchOffice()).build();
        IntegrationTestObjectMother.saveFee(weeklyPeriodicFeeForFirstClients);

        client = new ClientBuilder().withMeeting(weeklyMeeting).withName(
                "Client 1").withOffice(sampleBranchOffice()).withLoanOfficer(testUser()).withParentCustomer(group)
                .buildForIntegrationTests();
        IntegrationTestObjectMother.createClient(client, weeklyMeeting);

        MeetingBO loanMeeting = TestObjectFactory.createLoanMeeting(client.getCustomerMeeting().getMeeting());

        LoanOfferingBO loanOffering = TestObjectFactory.createLoanOffering("Loan", ApplicableTo.CLIENTS, date,
                PrdStatus.LOAN_ACTIVE, 1200.0, 1.2, 12, InterestType.FLAT, loanMeeting);

        loan = null;
        try {
            loan = LoanBO.createIndividualLoan(userContext, loanOffering, client, AccountState.LOAN_APPROVED,
                    new Money(currency, "1200.0"), Short.valueOf("12"), date, false, false, 10.0, (short) 0, null,
                    new ArrayList<FeeDto>(), null, false);

        } catch (AccountException e) {
            throw new Exception(e);
        }

        loan.save();

    }

    public CenterBO getCenter() {
        return this.center;
    }

    public GroupBO getGroup() {
        return this.group;
    }

    public LoanBO getClientLoan() {
        return this.loan;
    }

    /**
     * clears persistent objects created by this class
     */
    public void clearObjects() throws Exception {

        if (loan != null) {
            loan = (LoanBO) StaticHibernateUtil.getSessionTL().get(AccountBO.class, loan.getAccountId());
        }
        if (client != null) {
            client = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class, client.getCustomerId());
        }
        if (group != null) {
            group = (GroupBO) StaticHibernateUtil.getSessionTL().get(GroupBO.class, group.getCustomerId());
        }
        if (center != null) {
            center = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class, center.getCustomerId());
        }
        if (anotherClient != null) {
            anotherClient = (ClientBO) StaticHibernateUtil.getSessionTL().get(ClientBO.class,
                    anotherClient.getCustomerId());
        }
        if (anotherGroup != null) {
            anotherGroup = (GroupBO) StaticHibernateUtil.getSessionTL()
                    .get(GroupBO.class, anotherGroup.getCustomerId());
        }
        if (anotherCenter != null) {
            anotherCenter = (CenterBO) StaticHibernateUtil.getSessionTL().get(CenterBO.class,
                    anotherCenter.getCustomerId());
        }
        loan = null;
        client = null;
        group = null;
        center = null;
        anotherClient = null;
        anotherGroup = null;
        anotherCenter = null;

    }

    /*
     *
     */
    private ClientBO getAnotherClientFromAnotherCenter() throws Exception {

        MeetingBO weeklyMeeting = new MeetingBuilder().customerMeeting().weekly().every(1).startingToday().build();

        anotherCenter = new CenterBuilder().with(weeklyMeeting).withName("Another Center").with(
                sampleBranchOffice()).withLoanOfficer(testUser()).build();
        IntegrationTestObjectMother.saveCustomer(anotherCenter);

        anotherGroup = new GroupBuilder().withMeeting(weeklyMeeting).withName("Another Group").withOffice(
                sampleBranchOffice()).withLoanOfficer(testUser()).withParentCustomer(anotherCenter).build();
        IntegrationTestObjectMother.saveCustomer(anotherGroup);

        anotherClient = new ClientBuilder().withMeeting(weeklyMeeting).withName("Another Client 1").withOffice(
                sampleBranchOffice()).withLoanOfficer(testUser()).withParentCustomer(anotherGroup)
                .buildForIntegrationTests();
        IntegrationTestObjectMother.saveCustomer(anotherClient);

        return anotherClient;
    }

    /*
     * Return a SaveCollectionSheetDto that matches the input CollectionSheetDto Handy if doing performance tests that
     * want to read and save collection sheets without altering the values
     */
    public SaveCollectionSheetDto assembleSaveCollectionSheetDto(CollectionSheetDto collectionSheet,
            LocalDate transactionDate) {

        LocalDate usedTransactionDate = transactionDate;
        if (invalidTransactionDate) {
            usedTransactionDate = transactionDate.plusDays(2);
        }
        SaveCollectionSheetDto saveCollectionSheet = null;
        try {
            saveCollectionSheet = new SaveCollectionSheetDto(assembleSCSCustomers(collectionSheet
                    .getCollectionSheetCustomer()), PaymentTypes.VOUCHER.getValue(), usedTransactionDate,
                    "my new receipt", transactionDate, testUser().getPersonnelId());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (SaveCollectionSheetException e) {
            throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
        }

        return saveCollectionSheet;

    }

    /**
     * @param collectionSheetCustomers
     * @return
     */
    private List<SaveCollectionSheetCustomerDto> assembleSCSCustomers(
            List<CollectionSheetCustomerDto> collectionSheetCustomers) {

        List<SaveCollectionSheetCustomerDto> saveCollectionSheetCustomers = new ArrayList<SaveCollectionSheetCustomerDto>();
        Boolean firstClient = true;
        Boolean firstGroup = true;
        Integer numberToCreate = 1;
        for (CollectionSheetCustomerDto collectionSheetCustomer : collectionSheetCustomers) {

            Integer customerId = collectionSheetCustomer.getCustomerId();
            Integer parentCustomerId = collectionSheetCustomer.getParentCustomerId();
            Short attendanceId = null;

            SaveCollectionSheetCustomerAccountDto saveCollectionSheetCustomerAccount = assembleSCSCustomerAccount(
                    collectionSheetCustomer.getCollectionSheetCustomerAccount(), collectionSheetCustomer.getLevelId(),
                    firstClient);
            List<SaveCollectionSheetCustomerLoanDto> saveCollectionSheetCustomerLoans = assembleSCSCustomerLoans(
                    collectionSheetCustomer.getCollectionSheetCustomerLoan(), collectionSheetCustomer.getLevelId(),
                    firstClient);
            List<SaveCollectionSheetCustomerSavingDto> saveCollectionSheetCustomerSavings = assembleSCSCustomerSavings(collectionSheetCustomer
                    .getCollectionSheetCustomerSaving());
            List<SaveCollectionSheetCustomerSavingDto> saveCollectionSheetCustomerIndividualSavings = assembleSCSCustomerSavings(collectionSheetCustomer
                    .getIndividualSavingAccounts());

            if (collectionSheetCustomer.getLevelId().compareTo(CustomerLevel.CLIENT.getValue()) == 0) {

                attendanceId = AttendanceType.PRESENT.getValue();

                if (firstClient) {
                    if (duplicateFirstClient) {
                        numberToCreate = 2;
                        duplicateFirstClient = false;
                    }
                    if (!firstClientExists) {
                        customerId = nonExistingId;
                    }
                    if (firstClientParentIdInvalid) {
                        parentCustomerId = nonExistingId;
                    }
                    if (savingsAccountIdtoLoanAccountIdForFirstClient) {
                        if (saveCollectionSheetCustomerSavings == null) {
                            saveCollectionSheetCustomerSavings = new ArrayList<SaveCollectionSheetCustomerSavingDto>();
                        }
                        saveCollectionSheetCustomerSavings.add(assembleOptionalSavingsAccount(loan.getAccountId()));
                    }
                    attendanceId = firstClientAttendanceType;

                    firstClient = false;
                }
            }

            if (collectionSheetCustomer.getLevelId().compareTo(CustomerLevel.GROUP.getValue()) == 0) {

                if (firstGroup) {
                    attendanceId = firstGroupAttendanceType;

                    if (individualSavingsAccountUnderFirstGroup) {
                        if (saveCollectionSheetCustomerIndividualSavings == null) {
                            saveCollectionSheetCustomerIndividualSavings = new ArrayList<SaveCollectionSheetCustomerSavingDto>();
                        }
                        saveCollectionSheetCustomerIndividualSavings
                                .add(assembleOptionalGroupIndividualSavingsAccount());
                    }
                    if (loanAccountUnderFirstGroupWithFirstClientLoanId) {
                        if (saveCollectionSheetCustomerLoans == null) {
                            saveCollectionSheetCustomerLoans = new ArrayList<SaveCollectionSheetCustomerLoanDto>();
                        }
                        saveCollectionSheetCustomerLoans.add(assembleOptionalGroupLoanAccount(loan.getAccountId()));
                    }
                    firstGroup = false;
                }
            }

            SaveCollectionSheetCustomerDto saveCollectionSheetCustomer = null;

            for (Integer i = 0; i < numberToCreate; i++) {
                try {
                    saveCollectionSheetCustomer = new SaveCollectionSheetCustomerDto(customerId, parentCustomerId,
                            attendanceId, saveCollectionSheetCustomerAccount, saveCollectionSheetCustomerLoans,
                            saveCollectionSheetCustomerSavings, saveCollectionSheetCustomerIndividualSavings);
                } catch (SaveCollectionSheetException e) {
                    throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
                }

                saveCollectionSheetCustomers.add(saveCollectionSheetCustomer);
            }
        }

        if (nonCenterClient != null) {
            SaveCollectionSheetCustomerDto anotherSaveCollectionSheetCustomer = null;
            try {
                anotherSaveCollectionSheetCustomer = new SaveCollectionSheetCustomerDto(
                        nonCenterClient.getCustomerId(), nonCenterClient.getParentCustomer().getCustomerId(),
                        AttendanceType.PRESENT.getValue(), null, null, null, null);
            } catch (SaveCollectionSheetException e) {
                throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
            }
            saveCollectionSheetCustomers.add(anotherSaveCollectionSheetCustomer);
        }

        return saveCollectionSheetCustomers;
    }

    private SaveCollectionSheetCustomerAccountDto assembleSCSCustomerAccount(
            CollectionSheetCustomerAccountDto collectionSheetCustomerAccount, Short customerLevelId, Boolean firstClient) {

        if (null != collectionSheetCustomerAccount && collectionSheetCustomerAccount.getAccountId() != -1) {

            SaveCollectionSheetCustomerAccountDto saveCollectionSheetCustomerAccount = null;

            Integer accountId = collectionSheetCustomerAccount.getAccountId();

            if (loanAccountIdtoCustomerAccountIdForFirstClient
                    && (customerLevelId.compareTo(CustomerLevel.CLIENT.getValue()) == 0) && firstClient) {
                firstClientCustomerAccountId = accountId;
            }

            if (customerAccountIdtoLoanAccountIdForFirstClient
                    && (customerLevelId.compareTo(CustomerLevel.CLIENT.getValue()) == 0) && firstClient) {
                accountId = loan.getAccountId();
            }

            BigDecimal accountCollectionFee = new BigDecimal(collectionSheetCustomerAccount
                    .getTotalCustomerAccountCollectionFee());

            if (overpayFirstClientAccountCollectionFee
                    && (customerLevelId.compareTo(CustomerLevel.CLIENT.getValue()) == 0) && firstClient) {
                accountCollectionFee = new BigDecimal(1000000.00);
            }

            if (underpayFirstClientAccountCollectionFee
                    && (customerLevelId.compareTo(CustomerLevel.CLIENT.getValue()) == 0) && firstClient) {
                accountCollectionFee = new BigDecimal(1.45);
            }
            try {
                saveCollectionSheetCustomerAccount = new SaveCollectionSheetCustomerAccountDto(accountId,
                        collectionSheetCustomerAccount.getCurrencyId(), accountCollectionFee);
            } catch (SaveCollectionSheetException e) {
                throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
            }

            return saveCollectionSheetCustomerAccount;

        }
        return null;
    }

    private List<SaveCollectionSheetCustomerLoanDto> assembleSCSCustomerLoans(
            List<CollectionSheetCustomerLoanDto> collectionSheetCustomerLoans, Short customerLevelId,
            Boolean firstClient) {
        if (null != collectionSheetCustomerLoans && collectionSheetCustomerLoans.size() > 0) {

            Integer numberToCreate = 1;
            List<SaveCollectionSheetCustomerLoanDto> saveCollectionSheetCustomerLoans = new ArrayList<SaveCollectionSheetCustomerLoanDto>();
            Boolean firstLoan = true;
            for (CollectionSheetCustomerLoanDto collectionSheetCustomerLoan : collectionSheetCustomerLoans) {
                SaveCollectionSheetCustomerLoanDto saveCollectionSheetCustomerLoan = null;

                Integer accountId = collectionSheetCustomerLoan.getAccountId();
                BigDecimal loanRepayment = new BigDecimal(collectionSheetCustomerLoan.getTotalRepaymentDue());
                BigDecimal loanDisbursement = new BigDecimal(collectionSheetCustomerLoan.getTotalDisbursement());

                Short accountCurrencyId = collectionSheetCustomerLoan.getCurrencyId();

                if (firstLoan && (customerLevelId.compareTo(CustomerLevel.CLIENT.getValue()) == 0) && firstClient) {
                    if (duplicateFirstClientLoanAccount) {
                        numberToCreate = 2;
                        duplicateFirstClientLoanAccount = false;
                    }
                    if (overpayLoan) {
                        loanRepayment = loanRepayment.add(new BigDecimal(1000000.00));
                        loanDisbursement = BigDecimal.ZERO;
                    }
                    if (normalLoanRepayment) {
                        loanRepayment = loanRepayment.add(new BigDecimal(15.00));
                        loanDisbursement = BigDecimal.ZERO;
                    }
                    if (invalidDisbursalAmountFirstClient) {
                        loanDisbursement = new BigDecimal(1.10);
                    }

                    if (loanInvalidCurrency != null) {
                        accountCurrencyId = loanInvalidCurrency;
                    }
                    if (loanAccountIdtoCustomerAccountIdForFirstClient) {
                        accountId = firstClientCustomerAccountId;
                    }
                    if (loanAccountIdInvalid) {
                        accountId = nonExistingId;
                    }
                }
                for (Integer i = 0; i < numberToCreate; i++) {
                    try {
                        saveCollectionSheetCustomerLoan = new SaveCollectionSheetCustomerLoanDto(accountId,
                                accountCurrencyId, loanRepayment, loanDisbursement);
                    } catch (SaveCollectionSheetException e) {
                        throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
                    }
                    saveCollectionSheetCustomerLoans.add(saveCollectionSheetCustomerLoan);
                }
                firstLoan = false;
            }

            return saveCollectionSheetCustomerLoans;
        }
        return null;
    }

    private List<SaveCollectionSheetCustomerSavingDto> assembleSCSCustomerSavings(
            List<CollectionSheetCustomerSavingDto> collectionSheetCustomerSavings) {

        if (null != collectionSheetCustomerSavings && collectionSheetCustomerSavings.size() > 0) {

            List<SaveCollectionSheetCustomerSavingDto> saveCollectionSheetCustomerSavings = new ArrayList<SaveCollectionSheetCustomerSavingDto>();
            for (CollectionSheetCustomerSavingDto collectionSheetCustomerSaving : collectionSheetCustomerSavings) {
                SaveCollectionSheetCustomerSavingDto saveCollectionSheetCustomerSaving = null;

                Short savingsCurrencyId = collectionSheetCustomerSaving.getCurrencyId();
                if (savingsCurrencyId == null) {
                    savingsCurrencyId = currency.getCurrencyId();
                }
                try {
                    saveCollectionSheetCustomerSaving = new SaveCollectionSheetCustomerSavingDto(
                            collectionSheetCustomerSaving.getAccountId(), savingsCurrencyId,
                            collectionSheetCustomerSaving.getDepositDue(), new BigDecimal(0.0));
                } catch (SaveCollectionSheetException e) {
                    throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
                }

                saveCollectionSheetCustomerSavings.add(saveCollectionSheetCustomerSaving);
            }
            return saveCollectionSheetCustomerSavings;
        }
        return null;
    }

    private SaveCollectionSheetCustomerSavingDto assembleOptionalGroupIndividualSavingsAccount() {

        SaveCollectionSheetCustomerSavingDto groupIndividualSavingsAccount = null;

        try {
            groupIndividualSavingsAccount = new SaveCollectionSheetCustomerSavingDto(99999, currency.getCurrencyId(),
                    BigDecimal.ZERO, BigDecimal.ZERO);
        } catch (SaveCollectionSheetException e) {
            throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
        }

        return groupIndividualSavingsAccount;
    }

    private SaveCollectionSheetCustomerLoanDto assembleOptionalGroupLoanAccount(Integer loanAccountId) {

        SaveCollectionSheetCustomerLoanDto saveCollectionSheetCustomerLoan = null;

        try {
            saveCollectionSheetCustomerLoan = new SaveCollectionSheetCustomerLoanDto(loanAccountId, currency
                    .getCurrencyId(), BigDecimal.ZERO, new BigDecimal(1000.00));
        } catch (SaveCollectionSheetException e) {
            throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
        }

        return saveCollectionSheetCustomerLoan;
    }

    private SaveCollectionSheetCustomerSavingDto assembleOptionalSavingsAccount(Integer accountId) {
        SaveCollectionSheetCustomerSavingDto savingsAccount = null;

        try {
            savingsAccount = new SaveCollectionSheetCustomerSavingDto(accountId, currency.getCurrencyId(),
                    BigDecimal.ZERO, new BigDecimal(1000.00));
        } catch (SaveCollectionSheetException e) {
            throw new MifosRuntimeException(e.printInvalidSaveCollectionSheetReasons());
        }

        return savingsAccount;
    }

    /*
     *
     * methods to configure invalid entries below
     */
    /**
     * The first client in this sample collection sheet hierarchy will be given an id that doesn't exist
     */
    public void setFirstClientDoesntExist() {
        this.firstClientExists = false;
    }

    /**
     * The first client in this sample collection sheet hierarchy will be given an AttendanceType as specified
     */
    public void setFirstClientAttendanceType(Short attendanceType) {
        this.firstClientAttendanceType = attendanceType;
    }

    /**
     * The first group in this sample collection sheet hierarchy will be given an AttendanceType as specified
     */
    public void setFirstGroupAttendanceType(short attendanceType) {
        this.firstGroupAttendanceType = attendanceType;
    }

    /**
     * The first group in this sample collection sheet hierarchy will have an individual savings account added to it
     */
    public void setIndividualSavingsAccountUnderFirstGroup() {
        this.individualSavingsAccountUnderFirstGroup = true;
    }

    /**
     * The first client in this sample collection sheet hierarchy will have its parent's id set to a non-existing value
     */
    public void setFirstClientParentIdInvalid() {
        this.firstClientParentIdInvalid = true;
    }

    /**
     * Another collection sheet hierarchy will be created and a client from it will be added to this sample collection
     * sheet hierarchy
     */
    public void addAnotherClientFromADifferentCenter() throws Exception {
        nonCenterClient = getAnotherClientFromAnotherCenter();
    }

    /**
     * The loan account attached to the first client in this sample collection sheet hierarchy will have its currencyId
     * set to an invalid value
     */
    public void setLoanAccountInvalidCurrency() {
        Integer defaultCurrencyId = Integer.valueOf(currency.getCurrencyId().toString()) + 1;
        this.loanInvalidCurrency = Short.valueOf(defaultCurrencyId.toString());
    }

    /**
     * The loan account attached to the first client in this sample collection sheet hierarchy will have its id set to
     * an non-existing value
     */
    public void setLoanAccountIdInvalid() {
        this.loanAccountIdInvalid = true;
    }

    /**
     * The loan account attached to the first client in this sample collection sheet hierarchy will have its status set
     * to cancelled
     */
    public void setLoanAccountCancelled() {
        this.loanAccountCancelled = true;
    }

    /**
     * The first group in this sample collection sheet hierarchy will have a loan account added to it with an account id
     * equal to the loan account belonging to the first client in this sample collection sheet hierarchy
     */
    public void setLoanAccountUnderFirstGroupWithFirstClientLoanId() {
        this.loanAccountUnderFirstGroupWithFirstClientLoanId = true;
    }

    /**
     * The first client in this sample collection sheet hierarchy will have its customer account id set to equal its
     * loan account id
     */
    public void setCustomerAccountIdtoLoanAccountIdForFirstClient() {
        this.customerAccountIdtoLoanAccountIdForFirstClient = true;
    }

    /**
     * The first client in this sample collection sheet hierarchy will have its loan account id set to equal its
     * customer account id
     */
    public void setLoanAccountIdtoCustomerAccountIdForFirstClient() {
        this.loanAccountIdtoCustomerAccountIdForFirstClient = true;
    }

    /**
     * The first client in this sample collection sheet hierarchy will have a savings account added with the savings
     * account id set to equal its loan account id
     */
    public void setSavingsAccountIdtoLoanAccountIdForFirstClient() {
        this.savingsAccountIdtoLoanAccountIdForFirstClient = true;
    }

    /**
     * The first client's loan account will have a repayment set that is greater than the outstanding loan amount
     */
    public void setOverpayLoan() {
        this.overpayLoan = true;
    }

    /**
     * The first client will be duplicated
     */
    public void setDuplicateFirstClient() {
        this.duplicateFirstClient = true;
    }

    /**
     * The first client's loan account will be duplicated
     */
    public void setDuplicateFirstClientLoanAccount() {
        this.duplicateFirstClientLoanAccount = true;
    }

    public void setOverpayFirstClientAccountCollectionFee() {
        this.overpayFirstClientAccountCollectionFee = true;
    }

    public void setUnderpayFirstClientAccountCollectionFee() {
        this.underpayFirstClientAccountCollectionFee = true;
    }

    public void setInvalidDisbursalAmountFirstClient() {
        this.invalidDisbursalAmountFirstClient = true;
    }

    public void setInvalidTransactionDate() {
        this.invalidTransactionDate = true;
    }

    public void setNormalLoanRepayment() {
        this.normalLoanRepayment = true;
    }

}


text:
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.browser.search_resumption;

import org.chromium.base.UserData;
import org.chromium.chrome.browser.flags.ChromeFeatureList;
import org.chromium.chrome.browser.tab.Tab;
import org.chromium.components.embedder_support.util.UrlUtilities;
import org.chromium.components.omnibox.AutocompleteMatch;
import org.chromium.url.GURL;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Helper class for the search suggestion module which shows search suggestions on NTP.
 */
public class SearchResumptionUserData implements UserData {
    // The cached search suggestion results.
    static class SuggestionResult {
        private GURL mLastUrlToTrack;
        private String[] mSuggestionTexts;
        private GURL[] mSuggestionUrls;
        private List<AutocompleteMatch> mSuggestions;

        SuggestionResult(GURL gurl, String[] suggestionTexts, GURL[] suggestionUrls) {
            mLastUrlToTrack = gurl;
            mSuggestionTexts = suggestionTexts;
            mSuggestionUrls = suggestionUrls;
            mSuggestions = null;
        }

        public SuggestionResult(GURL urlToTrack, List<AutocompleteMatch> suggestions) {
            mLastUrlToTrack = urlToTrack;
            mSuggestions = suggestions;
            mSuggestionTexts = null;
            mSuggestionUrls = null;
        }

        GURL getLastUrlToTrack() {
            return mLastUrlToTrack;
        }
        String[] getSuggestionTexts() {
            return mSuggestionTexts;
        }
        GURL[] getSuggestionUrls() {
            return mSuggestionUrls;
        }
        List<AutocompleteMatch> getSuggestions() {
            return mSuggestions;
        }
    }

    private static final Class<SearchResumptionUserData> USER_DATA_KEY =
            SearchResumptionUserData.class;
    private long mTimeStampMs = -1;
    private SuggestionResult mCachedSuggestions;

    /**
     * Static class that implements the initialization-on-demand holder idiom.
     */
    private static class LazyHolder {
        static final SearchResumptionUserData INSTANCE = new SearchResumptionUserData();
    }

    /**
     * Gets the singleton instance for the SearchResumptionUserData.
     */
    public static SearchResumptionUserData getInstance() {
        return SearchResumptionUserData.LazyHolder.INSTANCE;
    }

    /**
     * Caches the fetched search suggestions.
     * @param tab: The tab which the suggestions live.
     * @param urlToTrack: The URL which the search suggestions are coming from.
     * @param suggestionTexts: The content texts of suggestions.
     * @param suggestionUrls: The URLs of the suggestions.
     */
    public void cacheSuggestions(
            Tab tab, GURL urlToTrack, String[] suggestionTexts, GURL[] suggestionUrls) {
        if (tab == null || !UrlUtilities.isNTPUrl(tab.getUrl())) return;

        SearchResumptionUserData searchResumptionUserData = get(tab);
        if (searchResumptionUserData == null) {
            searchResumptionUserData = new SearchResumptionUserData();
        }
        searchResumptionUserData.mTimeStampMs = System.currentTimeMillis();
        searchResumptionUserData.mCachedSuggestions =
                new SuggestionResult(urlToTrack, suggestionTexts, suggestionUrls);
        tab.getUserDataHost().setUserData(USER_DATA_KEY, searchResumptionUserData);
    }

    /**
     * Caches the fetched search suggestions.
     * @param tab The tab which the suggestions live.
     * @param urlToTrack: The URL which the search suggestions are coming from.
     * @param suggestions: The suggestions fetched using Autocompelete API.
     */
    public void cacheSuggestions(Tab tab, GURL urlToTrack, List<AutocompleteMatch> suggestions) {
        if (tab == null || !UrlUtilities.isNTPUrl(tab.getUrl())) return;

        SearchResumptionUserData searchResumptionUserData = get(tab);
        if (searchResumptionUserData == null) {
            searchResumptionUserData = new SearchResumptionUserData();
        }
        searchResumptionUserData.mTimeStampMs = System.currentTimeMillis();
        searchResumptionUserData.mCachedSuggestions = new SuggestionResult(urlToTrack, suggestions);
        tab.getUserDataHost().setUserData(USER_DATA_KEY, searchResumptionUserData);
    }

    /**
     * Returns the last cached search suggestions, null if the UserData isn't set or expired.
     */
    public SuggestionResult getCachedSuggestions(Tab tab) {
        SearchResumptionUserData searchResumptionUserData = get(tab);
        return searchResumptionUserData == null ? null
                                                : searchResumptionUserData.mCachedSuggestions;
    }

    /**
     * Returns an instance of SearchResumptionUserData if exists and isn't expired, null otherwise.
     * If the data is expired, remove it.
     */
    private static SearchResumptionUserData get(Tab tab) {
        SearchResumptionUserData searchResumptionUserData =
                tab.getUserDataHost().getUserData(USER_DATA_KEY);
        if (searchResumptionUserData == null) return null;

        assert searchResumptionUserData.mTimeStampMs != -1;
        if (searchResumptionUserData.isCachedResultExpired()) {
            tab.getUserDataHost().removeUserData(USER_DATA_KEY);
            return null;
        }
        return searchResumptionUserData;
    }

    /**
     * @return whether the cached results has expired.
     */
    private boolean isCachedResultExpired() {
        return (TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - mTimeStampMs))
                >= ChromeFeatureList.getFieldTrialParamByFeatureAsInt(
                        ChromeFeatureList.SEARCH_RESUMPTION_MODULE_ANDROID,
                        SearchResumptionModuleUtils.TAB_EXPIRATION_TIME_PARAM,
                        SearchResumptionModuleUtils.LAST_TAB_EXPIRATION_TIME_SECONDS);
    }
}


text:
  Gommersdorf est
       un village
       géographiquement positionné dans le département de Haut-Rhin en Alsace. Elle comptait 367 habitants en 2008.

La ville compte quelques  aménagements, elle dispose, entre autres, de un terrain de tennis et un terrain de sport.

Le nombre de logements, à Gommersdorf, se décomposait en 2011 en 28 appartements et 136 maisons soit
 un marché plutôt équilibré.

À proximité de Gommersdorf sont localisées les communes de
Retzwiller à 2 km, 655 habitants,
Wolfersdorf localisée à 1 km, 380 habitants,
Dannemarie à 1 km, 2 299 habitants,
Manspach localisée à 3 km, 514 habitants,
Elbach localisée à 3 km, 270 habitants,
Altenach localisée à 3 km, 382 habitants,
 entre autres. De plus, Gommersdorf est située à seulement 19 km de Mulhouse.

Si vous pensez emmenager à Gommersdorf, vous pourrez facilement trouver une maison à vendre.


text:
class PurchaseOrder < ActiveRecord::Base
  include TransactionAccountable

  belongs_to :supplier

  has_many  :purchase_order_variants
  has_many  :variants, :through => :purchase_order_variants

  has_many  :batches,             :as => :batchable
  has_many  :transaction_ledgers, :as => :accountable

  validates :invoice_number,  :presence => true, :length => { :maximum => 200 }
  validates :ordered_at,      :presence => true
  validates :total_cost,      :presence => true
  #validates :is_received,     :presence => true

  accepts_nested_attributes_for :purchase_order_variants,
                                :reject_if      => lambda { |attributes| attributes['cost'].blank? && attributes['quantity'].blank? },
                                :allow_destroy  => true

  INCOMPLETE  = 'incomplete'
  PENDING     = 'pending'
  RECEIVED    = 'received'
  STATES      = [PENDING, INCOMPLETE, RECEIVED]

  state_machine :state, :initial => :pending do
    state :pending
    state :incomplete
    state :received

    after_transition :on => :complete, :do => [:pay_for_order, :receive_variants]

    event :complete do |purchase_order|
      transition all => :received
    end

    event :mark_as_complete do
      transition all => :received
    end
  end

  # in the admin form this is the method called when the form is submitted, The method sets
  # the PO to complete, pays for the order in the accounting peice and adds the inventory to stock
  #
  # @param [String] value for set_keywords in a products form
  # @return [none]
  def receive_po=(answer)

    if (answer == 'true' || answer == '1') && (state != RECEIVED)
      self.complete!
    end
  end

  # in the admin form this is the method called when the form is created, The method
  # determines if the order has already been received
  #
  # @return [Boolean]
  def receive_po
    (state == RECEIVED)
  end

  # called by state machine after the PO is complete.  adds the inventory to stock
  #
  # @param [none]
  # @return [none]
  def receive_variants
    po_variants = PurchaseOrderVariant.where(:purchase_order_id => self.id).lock("LOCK IN SHARE MODE").all
    po_variants.each do |po_variant|
      po_variant.receive! unless po_variant.is_received?
    end
  end

  # returns "Yes" if the PO has been received, otherwise "No"
  #
  # @param [none]
  # @return [String]  "Yes" or "No"
  def display_received
    receive_po ? 'Yes' : 'No'
  end

  def display_estimated_arrival_on
    estimated_arrival_on? ? estimated_arrival_on.to_s(:format => :us_date) : ""
  end

  # returns "the tracking #" if the tracking # exists, otherwise "N/A"
  #
  # @param [none]
  # @return [String]  "Yes" or "No"
  def display_tracking_number
    tracking_number? ? tracking_number : 'N/A'
  end

  # returns "Suppliers name" if the supplier exists, otherwise "N/A"
  #
  # @param [none]
  # @return [String]  "Yes" or "No"
  def supplier_name
    supplier.name rescue 'N/A'
  end

  def receive_order_from_credit
      batch = self.batches.create()
      transaction = ReceivePurchaseOrder.new_expensed(self, total_cost)
      batch.transactions.push(transaction)
      batch.save
  end

  def pay_for_order
    now = Time.zone.now
    if self.batches.empty?
        batch = self.batches.create()
        transaction = ReceivePurchaseOrder.new_direct_payment(self, total_cost, now)
        batch.transactions.push(transaction)
        batch.save
    else # thus we are paying after having received the item from credit
      batch       = batches.first
      transaction = ReceivePurchaseOrder.new_expensed_payment(self, total_cost, now)
      batch.transactions.push(transaction)
      batch.save
    end
  end

  # paginated results from the admin PurchaseOrder grid
  #
  # @param [Optional params]
  # @return [ Array[PurchaseOrder] ]
  def self.admin_grid(params = {})
    grid = includes(:supplier)
    grid = grid.where("suppliers.name LIKE ?",                  "#{params[:supplier_name]}%")   if params[:supplier_name].present?
    grid = grid.where("purchase_orders.invoice_number LIKE ?",  "#{params[:invoice_number]}%")  if params[:invoice_number].present?
    grid = grid.where("purchase_orders.tracking_number LIKE ?", "#{params[:tracking_number]}%") if params[:tracking_number].present?
    grid
  end

  # paginated results from the admin PurchaseOrder grid for PO to receive
  #
  # @param [Optional params]
  # @return [ Array[PurchaseOrder] ]
  def self.receiving_admin_grid(params = {})
    grid = where(['purchase_orders.state != ?', PurchaseOrder::RECEIVED])#.where("suppliers.name = ?", params[:name])
    grid = grid.includes([:supplier, :purchase_order_variants])
    grid = grid.where("suppliers.name LIKE ?",                  "#{params[:supplier_name]}%")   if params[:supplier_name].present?
    grid = grid.where("purchase_orders.invoice_number LIKE ?",  "#{params[:invoice_number]}%")  if params[:invoice_number].present?
    grid = grid.where("purchase_orders.tracking_number LIKE ?", "#{params[:tracking_number]}%") if params[:tracking_number].present?
    grid
  end
end


text:
package topotools

import (
	"fmt"
	"net"
	"sort"
	"strconv"
	"strings"
	"sync"

	"golang.org/x/net/context"

	log "github.com/golang/glog"
	"github.com/youtube/vitess/go/netutil"
	"github.com/youtube/vitess/go/vt/concurrency"
	"github.com/youtube/vitess/go/vt/topo"
	"github.com/youtube/vitess/go/vt/topo/topoproto"

	pb "github.com/youtube/vitess/go/vt/proto/topodata"
)

// TabletNode is the representation of a tablet in the db topology.
// It can be constructed from a Tablet object, or from an EndPoint.
type TabletNode struct {
	Host  string
	Alias *pb.TabletAlias
	Port  int32
}

// ShortName returns a displayable representation of the host name.
// If the host is an IP address instead of a name, it is not shortened.
func (tn *TabletNode) ShortName() string {
	if net.ParseIP(tn.Host) != nil {
		return netutil.JoinHostPort(tn.Host, tn.Port)
	}

	hostPart := strings.SplitN(tn.Host, ".", 2)[0]
	if tn.Port == 0 {
		return hostPart
	}
	return netutil.JoinHostPort(hostPart, tn.Port)
}

func newTabletNodeFromTabletInfo(ti *topo.TabletInfo) *TabletNode {
	if err := topo.TabletValidatePortMap(ti.Tablet); err != nil {
		log.Errorf("ValidatePortmap(%v): %v", ti.Alias, err)
	}
	return &TabletNode{
		Host:  ti.Hostname,
		Port:  ti.PortMap["vt"],
		Alias: ti.Alias,
	}
}

func newTabletNodeFromEndPoint(ep *pb.EndPoint, cell string) *TabletNode {
	return &TabletNode{
		Host: ep.Host,
		Alias: &pb.TabletAlias{
			Uid:  ep.Uid,
			Cell: cell,
		},
		Port: ep.PortMap[topo.DefaultPortName],
	}
}

// TabletNodesByType maps tablet types to slices of tablet nodes.
type TabletNodesByType struct {
	TabletType pb.TabletType
	Nodes      []*TabletNode
}

// ShardNodes represents all tablet nodes for a shard, indexed by tablet type.
type ShardNodes struct {
	Name        string
	TabletNodes []*TabletNodesByType
	ServedTypes []pb.TabletType
	Tag         interface{} // Tag is an arbitrary value manageable by a plugin.
}

type numericShardNodesList []*ShardNodes

// Len is part of sort.Interface
func (nsnl numericShardNodesList) Len() int {
	return len(nsnl)
}

// Less is part of sort.Interface
func (nsnl numericShardNodesList) Less(i, j int) bool {
	// This panics, so it shouldn't be called unless all shard
	// names can be converted to integers.
	ii, err := strconv.Atoi(nsnl[i].Name)
	if err != nil {
		panic("bad numeric shard: " + nsnl[i].Name)
	}

	jj, err := strconv.Atoi(nsnl[j].Name)
	if err != nil {
		panic("bad numeric shard" + nsnl[j].Name)
	}
	return ii < jj

}

// Swap is part of sort.Interface
func (nsnl numericShardNodesList) Swap(i, j int) {
	nsnl[i], nsnl[j] = nsnl[j], nsnl[i]
}

type rangeShardNodesList []*ShardNodes

// Len is part of sort.Interface
func (rsnl rangeShardNodesList) Len() int {
	return len(rsnl)
}

// Less is part of sort.Interface
func (rsnl rangeShardNodesList) Less(i, j int) bool {
	return rsnl[i].Name < rsnl[j].Name
}

// Swap is part of sort.Interface
func (rsnl rangeShardNodesList) Swap(i, j int) {
	rsnl[i], rsnl[j] = rsnl[j], rsnl[i]
}

// KeyspaceNodes represents all tablet nodes in a keyspace.
type KeyspaceNodes struct {
	ShardNodes []*ShardNodes // sorted by shard name
	ServedFrom map[string]string
}

func newKeyspaceNodes() *KeyspaceNodes {
	return &KeyspaceNodes{
		ServedFrom: make(map[string]string),
	}
}

func (ks *KeyspaceNodes) hasOnlyNumericShardNames() bool {
	for _, shardNodes := range ks.ShardNodes {
		if _, err := strconv.Atoi(shardNodes.Name); err != nil {
			return false
		}
	}
	return true
}

// TabletTypes returns a slice of tablet type names this ks
// contains.
func (ks KeyspaceNodes) TabletTypes() []pb.TabletType {
	var contained []pb.TabletType
	for _, t := range topoproto.AllTabletTypes {
		if ks.HasType(t) {
			contained = append(contained, t)
		}
	}
	return contained
}

// HasType returns true if ks has any tablets with the named type.
func (ks KeyspaceNodes) HasType(tabletType pb.TabletType) bool {
	for _, shardNodes := range ks.ShardNodes {
		for _, tabletNodes := range shardNodes.TabletNodes {
			if tabletNodes.TabletType == tabletType {
				return true
			}
		}
	}
	return false
}

// Topology is the entire set of tablets in the topology.
type Topology struct {
	Assigned map[string]*KeyspaceNodes // indexed by keyspace name
	Partial  bool
}

// DbTopology returns the Topology for the topo server.
func DbTopology(ctx context.Context, ts topo.Server) (*Topology, error) {
	topology := &Topology{
		Assigned: make(map[string]*KeyspaceNodes),
		Partial:  false,
	}

	tabletInfos, err := GetAllTabletsAcrossCells(ctx, ts)
	switch err {
	case nil:
		// we're good, no error
	case topo.ErrPartialResult:
		// we got a partial result
		topology.Partial = true
	default:
		// we got no result at all
		return nil, err
	}

	assigned := make(map[string]map[string][]*TabletNodesByType)
	for _, ti := range tabletInfos {
		tablet := newTabletNodeFromTabletInfo(ti)
		if _, ok := assigned[ti.Keyspace]; !ok {
			assigned[ti.Keyspace] = make(map[string][]*TabletNodesByType)
		}
		var tabletNode *TabletNodesByType
		for _, tabletNodes := range assigned[ti.Keyspace][ti.Shard] {
			if tabletNodes.TabletType == ti.Type {
				tabletNode = tabletNodes
				break
			}
		}
		if tabletNode == nil {
			tabletNode = &TabletNodesByType{
				TabletType: ti.Type,
			}
			assigned[ti.Keyspace][ti.Shard] = append(assigned[ti.Keyspace][ti.Shard], tabletNode)
		}
		tabletNode.Nodes = append(tabletNode.Nodes, tablet)
	}

	for keyspace, shardMap := range assigned {
		kn := newKeyspaceNodes()
		for shard, nodes := range shardMap {
			kn.ShardNodes = append(kn.ShardNodes, &ShardNodes{
				Name:        shard,
				TabletNodes: nodes,
			})
		}
		if kn.hasOnlyNumericShardNames() {
			sort.Sort(numericShardNodesList(kn.ShardNodes))
		} else {
			sort.Sort(rangeShardNodesList(kn.ShardNodes))
		}
		topology.Assigned[keyspace] = kn
	}
	return topology, nil
}

// ServingGraph contains the representation of the serving graph
// for a given cell.
type ServingGraph struct {
	Cell      string
	Keyspaces map[string]*KeyspaceNodes // indexed by keyspace name
	Errors    []string                  // collected during creation
}

// DbServingGraph returns the ServingGraph for the given cell.
func DbServingGraph(ctx context.Context, ts topo.Server, cell string) (servingGraph *ServingGraph) {
	servingGraph = &ServingGraph{
		Cell:      cell,
		Keyspaces: make(map[string]*KeyspaceNodes),
	}
	rec := concurrency.AllErrorRecorder{}

	keyspaces, err := ts.GetSrvKeyspaceNames(ctx, cell)
	if err != nil {
		servingGraph.Errors = append(servingGraph.Errors, fmt.Sprintf("GetSrvKeyspaceNames failed: %v", err))
		return
	}
	wg := sync.WaitGroup{}
	servingTypes := []pb.TabletType{pb.TabletType_MASTER, pb.TabletType_REPLICA, pb.TabletType_RDONLY}
	for _, keyspace := range keyspaces {
		kn := newKeyspaceNodes()
		servingGraph.Keyspaces[keyspace] = kn
		wg.Add(1)
		go func(keyspace string, kn *KeyspaceNodes) {
			defer wg.Done()

			ks, err := ts.GetSrvKeyspace(ctx, cell, keyspace)
			if err != nil {
				rec.RecordError(fmt.Errorf("GetSrvKeyspace(%v, %v) failed: %v", cell, keyspace, err))
				return
			}
			for _, sf := range ks.ServedFrom {
				kn.ServedFrom[strings.ToLower(sf.TabletType.String())] = sf.Keyspace
			}

			displayedShards := make(map[string]bool)
			for _, partitionTabletType := range servingTypes {
				kp := topoproto.SrvKeyspaceGetPartition(ks, partitionTabletType)
				if kp == nil {
					continue
				}
				for _, srvShard := range kp.ShardReferences {
					shard := srvShard.Name
					if displayedShards[shard] {
						continue
					}
					displayedShards[shard] = true

					sn := &ShardNodes{
						Name: shard,
					}
					kn.ShardNodes = append(kn.ShardNodes, sn)
					wg.Add(1)
					go func(shard string, sn *ShardNodes) {
						defer wg.Done()
						tabletTypes, err := ts.GetSrvTabletTypesPerShard(ctx, cell, keyspace, shard)
						if err != nil {
							rec.RecordError(fmt.Errorf("GetSrvTabletTypesPerShard(%v, %v, %v) failed: %v", cell, keyspace, shard, err))
							return
						}
						for _, tabletType := range tabletTypes {
							endPoints, _, err := ts.GetEndPoints(ctx, cell, keyspace, shard, tabletType)
							if err != nil {
								rec.RecordError(fmt.Errorf("GetEndPoints(%v, %v, %v, %v) failed: %v", cell, keyspace, shard, tabletType, err))
								continue
							}
							for _, endPoint := range endPoints.Entries {
								var tabletNode *TabletNodesByType
								for _, t := range sn.TabletNodes {
									if t.TabletType == tabletType {
										tabletNode = t
										break
									}
								}
								if tabletNode == nil {
									tabletNode = &TabletNodesByType{
										TabletType: tabletType,
									}
									sn.TabletNodes = append(sn.TabletNodes, tabletNode)
								}
								tabletNode.Nodes = append(tabletNode.Nodes, newTabletNodeFromEndPoint(endPoint, cell))
							}
						}
					}(shard, sn)
				}
			}
		}(keyspace, kn)
	}
	wg.Wait()
	servingGraph.Errors = rec.ErrorStrings()
	return
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>The bus</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//elte.me/themes/casper/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//elte.me/themes/casper/assets/css/screen.css?v=1.0.0" />
    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:300,700,700italic,300italic|Open+Sans:700,400" />

    <link rel="canonical" href="http://elte.me/2013/04/26/The-bus.html" />

    <meta property="og:site_name" content="Elte Hupkes" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="The bus" />
    <meta property="og:description" content="Now that I can&#8217;t ride my bicycle (a big deal here in Amsterdam), I have to take the bus to SRXP every day. I have to take two separate buses to get where I want. The funny thing..." />
    <meta property="og:url" content="http://elte.me/2013/04/26/The-bus.html" />
    <meta property="article:published_time" content="2013-04-25T22:00:00.000Z" />
    <meta property="article:modified_time" content="2015-03-29T10:52:41.975Z" />
    <meta property="article:tag" content="injury" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="The bus" />
    <meta name="twitter:description" content="Now that I can&#8217;t ride my bicycle (a big deal here in Amsterdam), I have to take the bus to SRXP every day. I have to take two separate buses to get where I want. The funny thing..." />
    <meta name="twitter:url" content="http://elte.me/2013/04/26/The-bus.html" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Elte Hupkes" href="http://elte.me/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

        Home

The bus

                <time class="post-date" datetime="2013-04-26">26 April 2013</time>  on injury

Now that I can’t ride my bicycle (a big deal here in Amsterdam), I have to take the bus to SRXP
every day. I have to take two separate buses to get where I want. The funny thing is, it does not matter in which
direction I take them. Both go back and forth between two locations where their lines intersect, the points where I
have to get on / off are about in the middle. So whichever bus I take first, I get to take in whichever direction I
like.

I appreciate these little quirks. Unfortunately I do not appreciate having to ride the bus.

                Elte Hupkes's Picture

Elte Hupkes

Read more posts by this author.

                    Amsterdam
                    http://elte.me

Share this post

                    Twitter

                    Facebook

                    Google+

          Please enable JavaScript to view the comments powered by Disqus.
          comments powered by Disqus

Elte Hupkes © 2015

My stuff on GitHub

Watch me on YouTube

Hear me on SoundCloud

My company SRXP

Proudly published with HubPress


text:
module.exports = ImageLoaderItem;

function ImageLoaderItem(options)
{
    'use strict';

    var STATUS = {
        PENDING: "pending",
        LOADING: "loading",
        COMPLETE: "complete",
        FAILED: "failed"
    };

    var me = this;

    var onLoadCallback;

    init();

    me.load = function(onLoad)
    {
        onLoadCallback = onLoad;

        setStatusLoading();

        me.tag.addEventListener('load', onLoadHandler);
        me.tag.addEventListener('error', onErrorHandler);

        me.tag.src = me.src;
    };

    me.isPending = function () { return me.status === STATUS.PENDING; };
    me.isComplete = function () { return me.status === STATUS.COMPLETE; };
    me.isLoading = function () { return me.status === STATUS.LOADING; };
    me.isFailed = function () { return me.status === STATUS.FAILED; };

    function init()
    {
        setProperties();
        setStatusPending();
    }

    function setProperties()
    {
        for(var property in options)
        {
            me[property] = options[property];
        }

        me.tag = document.createElement("img");
    }

    function setStatusFailed() { me.status = STATUS.FAILED; }
    function setStatusComplete() { me.status = STATUS.COMPLETE; }
    function setStatusLoading() { me.status = STATUS.LOADING; }
    function setStatusPending() { me.status = STATUS.PENDING; }

    function removeListeners()
    {
        me.tag.removeEventListener('load', onLoadHandler);
        me.tag.removeEventListener('error', onErrorHandler);
    }

    function onLoadHandler(event)
    {
        if (ImageLoaderItem.simulationDelayMin)
        {
            setTimeout(function()
            {
                finalizeOnLoad();

            }, calculateSimulationDelay());
        }
        else
        {
            finalizeOnLoad();
        }
    }

    function onErrorHandler(event)
    {
        if (ImageLoaderItem.simulationDelayMin)
        {
            setTimeout(function()
            {
                finalizeOnError();

            }, calculateSimulationDelay());
        }
        else
        {
            finalizeOnError();
        }
    }

    function finalizeOnLoad()
    {
        removeListeners();
        setStatusComplete();
        onLoadCallback(me);
        onLoadCallback = undefined;
    }

    function finalizeOnError()
    {
        removeListeners();
        me.tag = undefined;
        setStatusFailed();
        onLoadCallback(me);
        onLoadCallback = undefined;
    }

    function calculateSimulationDelay()
    {
        var max = ImageLoaderItem.simulationDelayMax;
        var min = ImageLoaderItem.simulationDelayMin;

        return Math.floor(Math.random() * (max - min) + min);
    }

    return this;
}

ImageLoaderItem.setSimulationDelays = function(min, max)
{
    var delayMin = min;
    var delayMax = max;

    if (delayMin && !delayMax)
    {
        delayMax = delayMin;
    }
    else if (delayMax && !delayMin)
    {
        delayMin = delayMax;
    }

    ImageLoaderItem.simulationDelayMin = delayMin;
    ImageLoaderItem.simulationDelayMax = delayMax;
};


text:
class BackpopulateSlugOnUsers < ActiveRecord::Migration
  def up
    User.find_each(&:save)
  end

  def down
  end
end


text:
import glob
import os
import sys
import re
from settings import nodecrypt
from animolite.filetools import decrypt, createandwrite
from animolite.binded import unbind

def dump(gamedir='.'):
    running_dir = os.getcwd()
    os.chdir(gamedir)
    datafiles = glob.glob('data/**', recursive=True)

    for filepath in datafiles:
        if os.path.isfile(filepath) and not filepath.startswith(tuple(nodecrypt)):
            print("Decrypting {}".format(filepath))

            data_in = open(filepath, "rb").read()
            decrypt_path = filepath.lower()
            data_out = decrypt(data_in, decrypt_path)

            outfilepath = os.path.join(running_dir, '_decrypted', filepath.lstrip("data" + os.path.sep))
            if filepath.endswith("binded"):
                binded_dir = re.sub('\d+\.binded$', '.binded', outfilepath)
                for bindedfile in unbind(data_out):
                    bf_name = bindedfile[0]
                    bf_data = bindedfile[1]
                    out_path = os.path.join(binded_dir, bf_name)
                    createandwrite(out_path, bf_data)
            else:
                createandwrite(outfilepath, data_out)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        dump(sys.argv[1])
    else:
        dump()


text:
require("cloud/app.js");

// Use Parse.Cloud.define to define as many cloud functions as you want.
// For example:
Parse.Cloud.define("hello", function(request, response) {
  response.success("Hello world!");
});

var API = "key-021d53cb5826444129f6c79c44b3ec66"
// REST API key from parse var API = "key-U5wFQ8aSYU08vHbHBGGhAA2bYQCianvGCHUInA7m"
var Domain = "sandbox9a1bd549307b4773b54d484a3039df14.mailgun.org"
var Mailgun = require('mailgun');
Mailgun.initialize(Domain, API);

Parse.Cloud.beforeSave("emailObject", function(request, response) {

    var text = "Submission Form From raj.com\n\n" +
        "Name: "+request.object.get("name") + "\n\n"+
        "Email: "+request.object.get("email") + "\n\n"+
         "file"+ request.object.get("photo.jpg")+ "\n\n"+
         "Company: "+request.object.get("company") + "\n\n"+
        "Message: \n"+request.object.get("comments");

    Mailgun.sendEmail({
            to: "vansia112@gmail.com",
            from: request.object.get("email"),
            subject: "Submission Form raj.com from: " + request.object.get("name"),
            text: text,
            attachment: request.object.get("photo.jpg")
        }, {
        success: function(httpResponse) {
            response.success();
        },
        error: function(httpResponse) {
            console.error(httpResponse);
            response.error("Uh oh, something went wrong");
        }
    });

});


text:
package eu.leads.processor.web;

import com.fasterxml.jackson.annotation.JsonAutoDetect;

import java.util.List;

/**
 * Created by vagvaz on 3/7/14.
 */
@JsonAutoDetect public class ObjectQuery {
  private String table;
  private String key;
  private List<String> attributes;

  public String getTable() {
    return table;
  }

  public void setTable(String table) {
    this.table = table;
  }

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public List<String> getAttributes() {
    return attributes;
  }

  public void setAttributes(List<String> attributes) {
    this.attributes = attributes;
  }

  @Override public String toString() {
    String result = table + ":" + key + " [ ";
    StringBuilder builder = new StringBuilder();
    for (String attribute : attributes) {
      builder.append(attribute + ", ");
    }
    return result + builder.toString() + " ]";
  }
}


text:
layout: post
title: "Beyond"
date: 2014-01-09 21:20:00
categories: blog
description: Beyond and beyond
---

<div class="wrapper" markdown="1">
And if you could go *beyond* everything you done?
</div>


text:
from django.conf import settings

def short_language_code(request):
    return {
        'SHORT_LANGUAGE_CODE': settings.SHORT_LANGUAGE_CODE,
    }

def google_settings(request):
    return {
        'GOOGLE_API_KEY': settings.GOOGLE_API_KEY,
        'GOOGLE_ANALYTICS': settings.GOOGLE_ANALYTICS,
        'GOOGLE_ANALYTICS_CODE': settings.GOOGLE_ANALYTICS_CODE,
    }


text:
---
layout: documentation
title: ReactiveX - Create operator
id: create
---

Operators

Creating

Create

Create

create an Observable from scratch by means of a function

  You can create an Observable from scratch by using the Create
  operator. You pass this operator a function that accepts the observer as its parameter. Write this
  function so that it behaves as an Observable — by calling the observer's onNext,
  onError, and onCompleted methods appropriately.

  A well-formed finite Observable must attempt to call either the observer's onCompleted
  method exactly once or its onError method exactly once, and must not thereafter
  attempt to call any of the observer's other methods.

See Also

Introduction to Rx: Create

Introduction to Rx: Generate

101 Rx Samples: Generate

RxJava Tutorial 03: Observable from, just, & create methods

Language-Specific Information:

  {% lang_operator RxClojure generator %}

     TBD

  {% endlang_operator %}

  {% lang_operator RxCpp %}

     TBD

  {% endlang_operator %}

  {% lang_operator RxGroovy create %}

      RxGroovy implements this operator as create.

Sample Code

def myObservable = Observable.create({ aSubscriber ->
  try {
    for (int i = 1; i < 1000000; i++) {
      if (aSubscriber.isUnsubscribed()) {
        return;
      }
      aSubscriber.onNext(i);
    }
    if (!aSubscriber.isUnsubscribed()) {
      aSubscriber.onCompleted();
    }
  } catch(Throwable t) {
    if (!aSubscriber.isUnsubscribed()) {
      aSubscriber.onError(t);
    }
  }
})

      It is good practice to check the observer's isUnsubscribed state so that your
      Observable can stop emitting items or doing expensive calculations when there is no longer an
      interested observer.

      create does not by default operate on any particular
      Scheduler.

Javadoc: create(OnSubscribe)

  {% endlang_operator %}

  {% lang_operator RxJava create %}

      RxJava implements this operator as create.

      It is good practice to check the observer's isUnsubscribed state from within the
      function you pass to create so that your Observable can stop emitting items or
      doing expensive calculations when there is no longer an interested observer.

Sample Code

Observable.create(new Observable.OnSubscribe<Integer>() {
    @Override
    public void call(Subscriber<? super Integer> observer) {
        try {
            if (!observer.isUnsubscribed()) {
                for (int i = 1; i < 5; i++) {
                    observer.onNext(i);
                }
                observer.onCompleted();
            }
        } catch (Exception e) {
            observer.onError(e);
        }
    }
 } ).subscribe(new Subscriber<Integer>() {
        @Override
        public void onNext(Integer item) {
            System.out.println("Next: " + item);
        }

        @Override
        public void onError(Throwable error) {
            System.err.println("Error: " + error.getMessage());
        }

        @Override
        public void onCompleted() {
            System.out.println("Sequence complete.");
        }
    });

Next: 1
Next: 2
Next: 3
Next: 4
Sequence complete.

      create does not by default operate on any particular
      Scheduler.

Javadoc: create(OnSubscribe)

  {% endlang_operator %}

  {% lang_operator RxJS create createWithDisposable generate generateWithAbsoluteTime generateWithRelativeTime %}

      RxJS implements this operator as create (there is also an alternate name for the
      same operator: createWithDisposable).

Sample Code

/* Using a function */
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
    return function () { console.log('disposed'); };
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Next: 42
Completed

/* Using a disposable */
var source = Rx.Observable.create(function (observer) {
    observer.onNext(42);
    observer.onCompleted();

    // Note that this is optional, you do not have to return this if you require no cleanup
    return Rx.Disposable.create(function () {
        console.log('disposed');
    });
});

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Next: 42
Completed

      create is found in the following distributions:

rx.js

rx.all.js

rx.all.compat.js

rx.compat.js

rx.lite.js

rx.lite.compat.js

      You can use the generate operator to create simple Observables that can generate their
      next emissions, and can determine when to terminate, based on the value of the previous emission. The
      basic form of generate takes four parameters:

the first item to emit

a function to test an item to determine whether to emit it (true) or terminate the
          Observable (false)

a function to generate the next item to test and emit based on the value of the previous item

a function to transform items before emitting them

      You can also pass in as an optional fifth parameter a Scheduler that
      generate will use to create and emit its sequence (it uses currentThread by
      default).

Sample Code

var source = Rx.Observable.generate(
    0,
    function (x) { return x < 3; },
    function (x) { return x + 1; },
    function (x) { return x; }
);

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Next: 0
Next: 1
Next: 2
Completed

      generate is found in the following distributions:

rx.js

rx.compat.js

rx.lite.js

rx.lite.compat.js

      You can use the generateWithRelativeTime operator to create simple Observables that can
      generate their next emissions, and can determine when to terminate, based on the value of the previous
      emission. The basic form of generateWithRelativeTime takes five parameters:

the first item to emit

a function to test an item to determine whether to emit it (true) or terminate the
          Observable (false)

a function to generate the next item to test and emit based on the value of the previous item

a function to transform items before emitting them

a function to indicate how long, in milliseconds, the generator should wait after the emission of
          the previous item before emitting this item

      You can also pass in as an optional sixth parameter a Scheduler that
      generate will use to create and emit its sequence (it uses currentThread by
      default).

Sample Code

var source = Rx.Observable.generateWithRelativeTime(
    1,
    function (x) { return x < 4; },
    function (x) { return x + 1; },
    function (x) { return x; },
    function (x) { return 100 * x; }
).timeInterval();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Next: {value: 1, interval: 100}
Next: {value: 2, interval: 200}
Next: {value: 3, interval: 300}
Completed

      generateWithRelativeTime is found in the following distributions:

rx.lite.js

rx.lite.compat.js

rx.time.js (requires rx.js or rx.compat.js)

      You can use the generateWithAbsoluteTime operator to create simple Observables that can
      generate their next emissions, and can determine when to terminate, based on the value of the previous
      emission. The basic form of generateWithAbsoluteTime takes five parameters:

the first item to emit

a function to test an item to determine whether to emit it (true) or terminate the
          Observable (false)

a function to generate the next item to test and emit based on the value of the previous item

a function to transform items before emitting them

a function to indicate at what time (expressed as a Date) the generator should emit the
          the new item

      You can also pass in as an optional sixth parameter a Scheduler that
      generate will use to create and emit its sequence (it uses currentThread by
      default).

Sample Code

var source = Rx.Observable.generate(
    1,
    function (x) { return x < 4; },
    function (x) { return x + 1; },
    function (x) { return x; },
    function (x) { return Date.now() + (100 * x); }
).timeInterval();

var subscription = source.subscribe(
    function (x) { console.log('Next: ' + x); },
    function (err) { console.log('Error: ' + err); },
    function () { console.log('Completed'); });

Next: {value: 1, interval: 100}
Next: {value: 2, interval: 200}
Next: {value: 3, interval: 300}
Completed

      generateWithAbsoluteTime is found in the following distribution:

rx.time.js (requires rx.js or rx.compat.js)

  {% endlang_operator %}

  {% lang_operator RxKotlin create %}

     TBD

  {% endlang_operator %}

  {% lang_operator Rx.NET Create Generate %}

     TBD

  {% endlang_operator %}

  {% lang_operator RxPHP create %}

    RxPHP implements this operator as create.

    Creates an observable sequence from a specified subscribeAction callable implementation.

Sample Code

//from https://github.com/ReactiveX/RxPHP/blob/master/demo/create/create.php

//With static method
$source = \Rx\Observable::create(function (\Rx\ObserverInterface $observer) {
    $observer->onNext(42);
    $observer->onCompleted();

    return new CallbackDisposable(function () {
        echo "Disposed\n";
    });
});

$subscription = $source->subscribe($createStdoutObserver());

Next value: 42
Complete!
Disposed

  {% endlang_operator %}

  {% lang_operator RxPY create generate generate_with_relative_time %}

     TBD

  {% endlang_operator %}

  {% lang_operator Rx.rb create generate %}

     TBD

  {% endlang_operator %}

  {% lang_operator RxScala apply create %}

     TBD

  {% endlang_operator %}

  {% lang_operator RxSwift create generate %}

        RxSwift implements this operator as create.

Sample Code

let source = Observable<Int>.create { observer in
  for i in 1...5 {
    observer.on(.Next(i))
  }
  observer.on(.Completed)

  // Note that this is optional. If you require no cleanup you can return
  // NopDisposable.instance
  return AnonymousDisposable {
    print("Disposed")
  }
}

source.subscribe {
  print($0)
}

Next(1)
Next(2)
Next(3)
Next(4)
Next(5)
Completed
disposed

        You can use the generate operator to create simple Observables that can generate their
        next emissions, and can determine when to terminate, based on the value of the previous emission. The
        basic form of generate takes three parameters:

the first item to emit

a function to test an item to determine whether to emit it (true) or terminate the
            Observable (false)

a function to generate the next item to test and emit based on the value of the previous item

        You can also pass in as an optional fourth parameter a Scheduler that
        generate will use to create and emit its sequence (it uses CurrentThreadScheduler by
        default).

Sample Code

let source = Observable<Int>.generate(
   initialState: 0,
   condition: { $0 < 3 },
   iterate: { $0 + 1 }
)

source.subscribe {
   print($0)
}

Next(0)
Next(1)
Next(2)
Completed

  {% endlang_operator %}


text:
package com.apruve.test;

import java.util.ArrayList;

import com.apruve.models.LineItem;
import com.apruve.models.PaymentRequest;

public class PaymentRequestOM {

	private static final String A_MERCHANT_ID = "AMerchantId";
	private static final String AN_ORDER_ID = "AnOrderId";

	public static PaymentRequest getPaymentRequestSimple() {
		PaymentRequest request = new PaymentRequest(A_MERCHANT_ID);
		request.setAmountCents(new Integer(100));
		request.setLineItems(new ArrayList<LineItem>());
		request.getLineItems().add(LineItemOM.getMinimalLineItem());
		return request;
	}

	public static PaymentRequest getPaymentRequest() {
		PaymentRequest request = new PaymentRequest(A_MERCHANT_ID);
		request.setMerchantOrderId(AN_ORDER_ID);
		request.setAmountCents(new Integer(100));
		request.setLineItems(LineItemOM.getLineItems());
		request.setExpiresAt("2014-12-31T00:00:00-06:00");

		return request;
	}
}


text:
package net.sf.maven.plugin.autotools;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Copies an input stream to an output stream.
 */
class StreamPump
implements Runnable {

    private static final int BUF_SIZE = 1024;

    /** */
    private Thread pumpThread;

    /** */
    private InputStream in;

    /** */
    private OutputStream out;

    /** */
    private volatile boolean finished;

    /**
     * Creates a stream pump.
     *
     * @param in an input stream
     * @param out an output stream
     */
    public StreamPump(InputStream in, OutputStream out) {
        this.in = in;
        this.out = out;
    }

    /**
     * Starts this stream pump.
     */
    public void start() {
        if (pumpThread != null) {
            throw new IllegalStateException("Stream pump already started");
        }
        pumpThread = new Thread(this);
        pumpThread.setDaemon(true);
        pumpThread.start();
    }

    /**
     * Stops this stream pump.
     */
    public void stop() {
        try {
            pumpThread.join();
        } catch (InterruptedException e) {
        }
        try {
            out.flush();
        } catch (IOException e) {
        }
    }

    /**
     * Copies data from the input stream to the output stream.  It stops if
     * the end of the input stream has been reached or an error occurs.
     */
    public synchronized void run() {
        byte[] buf = new byte[BUF_SIZE];

        try {
            int size;
            while ((size = in.read(buf)) > 0) {
                out.write(buf, 0, size);
            }
        } catch (Exception ex) {
        } finally {
            try {
                out.flush();
            } catch (IOException ex) {
            }
            finished = true;
            notifyAll();
        }
    }

    /**
     * Wait until the input stream is exhausted.
     *
     * @throws InterruptedException if the thread stops prematurely
     */
    public synchronized void waitFor()
    throws InterruptedException {
        while (!finished) {
            wait();
        }
    }

}


text:
/*
 * @author max
 */
package com.intellij.psi.impl.java.stubs;

import com.intellij.lang.ASTNode;
import com.intellij.psi.PsiCompiledElement;
import com.intellij.psi.PsiJavaCodeReferenceElement;
import com.intellij.psi.PsiNameHelper;
import com.intellij.psi.PsiReferenceList;
import com.intellij.psi.impl.compiled.ClsReferenceListImpl;
import com.intellij.psi.impl.java.stubs.impl.PsiClassReferenceListStubImpl;
import com.intellij.psi.impl.java.stubs.index.JavaSuperClassNameOccurenceIndex;
import com.intellij.psi.impl.source.PsiReferenceListImpl;
import com.intellij.psi.impl.source.tree.java.PsiTypeParameterExtendsBoundsListImpl;
import com.intellij.psi.stubs.IndexSink;
import com.intellij.psi.stubs.StubElement;
import com.intellij.psi.stubs.StubInputStream;
import com.intellij.psi.stubs.StubOutputStream;
import com.intellij.util.ArrayUtil;
import com.intellij.util.io.StringRef;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;

public class JavaClassReferenceListElementType extends JavaStubElementType<PsiClassReferenceListStub, PsiReferenceList> {
  public JavaClassReferenceListElementType(@NotNull @NonNls String id) {
    super(id);
  }

  public PsiReferenceList createPsi(final PsiClassReferenceListStub stub) {
    if (isCompiled(stub)) {
      return new ClsReferenceListImpl(stub);
    }
    else {
      if (stub.getRole() == PsiReferenceList.Role.EXTENDS_BOUNDS_LIST) {
        return new PsiTypeParameterExtendsBoundsListImpl(stub, JavaStubElementTypes.EXTENDS_BOUND_LIST);
      }

      return new PsiReferenceListImpl(stub, stub.getStubType());
    }
  }

  public PsiReferenceList createPsi(final ASTNode node) {
    if (node.getElementType() == JavaStubElementTypes.EXTENDS_BOUND_LIST) {
      return new PsiTypeParameterExtendsBoundsListImpl(node);
    }

    return new PsiReferenceListImpl(node);
  }

  public PsiClassReferenceListStub createStub(final PsiReferenceList psi, final StubElement parentStub) {
    return new PsiClassReferenceListStubImpl(roleToElementType(psi.getRole()), parentStub, getTexts(psi), psi.getRole());
  }

  private static JavaClassReferenceListElementType roleToElementType(final PsiReferenceList.Role role) {
    switch (role) {
      case EXTENDS_BOUNDS_LIST:
        return JavaStubElementTypes.EXTENDS_BOUND_LIST;
      case EXTENDS_LIST:
        return JavaStubElementTypes.EXTENDS_LIST;
      case IMPLEMENTS_LIST:
        return JavaStubElementTypes.IMPLEMENTS_LIST;
      case THROWS_LIST:
        return JavaStubElementTypes.THROWS_LIST;
    }

    throw new RuntimeException("Unknown role: " + role);
  }

  private static String[] getTexts(PsiReferenceList psi) {
    final PsiJavaCodeReferenceElement[] refs = psi.getReferenceElements();
    String[] texts = ArrayUtil.newStringArray(refs.length);
    for (int i = 0; i < refs.length; i++) {
      PsiJavaCodeReferenceElement ref = refs[i];
      texts[i] = ref instanceof PsiCompiledElement ? ref.getCanonicalText() : ref.getText();
    }
    return texts;
  }

  public void serialize(final PsiClassReferenceListStub stub, final StubOutputStream dataStream) throws IOException {
    dataStream.writeByte(encodeRole(stub.getRole()));
    final String[] names = stub.getReferencedNames();
    dataStream.writeVarInt(names.length);
    for (String name : names) {
      dataStream.writeName(name);
    }
  }

  public PsiClassReferenceListStub deserialize(final StubInputStream dataStream, final StubElement parentStub)
      throws IOException {
    byte role = dataStream.readByte();
    int len = dataStream.readVarInt();
    StringRef[] names = StringRef.createArray(len);
    for (int i = 0; i < names.length; i++) {
      names[i] = dataStream.readName();
    }

    final PsiReferenceList.Role decodedRole = decodeRole(role);
    return new PsiClassReferenceListStubImpl(roleToElementType(decodedRole), parentStub, names, decodedRole);
  }

  private static PsiReferenceList.Role decodeRole(int code) {
    switch (code) {
      case 0: return PsiReferenceList.Role.EXTENDS_LIST;
      case 1: return PsiReferenceList.Role.IMPLEMENTS_LIST;
      case 2: return PsiReferenceList.Role.THROWS_LIST;
      case 3: return PsiReferenceList.Role.EXTENDS_BOUNDS_LIST;

      default:
        throw new RuntimeException("Unknown role code: " + code);
    }
  }

  private static byte encodeRole(PsiReferenceList.Role role) {
    switch (role) {
      case EXTENDS_LIST:         return 0;
      case IMPLEMENTS_LIST:      return 1;
      case THROWS_LIST:          return 2;
      case EXTENDS_BOUNDS_LIST:  return 3;

      default:
        throw new RuntimeException("Unknown role code: " + role);
    }
  }

  public void indexStub(final PsiClassReferenceListStub stub, final IndexSink sink) {
    final PsiReferenceList.Role role = stub.getRole();
    if (role == PsiReferenceList.Role.EXTENDS_LIST || role == PsiReferenceList.Role.IMPLEMENTS_LIST) {
      final String[] names = stub.getReferencedNames();
      for (String name : names) {
        sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, PsiNameHelper.getShortClassName(name));
      }

      if (role == PsiReferenceList.Role.EXTENDS_LIST) {
        StubElement parentStub = stub.getParentStub();
        if (parentStub instanceof PsiClassStub) {
          PsiClassStub psiClassStub = (PsiClassStub)parentStub;
          if (psiClassStub.isEnum()) {
            sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, "Enum");
          }

          if (psiClassStub.isAnnotationType()) {
            sink.occurrence(JavaSuperClassNameOccurenceIndex.KEY, "Annotation");
          }
        }
      }
    }
  }
}


text:
using System.IO;
using Wasm.Binary;

namespace Wasm
{
    /// <summary>
    /// Represents an unknown section: a non-custom section whose section code was not recognized.
    /// </summary>
    public sealed class UnknownSection : Section
    {
        /// <summary>
        /// Creates an unknown section from the given section name and payload.
        /// </summary>
        /// <param name="code">The unknown section's code.</param>
        /// <param name="payload">The unknown section's payload.</param>
        public UnknownSection(SectionCode code, byte[] payload)
        {
            this.Code = code;
            this.Payload = payload;
        }

        /// <summary>
        /// Gets this unknown section's code.
        /// </summary>
        /// <returns>The code of the unknown section.</returns>
        public SectionCode Code { get; private set; }

        /// <inheritdoc/>
        public override SectionName Name => new SectionName(Code);

        /// <summary>
        /// Gets this unknown section's payload, as an array of bytes.
        /// </summary>
        /// <returns>A byte array that defines the unknown section's payload.</returns>
        public byte[] Payload { get; private set; }

        /// <summary>
        /// Writes this WebAssembly section's payload to the given binary WebAssembly writer.
        /// </summary>
        /// <param name="writer">The writer to which the payload is written.</param>
        public override void WritePayloadTo(BinaryWasmWriter writer)
        {
            writer.Writer.Write(Payload);
        }
    }
}