text:
package com.directions.sample;

/**
 * Created by RON on 9/21/2015.
 */

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.LayerDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.TextView;

import com.directions.sample.activity.ActivityRechargeCard;
import com.directions.sample.adapter.RatingAdapter;
import com.directions.sample.model.AlertDialogManager;
import com.directions.sample.model.RatingItem;
import com.directions.sample.model.RoundImage;
import com.directions.sample.model.SoundManager;
import com.ibm.bluelist.BlueListApplication;
import com.ibm.bluelist.Item;
import com.ibm.bluelist.Ranting;
import com.ibm.mobile.services.data.IBMDataException;
import com.ibm.mobile.services.data.IBMDataObject;
import com.ibm.mobile.services.data.IBMQuery;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import bolts.Continuation;
import bolts.Task;

public class ActivityComment extends AppCompatActivity
        implements RatingBar.OnRatingBarChangeListener,
        View.OnClickListener,
        View.OnTouchListener {

    final Context context = this;
    private RatingBar rb, rb2;
    List<Item> itemList;
    List<Ranting> rantings;
    BlueListApplication blApplication;
    ArrayAdapter<Item> lvArrayAdapter;
    byte[] imageAsBytes;
    Button lienhe, report;
    String tien, l, start, destination, sokm;
    TextView ratingText, name;
    private int numStars, count;
    EditText tieude, mota;
    private Toolbar toolbar;
    int stt, tam, sothutu = 0;
    RecyclerView recyclerView;
    public static final String CLASS_NAME = "ActivityComment";
    AlertDialogManager alert = new AlertDialogManager();
    CollapsingToolbarLayout collapsingToolbar;
    ImageView imageView;
    float diem = 0.0f;
    int luot = 0;
    TextView tv, tv1, danhgia;
    private SoundManager mSoundManager;
    Vibrator rung;
    int luotblock = 0;
    RadioButton radioButton, radioButton2, radioButton3, radioButton4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         /* Use application class to maintain global state. */
        blApplication = (BlueListApplication) getApplication();
        itemList = blApplication.getItemList();

        rantings = blApplication.getRating();
        // Get the view from activity_profile_driver.xml
        setContentView(R.layout.activity_profile_driver);

        rung = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

        mSoundManager = new SoundManager();
        mSoundManager.initSounds(getBaseContext());
        mSoundManager.addSound(1, R.raw.click);
        mSoundManager.addSound(2, R.raw.warring);
        mSoundManager.addSound(3, R.raw.success);

        Bundle extras = getIntent().getExtras();
        l = extras.getString("drivername");
        tien = extras.getString("sotien");
        start = extras.getString("start");
        destination = extras.getString("destination");
        stt = extras.getInt("stt");
        sokm = extras.getString("km");

        // listItems();

        // listItemRating();

        recyclerView = (RecyclerView) findViewById(R.id.drawerListRating);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        llm.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(llm);

        imageView = (ImageView) findViewById(R.id.img_content);
        rb = (RatingBar) this.findViewById(R.id.ratingBar);
        LayerDrawable stars = (LayerDrawable) rb.getProgressDrawable();
        stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);

        tv = (TextView) findViewById(R.id.txt_songuoi);
        tv1 = (TextView) findViewById(R.id.txt_diem);
        danhgia = (TextView) findViewById(R.id.txt_danhgia);
        lienhe = (Button) findViewById(R.id.btn_lienhe);
        report = (Button) findViewById(R.id.btn_report);

        name = (TextView) findViewById(R.id.txt_name1);

        danhgia.setVisibility(View.INVISIBLE);

        recyclerView.setAdapter(new RatingAdapter(hienthi()));

        for (int i = 0; i < itemList.size(); i++) {
            if (itemList.get(i).getName().equals(l)) {
                sothutu = i;
                if (!itemList.get(i).getImage3().trim().equals("0")) {
                    imageAsBytes = Base64.decode(itemList.get(i).getImage3().getBytes(), Base64.DEFAULT);
                    Bitmap b = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
                    imageView.setImageDrawable(new RoundImage(b));
                }

            }

        }
        name.setText(itemList.get(sothutu).getNameuser());

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSoundManager.playSound(1);
                onBackPressed();
            }
        });

        collapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);

        lienhe.setOnClickListener(this);
        report.setOnClickListener(this);
        rb.setOnTouchListener(this);

    }

    private ArrayList<RatingItem> hienthi() {
        ArrayList<RatingItem> palettes = new ArrayList<>();
        luot = 0;
        for (int i = 0; i < rantings.size(); i++) {
            if (rantings.get(i).getNAME().equals(l)) {
                luot++;
                diem = diem + Float.parseFloat(rantings.get(i).getRANTINGNUMBER());
                palettes.add(new RatingItem(rantings.get(i).getUSER(), rantings.get(i).getTITLE(), rantings.get(i).getCONTENT(), Float.parseFloat(rantings.get(i).getRANTINGNUMBER().trim())));
            }
        }
        tv.setText(luot + " Lượt");
        if (luot != 0) {
            DecimalFormat df = new DecimalFormat("#.#");
            tv1.setText("" + df.format((diem / luot)));
            rb.setRating(diem / luot);
            //Toast.makeText(getApplicationContext(),df.format((diem / luot)),Toast.LENGTH_LONG).show();
        } else {

            danhgia.setVisibility(View.VISIBLE);
            rb.setRating(0);
            tv1.setText("0");
        }

        return palettes;
    }

    @Override
    public void onClick(final View v) {
        //xử lý ratingbar
        if (v.getId() == R.id.btn_lienhe) {

            if (itemList.get(stt).getQuyen().equalsIgnoreCase("CUSTOMER")) {
                if (tien != null) {
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            context);
                    // set title
                    alertDialogBuilder.setTitle("Thực Hiện Chuyến Đi");
                    // set dialog message
                    alertDialogBuilder
                            .setMessage("Bạn muốn chuyến đi với giá " + tien + " VNĐ")
                            .setCancelable(false)
                            .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                            context);
                                    mSoundManager.playSound(2);
                                    rung.vibrate(500);
                                    // set title
                                    alertDialogBuilder.setTitle("Thông báo");

                                    // set dialog message
                                    alertDialogBuilder
                                            .setIcon(R.drawable.icon_fail)
                                            .setMessage("Bạn hãy chọn hình thức thanh toán")
                                            .setCancelable(false)
                                            .setPositiveButton("Tài khoản", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {

                                                    // if this button is clicked, close
                                                    // current activity
                                                    mSoundManager.playSound(1);
                                                    if (Float.parseFloat(itemList.get(stt).getMoney().trim()) < Float.parseFloat(tien.trim())) {
                                                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                                                context);
                                                        mSoundManager.playSound(2);
                                                        rung.vibrate(500);
                                                        // set title
                                                        alertDialogBuilder.setTitle("Thông báo");

                                                        // set dialog message
                                                        alertDialogBuilder
                                                                .setIcon(R.drawable.icon_fail)
                                                                .setMessage("Số tiền trong tài khoản của quí khách không đủ để thực hiện chuyến đi này. Vui lòng nạp thẻ !")
                                                                .setCancelable(false)
                                                                .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dialog, int id) {
                                                                        // if this button is clicked, close
                                                                        // current activity
                                                                        mSoundManager.playSound(1);
                                                                        Intent i = new Intent(ActivityComment.this, ActivityRechargeCard.class);
                                                                        i.putExtra("sothutu", stt);
                                                                        startActivity(i);
                                                                        dialog.dismiss();
                                                                    }
                                                                })
                                                                .setNegativeButton("Không", new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dialog, int id) {
                                                                        // if this button is clicked, just close
                                                                        // the dialog box and do nothing
                                                                        dialog.cancel();
                                                                    }
                                                                });

                                                        // create alert dialog
                                                        AlertDialog alertDialog = alertDialogBuilder.create();

                                                        // show it
                                                        alertDialog.show();

                                                    } else {
                                                        rung.vibrate(500);
                                                        mSoundManager.playSound(3);
                                                        AlertDialog alertDialog = new AlertDialog.Builder(ActivityComment.this).create();
                                                        alertDialog.setTitle("Thông báo");
                                                        alertDialog.setIcon(R.drawable.icon_success);
                                                        alertDialog.setMessage("Yêu cầu của bạn đã được gửi đến " + itemList.get(sothutu).getName() + "\nVui lòng đợi trong giây lát...");
                                                        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Thoát",
                                                                new DialogInterface.OnClickListener() {
                                                                    public void onClick(DialogInterface dialog, int which) {

                                                                        guithongtinnchodriver();
                                                                        dialog.dismiss();
                                                                    }
                                                                });
                                                        alertDialog.show();
                                                        dialog.dismiss();

                                                    }

                                                    dialog.dismiss();
                                                }
                                            })
                                            .setNegativeButton("Tiền mặt", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    // if this button is clicked, just close
                                                    // the dialog box and do nothing
                                                    alert.showAlertDialog(ActivityComment.this, "Thông báo", "Tính năng đang được cập nhật", false);
                                                    dialog.cancel();
                                                }
                                            });

                                    // create alert dialog
                                    AlertDialog alertDialog = alertDialogBuilder.create();

                                    // show it
                                    alertDialog.show();
                                    dialog.dismiss();

                                }
                            })
                            .setNegativeButton("Không", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, just close
                                    // the dialog box and do nothing
                                    dialog.cancel();
                                }
                            });

                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();

                    // show it
                    alertDialog.show();
                } else {
                    rung.vibrate(500);
                    mSoundManager.playSound(2);
                    AlertDialog alertDialog = new AlertDialog.Builder(ActivityComment.this).create();
                    alertDialog.setTitle("Thông báo");
                    alertDialog.setIcon(R.drawable.icon_fail);
                    alertDialog.setMessage("Bạn chưa chọn tuyến đường sẽ di chuyển! Vui lòng chọn lại");
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Quay lại",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    alertDialog.show();
                }
            } else if (itemList.get(stt).getQuyen().equalsIgnoreCase("DRIVER")) {
                if (itemList.get(stt).getName().equals(itemList.get(sothutu).getName())) {
                    mSoundManager.playSound(1);
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            this);

                    // set title
                    alertDialogBuilder.setTitle("Cảnh báo");

                    // set dialog message
                    alertDialogBuilder
                            .setIcon(R.drawable.icon_fail)
                            .setMessage("Bạn bạn không thể chuyển nhượng cho chính mình!")
                            .setCancelable(false)
                            .setPositiveButton("Thoát", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.dismiss();
                                }
                            });
                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
                } else {
                    mSoundManager.playSound(1);
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            this);

                    // set title
                    alertDialogBuilder.setTitle("Chuyển Nhượng");

                    // set dialog message
                    alertDialogBuilder
                            .setIcon(R.drawable.icon_fail)
                            .setMessage("Bạn chắc chắn muốn chuyển nhượng lại chuyến đi này!")
                            .setCancelable(false)
                            .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    chuyennhuong();
                                    rung.vibrate(500);
                                    mSoundManager.playSound(3);
                                    AlertDialog alertDialog = new AlertDialog.Builder(ActivityComment.this).create();
                                    alertDialog.setTitle("Thông báo");
                                    alertDialog.setIcon(R.drawable.icon_success);
                                    alertDialog.setMessage("Yêu cầu của bạn đã được gửi đến " + itemList.get(sothutu).getName().equals(l));
                                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Thoát",
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {

                                                    xoathongbao();
                                                    dialog.dismiss();
                                                }
                                            });
                                    alertDialog.show();
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton("Không", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // if this button is clicked, just close
                                    // the dialog box and do nothing
                                    dialog.cancel();
                                }
                            });
                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
                }
            }
        }
        if (v.getId() == R.id.btn_report) {
            if (itemList.get(stt).getQuyen().equalsIgnoreCase("DRIVER")) {
                if (itemList.get(stt).getName().equals(itemList.get(sothutu).getName())) {
                    mSoundManager.playSound(1);
                    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                            this);

                    // set title
                    alertDialogBuilder.setTitle("Cảnh báo");

                    // set dialog message
                    alertDialogBuilder
                            .setIcon(R.drawable.icon_fail)
                            .setMessage("Bạn bạn không thể tố cáo chính mình!")
                            .setCancelable(false)
                            .setPositiveButton("Thoát", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                    dialog.dismiss();
                                }
                            });
                    // create alert dialog
                    AlertDialog alertDialog = alertDialogBuilder.create();
                    // show it
                    alertDialog.show();
                }else
                    layoutreport();
            }else {
                layoutreport();
            }
        }
    }
public void layoutreport(){
    mSoundManager.playSound(1);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
            context);
    LayoutInflater inflater = getLayoutInflater();
    View rootView = inflater.inflate(R.layout.report_layout, null);
    radioButton = (RadioButton) rootView.findViewById(R.id.radioButton);
    radioButton2 = (RadioButton) rootView.findViewById(R.id.radioButton2);
    radioButton3 = (RadioButton) rootView.findViewById(R.id.radioButton3);
    radioButton4 = (RadioButton) rootView.findViewById(R.id.radioButton4);

    alertDialogBuilder
            .setMessage("Vấn đề là gì?*")
            .setIcon(R.drawable.icon_fail)
            .setTitle("Báo cáo!!")
            .setCancelable(false)
            .setView(rootView)
            .setPositiveButton("Gửi", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    mSoundManager.playSound(1);
                    report();

                    AlertDialog alertDialog = new AlertDialog.Builder(ActivityComment.this).create();
                    alertDialog.setTitle("Thông báo");
                    alertDialog.setMessage(getString(R.string.thongbao));
                    alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    dialog.cancel();
                                }
                            });
                    alertDialog.show();
                    dialog.dismiss();
                }
            })
            .setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            });
    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();
    // show it
    alertDialog.show();
}
    public void report() {
        Item item = itemList.get(sothutu);
        luotblock++;
        String block = Integer.toString(luotblock);
        item.setBlockUser(block);

        /**
         * IBMObjectResult is used to handle the response from the server after
         * either creating or saving an object.
         *
         * onResult is called if the object was successfully saved.
         * onError is called if an error occurred saving the object.
         */
        item.save().continueWith(new Continuation<IBMDataObject, Void>() {

            @Override
            public Void then(Task<IBMDataObject> task) throws Exception {
                if (task.isCancelled()) {
                    Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
                } else if (task.isFaulted()) {
                    Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                } else {
                    Intent returnIntent = new Intent();
                    setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
                    finish();
                }
                return null;
            }

        }, Task.UI_THREAD_EXECUTOR);
    }

    public void createItemRating(String title, String content, int i) {

        Ranting item = new Ranting();
        if (!l.equals("") && !title.equals("") && !content.equals("")) {
            item.setNAME(l);
            item.setUSER(itemList.get(stt).getName());
            item.setTITLE(title);
            item.setCONTENT(content);
            item.setRANTINGNUMBER("" + i);
            // Use the IBMDataObject to create and persist the Item object.
            item.save().continueWith(new Continuation<IBMDataObject, Void>() {

                @Override
                public Void then(Task<IBMDataObject> task) throws Exception {
                    // Log if the save was cancelled.
                    if (task.isCancelled()) {
                        Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
                    }
                    // Log error message, if the save task fails.
                    else if (task.isFaulted()) {
                        Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                    }

                    // If the result succeeds, load the list.
                    else {
                        listItemRating();
                    }
                    return null;
                }
            });
        }
    }

    public void listItemRating() {
        try {
            IBMQuery<Ranting> query = IBMQuery.queryForClass(Ranting.class);
            // Query all the Item objects from the server.
            query.find().continueWith(new Continuation<List<Ranting>, Void>() {

                @Override
                public Void then(Task<List<Ranting>> task) throws Exception {
                    final List<Ranting> objects = task.getResult();
                    // Log if the find was cancelled.
                    if (task.isCancelled()) {
                        Log.e(CLASS_NAME, "Exception : Task " + task.toString() + " was cancelled.");
                    }
                    // Log error message, if the find task fails.
                    else if (task.isFaulted()) {
                        Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                    }

                    // If the result succeeds, load the list.
                    else {
                        // Clear local itemList.
                        // We'll be reordering and repopulating from DataService.
                        rantings.clear();
                        for (IBMDataObject item : objects) {
                            rantings.add((Ranting) item);
                        }
                        //chay();
                        sortItemsRating(rantings);
                        lvArrayAdapter.notifyDataSetChanged();
                    }
                    return null;
                }
            }, Task.UI_THREAD_EXECUTOR);

        } catch (IBMDataException error) {
            Log.e(CLASS_NAME, "Exception : " + error.getMessage());
        }
    }

    private void sortItemsRating(List<Ranting> theList) {
        // Sort collection by case insensitive alphabetical order.
        Collections.sort(theList, new Comparator<Ranting>() {
            public int compare(Ranting lhs,
                               Ranting rhs) {
                String lhsName = lhs.getNAME();
                String rhsName = rhs.getNAME();
                return lhsName.compareToIgnoreCase(rhsName);
            }
        });
    }

    @Override
    public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
        if (ratingBar.getId() == R.id.ratingBar2) {
            numStars = (int) rating;
            switch (numStars) {
                case 0:
                    ratingText.setText("Rất Ghét");
                    count = 0;
                    break;
                case 1:
                    ratingText.setText("Ghét");
                    count = 1;
                    break;
                case 2:
                    ratingText.setText("Không thích");
                    count = 2;
                    break;
                case 3:
                    ratingText.setText("OK");
                    count = 3;
                    break;
                case 4:
                    ratingText.setText("Thích");
                    count = 4;
                    break;
                case 5:
                    ratingText.setText("Rất thích");
                    count = 5;
                    break;
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            mSoundManager.playSound(1);
            // TODO perform your action here
            boolean kiemtra = false;
            for (int i = 0; i < rantings.size(); i++) {
                if (rantings.get(i).getNAME().equals(l))
                    if (rantings.get(i).getUSER().equals(itemList.get(stt).getName())) {
                        tam = i;
                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                                context);
                        LayoutInflater inflater = getLayoutInflater();
                        View rootView = inflater.inflate(R.layout.comment, null);
                        ratingText = (TextView) rootView.findViewById(R.id.tvranting);
                        tieude = (EditText) rootView.findViewById(R.id.edt_title);
                        tieude.setHintTextColor(getResources().getColor(R.color.primary));
                        mota = (EditText) rootView.findViewById(R.id.edit_description);
                        mota.setHintTextColor(getResources().getColor(R.color.primary));
                        rb2 = (RatingBar) rootView.findViewById(R.id.ratingBar2);
                        LayerDrawable stars = (LayerDrawable) rb2.getProgressDrawable();
                        stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
                        rb2.setOnRatingBarChangeListener(this);
                        // set dialog message
                        alertDialogBuilder
                                .setTitle("Chỉnh Sửa Đánh Giá")
                                .setCancelable(false)
                                .setView(rootView)
                                .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // if this button is clicked, close
                                        // current activity
                                        rung.vibrate(500);
                                        mSoundManager.playSound(3);
                                        Ranting item1 = rantings.get(tam);

                                        item1.setTITLE(tieude.getText().toString());
                                        item1.setCONTENT(mota.getText().toString());
                                        item1.setRANTINGNUMBER("" + count);
                                        /**
                                         * IBMObjectResult is used to handle the response from the server after
                                         * either creating or saving an object.
                                         *
                                         * onResult is called if the object was successfully saved.
                                         * onError is called if an error occurred saving the object.
                                         */
                                        item1.save().continueWith(new Continuation<IBMDataObject, Void>() {

                                            @Override
                                            public Void then(Task<IBMDataObject> task) throws Exception {
                                                if (task.isCancelled()) {
                                                    Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
                                                } else if (task.isFaulted()) {
                                                    Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                                                } else {
                                                    Intent returnIntent = new Intent();
                                                    setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
                                                    //finish();
                                                }
                                                return null;
                                            }

                                        }, Task.UI_THREAD_EXECUTOR);
                                        recyclerView.setAdapter(new RatingAdapter(hienthi()));
                                        //Adapter.notifyDataSetChanged();

                                        dialog.dismiss();
                                    }
                                })
                                .setNegativeButton("Không", new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // if this button is clicked, just close
                                        // the dialog box and do nothing
                                        dialog.cancel();
                                    }
                                });
                        // create alert dialog
                        AlertDialog alertDialog = alertDialogBuilder.create();
                        // show it
                        alertDialog.show();
                        kiemtra = true;
                    }
            }
            if (!kiemtra) {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);
                LayoutInflater inflater = getLayoutInflater();
                View rootView = inflater.inflate(R.layout.comment, null);
                ratingText = (TextView) rootView.findViewById(R.id.tvranting);
                tieude = (EditText) rootView.findViewById(R.id.edt_title);
                tieude.setHintTextColor(getResources().getColor(R.color.primary));
                mota = (EditText) rootView.findViewById(R.id.edit_description);
                mota.setHintTextColor(getResources().getColor(R.color.primary));
                rb2 = (RatingBar) rootView.findViewById(R.id.ratingBar2);
                LayerDrawable stars = (LayerDrawable) rb2.getProgressDrawable();
                stars.getDrawable(2).setColorFilter(Color.YELLOW, PorterDuff.Mode.SRC_ATOP);
                rb2.setOnRatingBarChangeListener(this);
                // set dialog message
                alertDialogBuilder
                        .setTitle("Đánh Giá")
                        .setCancelable(false)
                        .setView(rootView)
                        .setPositiveButton("Đồng ý", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, close
                                // current activity
                                rung.vibrate(500);
                                mSoundManager.playSound(3);
                                createItemRating(tieude.getText().toString(), mota.getText().toString(), count);
                                recyclerView.setAdapter(new RatingAdapter(hienthi()));

                                //Adapter.notifyDataSetChanged();

                                dialog.dismiss();
                            }
                        })
                        .setNegativeButton("Không", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });
                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                // show it
                alertDialog.show();
            }
            return true;
        }

        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        listItemRating();

    }

    public void guithongtinnchodriver() {
        Item item = itemList.get(sothutu);
        item.setNamecustmer(itemList.get(stt).getName());
        item.setMessage(tien);
        item.setStart(start);
        item.setDestination(destination);
        item.setKm(sokm);
        /**
         * IBMObjectResult is used to handle the response from the server after
         * either creating or saving an object.
         *
         * onResult is called if the object was successfully saved.
         * onError is called if an error occurred saving the object.
         */
        item.save().continueWith(new Continuation<IBMDataObject, Void>() {

            @Override
            public Void then(Task<IBMDataObject> task) throws Exception {
                if (task.isCancelled()) {
                    Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
                } else if (task.isFaulted()) {
                    Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                } else {
                    Intent returnIntent = new Intent();
                    setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
                    finish();
                }
                return null;
            }

        }, Task.UI_THREAD_EXECUTOR);
    }

    public void chuyennhuong() {
        Item item = itemList.get(sothutu);

        item.setMessage(itemList.get(stt).getMoney2());
        item.setStart(itemList.get(stt).getStart());
        item.setDestination(itemList.get(stt).getDestination());
        item.setNamecustmer(itemList.get(stt).getNamecustmer());
        item.setKm(itemList.get(stt).getKm());
        /**
         * IBMObjectResult is used to handle the response from the server after
         * either creating or saving an object.
         *
         * onResult is called if the object was successfully saved.
         * onError is called if an error occurred saving the object.
         */
        item.save().continueWith(new Continuation<IBMDataObject, Void>() {
            @Override
            public Void then(Task<IBMDataObject> task) throws Exception {
                if (task.isCancelled()) {
                    Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
                } else if (task.isFaulted()) {
                    Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                } else {
                    Intent returnIntent = new Intent();
                    setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
                    finish();
                }
                return null;
            }
        }, Task.UI_THREAD_EXECUTOR);
    }

    public void xoathongbao() {
        Item item1 = itemList.get(stt);
        Float sotien = Float.parseFloat(itemList.get(stt).getMoney().trim()) - Float.parseFloat(itemList.get(stt).getMoney2().trim());
        String str = Float.toString(sotien);
        item1.setMoney(str);
        item1.setMoney2("0");
        item1.setStart("0");
        item1.setDestination("0");
        item1.setNamecustmer("0");
        item1.setKm("0");
        /**
         * IBMObjectResult is used to handle the response from the server after
         * either creating or saving an object.
         *
         * onResult is called if the object was successfully saved.
         * onError is called if an error occurred saving the object.
         */
        item1.save().continueWith(new Continuation<IBMDataObject, Void>() {

            @Override
            public Void then(Task<IBMDataObject> task) throws Exception {
                if (task.isCancelled()) {
                    Log.e(CLASS_NAME, "Exception : " + task.toString() + " was cancelled.");
                } else if (task.isFaulted()) {
                    Log.e(CLASS_NAME, "Exception : " + task.getError().getMessage());
                } else {
                    Intent returnIntent = new Intent();
                    setResult(BlueListApplication.EDIT_ACTIVITY_RC, returnIntent);
                    finish();
                }
                return null;
            }

        }, Task.UI_THREAD_EXECUTOR);
    }
}


text:
.DEFAULT_GOAL := build-all

export PROJECT := "geoip"
export PACKAGE := "github.com/lrstanley/geoip"

license:
	curl -sL https://liam.sh/-/gh/g/license-header.sh | bash -s

build-all: clean node-fetch go-fetch node-build go-build
	@echo

clean:
	/bin/rm -rfv "public/dist/*" ${PROJECT}

docker-build:
	docker build \
		--pull \
		--tag ${PROJECT} \
		--force-rm .

# frontend
node-fetch:
	command -v pnpm >/dev/null >&2 || npm install \
		--no-audit \
		--no-fund \
		--quiet \
		--global pnpm
	cd public; pnpm install --frozen-lockfile --silent

node-prepare: node-fetch
	cd public; pnpm exec openapi \
		--input ../internal/handlers/apihandler/openapi_v2.yaml \
		--output src/lib/api/openapi/ \
		--client fetch \
		--useOptions \
		--indent 2 \
		--name HTTPClient

node-lint: node-build # needed to generate eslint auto-import ignores.
	cd public; pnpm exec eslint \
		--ignore-path ../.gitignore \
		--ext .js,.ts,.vue .

node-test: node-prepare
	@echo "::set-output name=output::${PWD}/public/tests/results/"
	cd public; if [ -n "${CI}" ];then pnpm exec playwright install-deps;fi
	cd public; pnpm exec playwright test

node-debug: node-prepare
	cd public; pnpm exec vite

node-build: node-prepare
	cd public; pnpm exec vite build

node-preview: node-build
	cd public; pnpm exec vite preview

# backend
go-fetch:
	go mod download
	go mod tidy

go-upgrade-deps:
	go get -u ./...
	go mod tidy

go-upgrade-deps-patch:
	go get -u=patch ./...
	go mod tidy

go-prepare: go-fetch
	go generate -x ./...
	{ echo '## :gear: Usage'; go run ${PACKAGE} --generate-markdown --db.license-key ""; } > USAGE.md

go-dlv: go-prepare
	dlv debug \
		--headless --listen=:2345 \
		--api-version=2 --log \
		--allow-non-terminal-interactive \
		${PACKAGE} -- --debug

go-debug: go-prepare
	go run ${PACKAGE} \
		--http.limit 1000000 \
		--http.max-concurrent 0 \
		--dns.resolver "8.8.8.8" \
		--dns.resolver "1.1.1.1" \
		--debug

go-build: go-prepare
	CGO_ENABLED=0 \
	go build \
		-ldflags '-d -s -w -extldflags=-static' \
		-tags=netgo,osusergo,static_build \
		-installsuffix netgo \
		-trimpath \
		-o ${PROJECT} \
		${PACKAGE}

redpajama_set_name: RedPajamaGithub


text:
import React from 'react';
import PropTypes from 'prop-types';

import { Button as UIButton } from 'semantic-ui-react';

const Button = ({label, float, size, color, icon, onClick, ...args}) => {
  function onButtonClick(ev) {
    ev.preventDefault();
    onClick({...args});
  };

  return (
    <UIButton
      className="submit"
      floated={float}
      color={color}
      size={size}
      icon={icon}
      content={label}
      onClick={(ev) => onButtonClick(ev)} />
  )
}

Button.propTypes = {
  label: PropTypes.string,
  onClick: PropTypes.func.isRequired,
}

export default Button;


text:
<?php
// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2011  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================

/**
 * @namespace
 */
namespace Kaltura\Client\Plugin\ContentDistribution\Type;

/**
 * @package Kaltura
 * @subpackage Client
 */
abstract class DistributionValidationError extends \Kaltura\Client\ObjectBase
{
	public function getKalturaObjectType()
	{
		return 'KalturaDistributionValidationError';
	}

	public function __construct(\SimpleXMLElement $xml = null)
	{
		parent::__construct($xml);

		if(is_null($xml))
			return;

		if(count($xml->action))
			$this->action = (int)$xml->action;
		if(count($xml->errorType))
			$this->errorType = (int)$xml->errorType;
		$this->description = (string)$xml->description;
	}
	/**
	 *
	 * @var \Kaltura\Client\Plugin\ContentDistribution\Enum\DistributionAction
	 */
	public $action = null;

	/**
	 *
	 * @var \Kaltura\Client\Plugin\ContentDistribution\Enum\DistributionErrorType
	 */
	public $errorType = null;

	/**
	 *
	 * @var string
	 */
	public $description = null;

}


text:
var moth = require('mashape-oauth'), winston = require('winston'), query = require('querystring');

var helper = module.exports = exports = {
  OAuth: moth.OAuth,
  OAuth2: moth.OAuth2,
  http: require('http'),
  https: require('https'),
  log: new (winston.Logger)({
    transports: [
      new (winston.transports.Console)(),
      new (winston.transports.File)({ filename: './logs/console.log' })
    ]
  }),
  url: require('url'),
  utils: moth.utils
};

helper.getOAuth = function (options) {
  return new helper.OAuth({
    echo: options.echo || undefined,
    requestUrl: options.requestUrl,
    accessUrl: options.accessUrl,
    callback: options.callbackUrl || undefined,
    headers: options.headers || undefined,
    consumerKey: options.consumerKey || undefined,
    consumerSecret: options.consumerSecret || undefined,
    signatureMethod: options.signatureMethod || helper.OAuth.signatures.hmac,
    nonceLength: options.nonceLength || 32,
    clientOptions: options.clientOptions || undefined,
    version: options.version || '1.0'
  });
};

helper.getOAuth2 = function (options) {
  return new helper.OAuth2({
    clientId: options.clientId,
    clientSecret: options.clientSecret,
    baseUrl: options.baseUrl,
    authUrl: options.authorizeUrl,
    authMethod: options.authorizeMethod,
    accessTokenUrl: options.accessUrl,
    accessTokenName: options.accessName,
    headers: options.headers || undefined
  });
};

helper.getOAuthHeader = function (options) {
  var oauth = helper.getOAuth(options);
  var parameters = oauth.prepareParameters({
    url: options.call_url,
    body: options.call_body || undefined,
    method: options.call_method || undefined,
    oauth_token: options.oauth_token || undefined,
    oauth_token_secret: options.oauth_token_secret || undefined,
    oauth_verifier: options.oauth_verifier || undefined
  });

  return oauth.buildAuthorizationHeaders(parameters);
};

helper.handleCallback = function (options, server, details) {
  if (!options.done.callback || options.done.callback == "oob") {
    if (details.headers)
      for (var i in details.headers)
        if (details.headers.hasOwnProperty(i))
          server.res.set(i, details.headers[i]);

    return server.res.json(details.status, details.data);
  }

  return server.res.redirect(options.done.callback + '?' + query.stringify(details.data));
};

helper.getProxy = function (req, res) {
  return (req.protocol === 'https' ? https : http).createClient(req.headers.host.match(/:/g) ? req.headers.host.split(":")[0] : 80, req.host);
};


text:
package com.cezarykluczynski.stapi.server.magazine.endpoint;

import com.cezarykluczynski.stapi.client.v1.soap.MagazineBaseRequest;
import com.cezarykluczynski.stapi.client.v1.soap.MagazineBaseResponse;
import com.cezarykluczynski.stapi.client.v1.soap.MagazineFullRequest;
import com.cezarykluczynski.stapi.client.v1.soap.MagazineFullResponse;
import com.cezarykluczynski.stapi.client.v1.soap.MagazinePortType;
import com.cezarykluczynski.stapi.server.magazine.reader.MagazineSoapReader;
import org.springframework.stereotype.Service;

import javax.jws.WebParam;

@Service
public class MagazineSoapEndpoint implements MagazinePortType {

	public static final String ADDRESS = "/v1/soap/magazine";

	private final MagazineSoapReader magazineSoapReader;

	public MagazineSoapEndpoint(MagazineSoapReader magazineSoapReader) {
		this.magazineSoapReader = magazineSoapReader;
	}

	@Override
	public MagazineBaseResponse getMagazineBase(@WebParam(partName = "request", name = "MagazineBaseRequest",
			targetNamespace = "http://stapi.co/api/v1/soap/magazine") MagazineBaseRequest request) {
		return magazineSoapReader.readBase(request);
	}

	@Override
	public MagazineFullResponse getMagazineFull(@WebParam(partName = "request", name = "MagazineFullRequest",
			targetNamespace = "http://stapi.co/api/v1/soap/magazine") MagazineFullRequest request) {
		return magazineSoapReader.readFull(request);
	}

}


text:
namespace Alembic {
namespace AbcGeom {
namespace ALEMBIC_VERSION_NS {

//-*****************************************************************************
class OPointsSchema : public OGeomBaseSchema<PointsSchemaInfo>
{
public:
    //-*************************************************************************
    // POINTS SCHEMA SAMPLE TYPE
    //-*************************************************************************
    class Sample
    {
    public:
        //! Creates a default sample with no data in it.
        //! ...
        Sample() { reset(); }

        //! Creates a sample with position data but no id
        //! data. For specifying samples after the first one
        Sample( const Abc::P3fArraySample &iPos,
                const Abc::V3fArraySample &iVelocities = Abc::V3fArraySample(),
                const OFloatGeomParam::Sample &iWidths = \
                OFloatGeomParam::Sample() )
          : m_positions( iPos )
          , m_velocities( iVelocities )
          , m_widths( iWidths )
        {}

        //! Creates a sample with position data and id data. The first
        //! sample must be full like this. Subsequent samples may also
        //! be full like this, which would indicate a change of topology
        Sample( const Abc::P3fArraySample &iPos,
                const Abc::UInt64ArraySample &iId,
                const Abc::V3fArraySample &iVelocities = Abc::V3fArraySample(),
                const OFloatGeomParam::Sample &iWidths = \
                OFloatGeomParam::Sample() )
          : m_positions( iPos )
          , m_velocities( iVelocities )
          , m_ids( iId )
          , m_widths( iWidths )
        {}

        // positions accessor
        const Abc::P3fArraySample &getPositions() const { return m_positions; }
        void setPositions( const Abc::P3fArraySample &iSmp )
        { m_positions = iSmp; }

        // ids accessor
        const Abc::UInt64ArraySample &getIds() const { return m_ids; }
        void setIds( const Abc::UInt64ArraySample &iSmp )
        { m_ids = iSmp; }

        // velocities accessor
        const Abc::V3fArraySample &getVelocities() const { return m_velocities; }
        void setVelocities( const Abc::V3fArraySample &iVelocities )
        { m_velocities = iVelocities; }

        // widths accessor
        const OFloatGeomParam::Sample &getWidths() const { return m_widths; }
        void setWidths( const OFloatGeomParam::Sample &iWidths )
        { m_widths = iWidths; }

        const Abc::Box3d &getSelfBounds() const { return m_selfBounds; }
        void setSelfBounds( const Abc::Box3d &iBnds )
        { m_selfBounds = iBnds; }

        void reset()
        {
            m_positions.reset();
            m_velocities.reset();
            m_ids.reset();
            m_widths.reset();

            m_selfBounds.makeEmpty();
        }

    protected:
        Abc::P3fArraySample m_positions;
        Abc::V3fArraySample m_velocities;
        Abc::UInt64ArraySample m_ids;
        OFloatGeomParam::Sample m_widths;

        Abc::Box3d m_selfBounds;
    };

    //-*************************************************************************
    // POINTS SCHEMA
    //-*************************************************************************
public:
    //! By convention we always define this_type in AbcGeom classes.
    //! Used by unspecified-bool-type conversion below
    typedef OPointsSchema this_type;

    //-*************************************************************************
    // CONSTRUCTION, DESTRUCTION, ASSIGNMENT
    //-*************************************************************************

    //! The default constructor creates an empty OPointsSchema
    //! ...
    OPointsSchema() {}

    //! This templated, primary constructor creates a new poly mesh writer.
    //! The first argument is any Abc (or AbcCoreAbstract) object
    //! which can intrusively be converted to an CompoundPropertyWriterPtr
    //! to use as a parent, from which the error handler policy for
    //! inheritance is also derived.  The remaining optional arguments
    //! can be used to override the ErrorHandlerPolicy, to specify
    //! MetaData, and to set TimeSamplingType.
    template <class CPROP_PTR>
    OPointsSchema( CPROP_PTR iParent,
                   const std::string &iName,

                   const Abc::Argument &iArg0 = Abc::Argument(),
                   const Abc::Argument &iArg1 = Abc::Argument(),
                   const Abc::Argument &iArg2 = Abc::Argument() )
      : OGeomBaseSchema<PointsSchemaInfo>(
                        GetCompoundPropertyWriterPtr( iParent ),
                        iName, iArg0, iArg1, iArg2 )
    {
        AbcA::TimeSamplingPtr tsPtr =
            Abc::GetTimeSampling( iArg0, iArg1, iArg2 );
        uint32_t tsIndex =
            Abc::GetTimeSamplingIndex( iArg0, iArg1, iArg2 );

        // if we specified a valid TimeSamplingPtr, use it to determine the
        // index otherwise we'll use the index, which defaults to the intrinsic
        // 0 index
        if (tsPtr)
        {
            tsIndex = GetCompoundPropertyWriterPtr( iParent )->getObject(
                )->getArchive()->addTimeSampling(*tsPtr);
        }

        // Meta data and error handling are eaten up by
        // the super type, so all that's left is time sampling.
        init( tsIndex );
    }

    template <class CPROP_PTR>
    explicit OPointsSchema( CPROP_PTR iParent,
                            const Abc::Argument &iArg0 = Abc::Argument(),
                            const Abc::Argument &iArg1 = Abc::Argument(),
                            const Abc::Argument &iArg2 = Abc::Argument() )
      : OGeomBaseSchema<PointsSchemaInfo>(
                            GetCompoundPropertyWriterPtr( iParent ),
                            iArg0, iArg1, iArg2 )
    {
        AbcA::TimeSamplingPtr tsPtr =
            Abc::GetTimeSampling( iArg0, iArg1, iArg2 );
        uint32_t tsIndex =
            Abc::GetTimeSamplingIndex( iArg0, iArg1, iArg2 );

        // if we specified a valid TimeSamplingPtr, use it to determine the
        // index otherwise we'll use the index, which defaults to the intrinsic
        // 0 index
        if (tsPtr)
        {
            tsIndex = GetCompoundPropertyWriterPtr( iParent )->getObject(
                    )->getArchive()->addTimeSampling(*tsPtr);
        }

        // Meta data and error handling are eaten up by
        // the super type, so all that's left is time sampling.
        init( tsIndex );
    }

    //! Copy constructor.
    OPointsSchema(const OPointsSchema& iCopy)
        : OGeomBaseSchema<PointsSchemaInfo>()
    {
        *this = iCopy;
    }

    //! Default assignment operator used.

    //-*************************************************************************
    // SCHEMA STUFF
    //-*************************************************************************

    //! Return the time sampling
    AbcA::TimeSamplingPtr getTimeSampling() const
    { return m_positionsProperty.getTimeSampling(); }

    //-*************************************************************************
    // SAMPLE STUFF
    //-*************************************************************************

    //! Get number of samples written so far.
    //! ...
    size_t getNumSamples() const
    { return m_positionsProperty.getNumSamples(); }

    //! Set a sample
    void set( const Sample &iSamp );

    //! Set from previous sample. Will apply to each of positions,
    //! ids, velocities, and widths
    void setFromPrevious( );

    void setTimeSampling( uint32_t iIndex );
    void setTimeSampling( AbcA::TimeSamplingPtr iTime );

    //-*************************************************************************
    // ABC BASE MECHANISMS
    // These functions are used by Abc to deal with errors, validity,
    // and so on.
    //-*************************************************************************

    //! Reset returns this function set to an empty, default
    //! state.
    void reset()
    {
        m_positionsProperty.reset();
        m_idsProperty.reset();
        m_velocitiesProperty.reset();
        m_widthsParam.reset();

        OGeomBaseSchema<PointsSchemaInfo>::reset();
    }

    //! Valid returns whether this function set is
    //! valid.
    bool valid() const
    {
        return ( OGeomBaseSchema<PointsSchemaInfo>::valid() &&
                 m_positionsProperty.valid() &&
                 m_idsProperty.valid() );
    }

    //! unspecified-bool-type operator overload.
    //! ...
    ALEMBIC_OVERRIDE_OPERATOR_BOOL( OPointsSchema::valid() );

protected:
    void init( uint32_t iTsIdx );

    Abc::OP3fArrayProperty m_positionsProperty;
    Abc::OUInt64ArrayProperty m_idsProperty;
    Abc::OV3fArrayProperty m_velocitiesProperty;
    OFloatGeomParam m_widthsParam;

};

//-*****************************************************************************
// SCHEMA OBJECT
//-*****************************************************************************
typedef Abc::OSchemaObject<OPointsSchema> OPoints;

typedef Util::shared_ptr< OPoints > OPointsPtr;

} // End namespace ALEMBIC_VERSION_NS

using namespace ALEMBIC_VERSION_NS;

} // End namespace AbcGeom
} // End namespace Alembic

#endif


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

    <bean id="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>

    <bean id="handlerExceptionResolver" class="org.systemsbiology.addama.commons.web.resolvers.QuietSimpleMappingExceptionResolver">
        <property name="warnLogCategory" value="simple-proxy-svc"/>
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.UnsupportedOperationException">notImplementedView</prop>
                <prop key="org.systemsbiology.addama.commons.web.exceptions.ResourceNotFoundException">resourceNotFoundView</prop>
                <prop key="java.lang.Exception">genericExceptionView</prop>
            </props>
        </property>
    </bean>

    <bean id="notImplementedView" class="org.systemsbiology.addama.commons.web.views.NotImplementedView"/>

    <bean id="resourceNotFoundView" class="org.systemsbiology.addama.commons.web.views.ResourceNotFoundView"/>

    <bean id="genericExceptionView" class="org.systemsbiology.addama.commons.web.views.GenericExceptionView"/>

</beans>


text:
set -e

credentialsFile="~/ScriptStore/.credentials"

function main() {
    if [ $# -eq 1 ]; then
        local key="$1"

        # Expanding the credentials file path to its absolute path:
        credentialsFile=$(eval "realpath $credentialsFile")

        if [ -f $credentialsFile ]; then
            local line=$(cat "$credentialsFile" | grep "$key" | head -1)

            if [ "$line" != "" ]; then
                local value=$(echo $line | cut -d "=" -f 2)

                if [ "$value" != "" ]; then
                    echo $value
                    exit 0
                else
                    echoerr "Value for key '$key' is empty"
                    exit 4
                fi
            else
                echoerr "Key not found: $key"
                exit 3
            fi
        else
            echoerr "Credentials file not found: '$credentialsFile'"
            exit 2
        fi
    else
        echoerr "Usage:"
        echoerr "  $0 <key>"
        echoerr ""
        echoerr "Examples:"
        echoerr "  $0 githubUser"
        echoerr "  $0 githubPass"
        exit 1
    fi
}

function echoerr() {
    >&2 echo $@
}

main $@


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>numpy.nditer.enable_external_loop — NumPy v1.8 Manual</title>
    <link rel="stylesheet" href="../../_static/pythonista.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />

    <link rel="author" title="About these documents" href="../../about.html" />
    <link rel="top" title="NumPy v1.8 Manual" href="../../index.html" />
    <link rel="up" title="numpy.nditer" href="numpy.nditer.html" />
    <link rel="next" title="numpy.nditer.iternext" href="numpy.nditer.iternext.html" />
    <link rel="prev" title="numpy.nditer.debug_print" href="numpy.nditer.debug_print.html" />
    <link rel="shortcut icon" type="image/png" href="../../_static/py.png" />
    <meta name = "viewport" content = "width=device-width,initial-scale=1.0,user-scalable=no;">

Navigation

          index

          next |

          previous |

NumPy v1.8 Manual »

NumPy Reference »

Routines »

Indexing routines »

numpy.nditer »

numpy.nditer.enable_external_loop¶

<tt class="descclassname">nditer.</tt><tt class="descname">enable_external_loop</tt><big>(</big><big>)</big>¶

When the “external_loop” was not used during construction, but
is desired, this modifies the iterator to behave as if the flag
was specified.

    © Copyright 2008-2009, The Scipy community.

    The Python Software Foundation is a non-profit corporation.
    Please donate.

    Last updated on May 03, 2016.
    Found a bug?

    Created using Sphinx 1.2.1.


text:
"""
Whois queries for domains and IPs
"""

import cassava
import re
from scrypture import webapi
class WebAPI(webapi.WebAPI):
    indicators = webapi.list_input('Indicators (Newline Delimited)')
    submit_button = webapi.submit_button('Investigate!')

    def run(self, form_input):
        indicators = form_input['indicators']

        if type(indicators) != list:
            indicators = [x.rstrip() for x in re.split('\n', form_input['indicators'])]
            indicators = [x for x in indicators if x != '']

        whois_info = []
        for indicator in indicators:
            whois_info.append(cassava.whois(indicator))

        headers = []

        return {'output_type' : 'table',
                'output' : whois_info,
                'headers' : whois_info[0].keys()}


text:
package com.cognifide.qa.bb.scope;

import com.cognifide.qa.bb.mapper.annotations.FieldAnnotationsProvider;
import com.google.inject.Injector;
import java.lang.reflect.Field;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.support.pagefactory.DefaultElementLocator;
import org.openqa.selenium.support.pagefactory.ElementLocator;
import org.openqa.selenium.support.pagefactory.ElementLocatorFactory;

public class BobcatDefaultElementLocatorFactory implements ElementLocatorFactory {

  private final SearchContext searchContext;

  private final Injector injector;

  public BobcatDefaultElementLocatorFactory(SearchContext searchContext, Injector injector) {
    this.searchContext = searchContext;
    this.injector = injector;
  }

  public ElementLocator createLocator(Field field) {
    return new DefaultElementLocator(searchContext,
        FieldAnnotationsProvider.create(field, injector));
  }
}


text:
/**
 * Module dependencies.
 */

var connect = require('../');

// $ curl -i http://localhost:3000/

connect(
    connect.profiler()
  , connect.favicon()
  , connect.static(__dirname)
  , function(req, res, next){
    res.end('hello world');
  }
).listen(3000);


text:
package edu.umd.cs.findbugs.ba.ca;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InvokeInstruction;

import edu.umd.cs.findbugs.ba.AbstractDataflowAnalysis;
import edu.umd.cs.findbugs.ba.BasicBlock;
import edu.umd.cs.findbugs.ba.BlockOrder;
import edu.umd.cs.findbugs.ba.CFG;
import edu.umd.cs.findbugs.ba.DataflowAnalysisException;
import edu.umd.cs.findbugs.ba.DepthFirstSearch;
import edu.umd.cs.findbugs.ba.Edge;
import edu.umd.cs.findbugs.ba.Location;
import edu.umd.cs.findbugs.ba.ReversePostOrder;

public class CallListAnalysis extends AbstractDataflowAnalysis<CallList> {
    private DepthFirstSearch dfs;

    // private ConstantPoolGen cpg;
    private Map<InstructionHandle, Call> callMap;

    public CallListAnalysis(CFG cfg, DepthFirstSearch dfs, ConstantPoolGen cpg) {
        this.dfs = dfs;
        // this.cpg = cpg;
        this.callMap = buildCallMap(cfg, cpg);
    }

    private static Map<InstructionHandle, Call> buildCallMap(CFG cfg, ConstantPoolGen cpg) {
        Map<InstructionHandle, Call> callMap = new HashMap<InstructionHandle, Call>();

        for (Iterator<Location> i = cfg.locationIterator(); i.hasNext();) {
            InstructionHandle handle = i.next().getHandle();
            Instruction ins = handle.getInstruction();

            if (ins instanceof InvokeInstruction) {
                InvokeInstruction inv = (InvokeInstruction) ins;
                Call call = new Call(inv.getClassName(cpg), inv.getName(cpg), inv.getSignature(cpg));
                callMap.put(handle, call);
            }
        }

        return callMap;
    }

    public void initEntryFact(CallList fact) {
        fact.clear();
    }

    // public void initResultFact(CallList fact) {
    // fact.setTop();
    // }

    public boolean isForwards() {
        return true;
    }

    public BlockOrder getBlockOrder(CFG cfg) {
        return new ReversePostOrder(cfg, dfs);
    }

    public void makeFactTop(CallList fact) {
        fact.setTop();
    }

    public boolean isTop(CallList fact) {
        return fact.isTop();
    }

    public CallList createFact() {
        return new CallList();
    }

    public boolean same(CallList a, CallList b) {
        return a.equals(b);
    }

    public void meetInto(CallList start, Edge edge, CallList result) throws DataflowAnalysisException {
        CallList merge = CallList.merge(start, result);
        result.copyFrom(merge);
    }

    public void copy(CallList source, CallList dest) {
        dest.copyFrom(source);
    }

    @Override
    public void transferInstruction(InstructionHandle handle, BasicBlock basicBlock, CallList fact)
            throws DataflowAnalysisException {
        Call call = callMap.get(handle);
        if (call != null) {
            fact.add(call);
        }
    }

    @Override
    public boolean isFactValid(CallList fact) {
        return fact.isValid();
    }

    // public static void main(String[] argv) throws Exception {
    // if (argv.length != 1) {
    // System.err.println("Usage: " + CallListAnalysis.class.getName() +
    // " <class file>");
    // System.exit(1);
    // }
    //
    // DataflowTestDriver<CallList, CallListAnalysis> driver =
    // new DataflowTestDriver<CallList, CallListAnalysis>() {
    // @Override
    // public Dataflow<CallList, CallListAnalysis> createDataflow(
    // ClassContext classContext,
    // Method method) throws CFGBuilderException, DataflowAnalysisException {
    // CallListAnalysis analysis = new CallListAnalysis(
    // classContext.getCFG(method),
    // classContext.getDepthFirstSearch(method),
    // classContext.getConstantPoolGen());
    // Dataflow<CallList, CallListAnalysis> dataflow =
    // new Dataflow<CallList, CallListAnalysis>(analysis.cfg, analysis);
    //
    // dataflow.execute();
    //
    // return dataflow;
    // }
    // };
    //
    // driver.execute(argv[0]);
    // }
}


text:
import {html, LitElement} from "lit";
import VariantUtils from "../variant-utils.js";
import ClinicalAnalysisManager from "../../clinical/clinical-analysis-manager.js";
import LitUtils from "../../commons/utils/lit-utils.js";
import NotificationUtils from "../../commons/utils/notification-utils.js";
import OpencgaCatalogUtils from "../../../core/clients/opencga/opencga-catalog-utils.js";
import UtilsNew from "../../../core/utils-new.js";
import "./variant-interpreter-browser-toolbar.js";
import "./variant-interpreter-grid.js";
import "./variant-interpreter-detail.js";
import "../variant-browser-filter.js";
import "../../commons/tool-header.js";
import "../../commons/opencga-active-filters.js";

class VariantInterpreterBrowserTemplate extends LitElement {

    constructor() {
        super();

        // Set status and init private properties
        this._init();
    }

    createRenderRoot() {
        return this;
    }

    static get properties() {
        return {
            clinicalAnalysis: {
                type: Object
            },
            query: {
                type: Object
            },
            opencgaSession: {
                type: Object
            },
            cellbaseClient: {
                type: Object
            },
            toolId: {
                type: String
            },
            settings: {
                type: Object
            },
            config: {
                type: Object
            }
        };
    }

    _init() {
        this._prefix = UtilsNew.randomString(8);

        this.searchActive = true;
        this.variant = null;
        this.query = {};
        this.savedVariants = [];
        this.notSavedVariantIds = 0;
        this.removedVariantIds = 0;

        // Variant inclusion list
        this.variantInclusionState = [];

        this.currentQueryBeforeSaveEvent = null;
        this._config = {};
    }

    connectedCallback() {
        super.connectedCallback();

        this.clinicalAnalysisManager = new ClinicalAnalysisManager(this, this.clinicalAnalysis, this.opencgaSession);
    }

    update(changedProperties) {
        if (changedProperties.has("clinicalAnalysis")) {
            this.clinicalAnalysisObserver();
        }
        if (changedProperties.has("query")) {
            this.queryObserver();
        }
        if (changedProperties.has("opencgaSession")) {
            this.opencgaSessionObserver();
        }
        if (changedProperties.has("settings") || changedProperties.has("config")) {
            this.settingsObserver();
        }
        super.update(changedProperties);
    }

    clinicalAnalysisObserver() {
        // Init saved variants with the primary findings of the main interpretation
        if (this.clinicalAnalysis?.interpretation?.primaryFindings?.length) {
            this.savedVariants = this.clinicalAnalysis?.interpretation?.primaryFindings?.map(v => v.id);
        }
        this.settingsObserver();

        // When refreshing AFTER saving variants we set the same query as before refreshing, check 'onSaveVariants'
        if (this.currentQueryBeforeSaveEvent) {
            this.query = {...this.currentQueryBeforeSaveEvent};
            this.currentQueryBeforeEvent = null;
        }
    }

    queryObserver() {
        if (this.opencgaSession && this.query) {
            this.preparedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
            this.executedQuery = {study: this.opencgaSession.study.fqn, ...this.query};
            this.searchActive = false;
        }
        this.requestUpdate();
    }

    opencgaSessionObserver() {
        this.clinicalAnalysisManager = new ClinicalAnalysisManager(this, this.clinicalAnalysis, this.opencgaSession);

        this.getInclusionVariantIds();
    }

    settingsObserver() {
        if (!this.clinicalAnalysis) {
            return;
        }
        // merge filters
        this._config = {...this.config};

        // filter list, canned filters, detail tabs
        if (this.settings?.menu) {
            this._config.filter = UtilsNew.mergeFiltersAndDetails(this._config?.filter, this.settings);
        }

        if (this.settings?.table) {
            this._config.filter.result.grid = {...this._config.filter.result.grid, ...this.settings.table};
        }

        if (this.settings?.table?.toolbar) {
            this._config.filter.result.grid.toolbar = {...this._config.filter.result.grid.toolbar, ...this.settings.table.toolbar};
        }

        // Check for user configuration
        if (this.toolId && this.opencgaSession.user?.configs?.IVA?.[this.toolId]?.grid) {
            this._config.filter.result.grid = {
                ...this._config.filter.result.grid,
                ...this.opencgaSession.user.configs.IVA[this.toolId].grid,
            };
        }

        // Check to hide the genome browser link
        if (this.settings?.hideGenomeBrowser) {
            this._config.filter.result.grid.showGenomeBrowserLink = false;
        }

        // Add copy.execute functions
        if (this._config.filter.result.grid?.copies?.length > 0) {
            for (const copy of this._config.filter.result.grid?.copies) {
                const originalCopy = this.settings.table?.copies?.find(c => c.id === copy.id);
                if (originalCopy?.execute) {
                    copy.execute = originalCopy.execute;
                }
            }
        }
    }

    getInclusionVariantIds() {
        if (this.opencgaSession?.study?.internal?.configuration?.clinical?.interpretation?.inclusion?.length > 0) {
            const localVariantInclusionState = [];
            const promises = [];
            const inclusionList = this.opencgaSession.study.internal.configuration.clinical.interpretation.inclusion;
            for (const inclusion of inclusionList) {
                localVariantInclusionState.push(
                    {
                        ...inclusion,
                        variants: []
                    }
                );
                const inclusionQuery = {
                    ...inclusion.query,

                    // Additional filters
                    sample: this.clinicalAnalysis.proband.samples[0].id,
                    include: "id,studies.files,studies.samples",
                    count: false,
                    study: this.opencgaSession.study.fqn,
                };
                promises.push(this.opencgaSession.opencgaClient.clinical().queryVariant(inclusionQuery));
            }

            // Process all results and update object state
            Promise.all(promises).then(values => {
                for (let i = 0; i < values.length; i++) {
                    localVariantInclusionState[i].variants = values[i].responses[0].results;
                }
                this.variantInclusionState = localVariantInclusionState;
                this.requestUpdate();
            });
        }
    }

    onQueryComplete() {
        this.searchActive = true;
        this.requestUpdate();
    }

    onSelectVariant(e) {
        this.variantId = e.detail.id;
        this.variant = e.detail.row;
        this.requestUpdate();
    }

    onCheckVariant(e) {
        const rows = Array.isArray(e.detail.row) ? e.detail.row : [e.detail.row];
        rows.forEach(row => {
            if (e.detail.checked) {
                this.clinicalAnalysisManager.addVariant(row);
            } else {
                this.clinicalAnalysisManager.removeVariant(row);
            }
        });
    }

    onUpdateVariant(e) {
        const rows = Array.isArray(e.detail.row) ? e.detail.row : [e.detail.row];
        rows.forEach(row => {
            this.clinicalAnalysisManager.updateSingleVariant(row);
        });
        this.requestUpdate();
    }

    onFilterVariants(e) {
        const lockedFields = [...this._config?.filter?.activeFilters?.lockedFields.map(key => key.id), "study"];
        const variantIds = e.detail.variants.map(v => v.id);
        this.query = {...UtilsNew.filterKeys(this.executedQuery, lockedFields), id: variantIds.join(",")};
        this.requestUpdate();
    }

    onResetVariants(e) {
        this.clinicalAnalysisManager.reset();

        this.preparedQuery = {...this.preparedQuery};
        this.executedQuery = {...this.executedQuery};
        delete this.preparedQuery.id;
        delete this.executedQuery.id;

        this.clinicalAnalysis = {...this.clinicalAnalysis};
    }

    onSaveVariants(e) {
        // We save current query so we can execute the same query after refreshing, check 'clinicaAnalysisObserver'
        this.currentQueryBeforeSaveEvent = this.query;

        const comment = e.detail.comment;
        this.clinicalAnalysisManager.updateInterpretationVariants(comment, () => {
            LitUtils.dispatchCustomEvent(this, "clinicalAnalysisUpdate", null, {
                clinicalAnalysis: this.clinicalAnalysis,
            }, null, {bubbles: true, composed: true});
        });
    }

    onVariantFilterChange(e) {
        this.preparedQuery = e.detail.query;
        this.requestUpdate();
    }

    onVariantFilterSearch(e) {
        this.preparedQuery = e.detail.query;
        this.executedQuery = e.detail.query;
        this.query = {...e.detail.query}; // We need to update the internal query to propagate to filters
        this.requestUpdate();
    }

    onActiveFilterChange(e) {
        VariantUtils.validateQuery(e.detail);
        this.query = {...e.detail};
        this.requestUpdate();
    }

    onSearch() {
        this.onVariantFilterSearch({
            detail: {
                query: this.preparedQuery,
            },
        });
    }

    onActiveFilterClear() {
        const lockedFields = [...this._config?.filter?.activeFilters?.lockedFields.map(key => key.id)];
        let _query = {
            study: this.opencgaSession.study.fqn
        };

        // Reset filters default
        lockedFields.forEach(field => {
            _query = {
                ..._query,
                [field]: this.query[field]
            };
        });

        // Check if panelLock is enabled
        if (this.clinicalAnalysis.panelLock) {
            _query.panel = this.query.panel;
            _query.panelIntersection = true;
        }
        this.query = UtilsNew.objectClone(_query);

        this.requestUpdate();

    }

    async onGridConfigSave(e) {
        const newGridConfig = {...e.detail.value};

        // Remove highlights and copies configuration from new config
        delete newGridConfig.highlights;
        // delete newConfig.copies;

        // Update user configuration
        try {
            await OpencgaCatalogUtils.updateGridConfig(this.opencgaSession, this.toolId, newGridConfig);
            this.settingsObserver();
            this.requestUpdate();

            NotificationUtils.dispatch(this, NotificationUtils.NOTIFY_SUCCESS, {
                message: "Configuration saved",
            });
        } catch (error) {
            NotificationUtils.dispatch(this, NotificationUtils.NOTIFY_RESPONSE, error);
        }
    }

    render() {
        // Check Project exists
        if (!this.opencgaSession?.study) {
            return html`

No project available to browse. Please login to continue

            `;
        }

        return html`

            ${this._config.showTitle ? html`
                <tool-header
                    title="${this.clinicalAnalysis ? `${this._config.title} (${this.clinicalAnalysis.id})` : this._config.title}"
                    icon="${this._config.icon}">
                </tool-header>
            ` : null}

            ${this.clinicalAnalysis.interpretation.locked ? html`

                            Interpretation locked: you cannot modify this interpretation. You can unlock the interpretation in
                            Case Info >> Interpretation Manager.

` : null
            }

                        <button type="button" class="btn btn-primary btn-block" ?disabled="${!this.searchActive}" @click="${this.onSearch}">

                            ${this._config.filter?.searchButtonText || "Search"}
                        </button>

                    <variant-browser-filter
                        .opencgaSession="${this.opencgaSession}"
                        .query="${this.query}"
                        .clinicalAnalysis="${this.clinicalAnalysis}"
                        .cellbaseClient="${this.cellbaseClient}"
                        .populationFrequencies="${POPULATION_FREQUENCIES}"
                        .consequenceTypes="${SAMPLE_STATS_CONSEQUENCE_TYPES}"
                        .config="${this._config.filter}"
                        @queryChange="${this.onVariantFilterChange}"
                        @querySearch="${this.onVariantFilterSearch}">
                    </variant-browser-filter>

                        <variant-interpreter-browser-toolbar
                            .clinicalAnalysis="${this.clinicalAnalysis}"
                            .state="${this.clinicalAnalysisManager.state}"
                            .variantInclusionState="${this.variantInclusionState}"
                            .write="${OpencgaCatalogUtils.checkPermissions(this.opencgaSession.study, this.opencgaSession.user.id, "WRITE_CLINICAL_ANALYSIS")}"
                            @filterVariants="${this.onFilterVariants}"
                            @resetVariants="${this.onResetVariants}"
                            @saveInterpretation="${this.onSaveVariants}">
                        </variant-interpreter-browser-toolbar>

                            <opencga-active-filters
                                resource="VARIANT"
                                .opencgaSession="${this.opencgaSession}"
                                .clinicalAnalysis="${this.clinicalAnalysis}"
                                .defaultStudy="${this.opencgaSession.study.fqn}"
                                .query="${this.preparedQuery}"
                                .executedQuery="${this.executedQuery}"
                                .filters="${this._config.filter.activeFilters.filters}"
                                .alias="${this._config.activeFilterAlias}"
                                .genotypeSamples="${this.genotypeSamples}"
                                .modeInheritance="${this.modeInheritance}"
                                .config="${this._config.filter.activeFilters}"
                                @activeFilterChange="${this.onActiveFilterChange}"
                                @activeFilterClear="${this.onActiveFilterClear}">
                            </opencga-active-filters>

                                ${!this._config.filter.result.grid.isRearrangement ? html`
                                    <variant-interpreter-grid
                                        .opencgaSession="${this.opencgaSession}"
                                        .clinicalAnalysis="${this.clinicalAnalysis}"
                                        .query="${this.executedQuery}"
                                        .review="${true}"
                                        .config="${this._config.filter.result.grid}"
                                        @queryComplete="${this.onQueryComplete}"
                                        @selectrow="${this.onSelectVariant}"
                                        @updaterow="${this.onUpdateVariant}"
                                        @checkrow="${this.onCheckVariant}"
                                        @gridconfigsave="${this.onGridConfigSave}">
                                    </variant-interpreter-grid>` : html`
                                    <variant-interpreter-rearrangement-grid
                                        .opencgaSession="${this.opencgaSession}"
                                        .clinicalAnalysis="${this.clinicalAnalysis}"
                                        .query="${this.executedQuery}"
                                        .review="${true}"
                                        .config="${this._config.filter.result.grid}"
                                        @queryComplete="${this.onQueryComplete}"
                                        @selectrow="${this.onSelectVariant}"
                                        @updaterow="${this.onUpdateVariant}"
                                        @checkrow="${this.onCheckVariant}">
                                    </variant-interpreter-rearrangement-grid>`
                                }

                                <variant-interpreter-detail
                                    .opencgaSession="${this.opencgaSession}"
                                    .clinicalAnalysis="${this.clinicalAnalysis}"
                                    .variant="${this.variant}"
                                    .cellbaseClient="${this.cellbaseClient}"
                                    .config=${this._config.filter.detail}>
                                </variant-interpreter-detail>

        `;
    }

}

customElements.define("variant-interpreter-browser-template", VariantInterpreterBrowserTemplate);


text:
'use strict';

var mongoose = require('mongoose'),
  deepPopulate = require('mongoose-deep-populate'),
  Schema = mongoose.Schema;

var ProtocolSchema = new Schema({
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
  },
  processes: {
    type: Schema.ObjectId,
    ref: 'Graph'
  },
  finalstatemachines: [{
    type: Schema.ObjectId,
    ref: 'Graph'
  }],
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  deleted: {
    type: Boolean,
    default: false
  },
  created: {
    type: Date,
    default: Date.now
  }
});

ProtocolSchema.plugin(deepPopulate, {
  populate: {
    'user': {
      select: 'displayName'
    }
  }
});

mongoose.model('Protocol', ProtocolSchema);


text:
package com.harms.stash.plugin.jenkins.job.intergration;

import java.io.Serializable;

/**
 *
 * @author fharms
 *
 */
public interface JobTrigger extends Serializable {

    /**
     * @return the next CI server from the list of servers
     */
    public String nextCIServer(String slug);

    /**
     * Validate the it got the correct settings before it trigger a build
     * @param jenkinsBaseUrl
     * @param slug
     * @return
     */
    public boolean validateSettings(String jenkinsBaseUrl, String slug);

    /**
     * @param toRefRepositoryId - Id to the repository
     * @param latestChangeset - The SHA commit id
     * @param pullRequestId - The current pull-request id
     * @param pullRequestTitle - The title of the pull-request
     * @param slug - The slug id
     * @param eventType - The type of job trigger event
     * @param retryCount - Number of current retries
     * @param baseUrl - the Jenkins CI base URL
     * @param projectId - The project id
     * @param fromBranch - From Branch name, the origin of the pull request
     * @param toBranch - To Branch name, the destination of the pull request
     */
    public void triggerBuild(Integer toRefRepositoryId, String latestChangeset, Long pullRequestId, String pullRequestTitle, String slug, TriggerRequestEvent eventType,
            int retryCount, String baseUrl, String projectId, String fromBranch, String toBranch);

}


text:
package com.sissi.pipeline;

/**
 * @author kim 2013年12月23日
 */
public interface OutputBuilder {

	public Output build(Transfer transfer);
}


text:
/* md5Checksum.c - checksumming routine on the client side
 */

#include "irods_stacktrace.hpp"
#include "irods_hasher_factory.hpp"
#include "getRodsEnv.h"
#include "irods_log.hpp"
#include "objInfo.h"
#include "MD5Strategy.hpp"
#include "rodsKeyWdDef.h"
#include "rcMisc.h"
#include "checksum.hpp"

#include <fstream>
#include "irods_stacktrace.hpp"

#define HASH_BUF_SZ (1024*1024)

int chksumLocFile(
    char*       _file_name,
    char*       _checksum,
    const char* _hash_scheme ) {
    if ( !_file_name ||
            !_checksum  ||
            !_hash_scheme ) {
        rodsLog(
            LOG_ERROR,
            "chksumLocFile :: null input param - %p %p %p",
            _file_name,
            _checksum,
            _hash_scheme );
        return SYS_INVALID_INPUT_PARAM;
    }

    // =-=-=-=-=-=-=-
    // capture client side configuration
    rodsEnv env;
    int status = getRodsEnv( &env );
    if ( status < 0 ) {
        return status;
    }

    // =-=-=-=-=-=-=-
    // capture the configured scheme if it is valid
    std::string env_scheme( irods::MD5_NAME );
    if ( strlen( env.rodsDefaultHashScheme ) > 0 ) {
        env_scheme = env.rodsDefaultHashScheme;

    }

    // =-=-=-=-=-=-=-
    // capture the configured hash match policy if it is valid
    std::string env_policy;
    if ( strlen( env.rodsMatchHashPolicy ) > 0 ) {
        env_policy = env.rodsMatchHashPolicy;
        // =-=-=-=-=-=-=-
        // hash scheme keywords are all lowercase
        std::transform(
            env_scheme.begin(),
            env_scheme.end(),
            env_scheme.begin(),
            ::tolower );
    }

    // =-=-=-=-=-=-=-
    // capture the incoming scheme if it is valid
    std::string hash_scheme;
    if ( _hash_scheme &&
            strlen( _hash_scheme ) > 0 &&
            strlen( _hash_scheme ) < NAME_LEN ) {
        hash_scheme = _hash_scheme;
        // =-=-=-=-=-=-=-
        // hash scheme keywords are all lowercase
        std::transform(
            hash_scheme.begin(),
            hash_scheme.end(),
            hash_scheme.begin(),
            ::tolower );
    }
    else {
        hash_scheme = env_scheme;

    }

    // =-=-=-=-=-=-=-
    // hash scheme keywords are all lowercase
    std::transform(
        hash_scheme.begin(),
        hash_scheme.end(),
        hash_scheme.begin(),
        ::tolower );
    std::transform(
        env_scheme.begin(),
        env_scheme.end(),
        env_scheme.begin(),
        ::tolower );

    // =-=-=-=-=-=-=-
    // verify checksum scheme against configuration
    // if requested
    std::string final_scheme( env_scheme );
    if ( !hash_scheme.empty() ) {
        if ( !env_policy.empty() ) {
            if ( irods::STRICT_HASH_POLICY == env_policy ) {
                if ( env_scheme != hash_scheme ) {
                    return USER_HASH_TYPE_MISMATCH;
                }
            }
        }

        final_scheme = hash_scheme;
    }

    // =-=-=-=-=-=-=-
    // init the hasher object
    irods::Hasher hasher;
    irods::error ret = irods::getHasher(
                           final_scheme,
                           hasher );
    if ( !ret.ok() ) {
        irods::log( PASS( ret ) );
        return ret.code();

    }

    // =-=-=-=-=-=-=-
    // open the local file
    std::ifstream in_file(
        _file_name,
        std::ios::in | std::ios::binary );
    if ( !in_file.is_open() ) {
        status = UNIX_FILE_OPEN_ERR - errno;
        rodsLogError(
            LOG_ERROR,
            status,
            "chksumLocFile - fopen failed for %s, status = %d",
            _file_name,
            status );
        return status;
    }

    std::string buffer_read;
    buffer_read.resize( HASH_BUF_SZ );

    while ( in_file.read( &buffer_read[0], HASH_BUF_SZ ) ) {
        hasher.update( buffer_read );
    }

    if ( in_file.eof() ) {
        if ( in_file.gcount() > 0 ) {
            buffer_read.resize( in_file.gcount() );
            hasher.update( buffer_read );
        }
    } else {
        status = UNIX_FILE_READ_ERR - errno;
        rodsLogError(
                     LOG_ERROR,
                     status,
                     "chksumLocFile - read() failed for %s, status = %d",
                     _file_name,
                     status );
        return status;
    }

    // =-=-=-=-=-=-=-
    // capture the digest
    std::string digest;
    hasher.digest( digest );
    strncpy(
        _checksum,
        digest.c_str(),
        digest.size() + 1 );

    return 0;

} // chksumLocFile

int verifyChksumLocFile(
    char *fileName,
    char *myChksum,
    char *chksumStr ) {
    // =-=-=-=-=-=-=-
    // extract scheme from checksum string
    std::string scheme;
    irods::error ret = irods::get_hash_scheme_from_checksum( myChksum, scheme );
    if ( !ret.ok() ) {
        //irods::log( PASS( ret ) );
    }

    char chksumBuf[CHKSUM_LEN];
    if ( chksumStr == NULL ) {
        chksumStr = chksumBuf;
    }

    int status = chksumLocFile( fileName, chksumStr, scheme.c_str() );
    if ( status < 0 ) {
        return status;
    }
    if ( strcmp( myChksum, chksumStr ) != 0 ) {
        return USER_CHKSUM_MISMATCH;
    }
    return 0;
}

int
hashToStr( unsigned char *digest, char *digestStr ) {
    int i;
    char *outPtr = digestStr;

    for ( i = 0; i < 16; i++ ) {
        sprintf( outPtr, "%02x", digest[i] );
        outPtr += 2;
    }

    return 0;
}

/* rcChksumLocFile - chksum a local file and put the result in the
 * condInput.
 * Input -
 *	char *fileName - the local file name
 *	char *chksumFlag - the chksum flag. valid flags are
 *         VERIFY_CHKSUM_KW and REG_CHKSUM_KW.
 *	keyValPair_t *condInput - the result is put into this struct
 */

int
rcChksumLocFile( char *fileName, char *chksumFlag, keyValPair_t *condInput, const char* _scheme ) {
    char chksumStr[NAME_LEN];
    int status;

    if ( condInput == NULL || chksumFlag == NULL || fileName == NULL ) {
        rodsLog( LOG_NOTICE,
                 "rcChksumLocFile: NULL input" );
        return USER__NULL_INPUT_ERR;
    }

    if ( strcmp( chksumFlag, VERIFY_CHKSUM_KW ) != 0 &&
            strcmp( chksumFlag, REG_CHKSUM_KW ) != 0 &&
            strcmp( chksumFlag, RSYNC_CHKSUM_KW ) != 0 ) {
        rodsLog( LOG_NOTICE,
                 "rcChksumLocFile: bad input chksumFlag %s", chksumFlag );
        return USER_BAD_KEYWORD_ERR;
    }

    status = chksumLocFile( fileName, chksumStr, _scheme );
    if ( status < 0 ) {
        return status;
    }

    addKeyVal( condInput, chksumFlag, chksumStr );

    return 0;
}


text:
require 'spec_helper'

describe DatabaseReplica do
  let(:flipper_key) { 'test_read_from_read_replica' }

  before do
    allow(Standby).to receive(:on_standby).and_call_original
  end

  describe '::read' do
    it 'defaults to reading from the primary db' do
      described_class.read(flipper_key) { nil }
      expect(Standby).not_to have_received(:on_standby)
    end

    context 'with read replica feature flag on' do
      before do
        Panoptes.flipper.enable(flipper_key)
      end

      it 'uses standby gem to read from replica' do
        described_class.read(flipper_key) { nil }
        expect(Standby).to have_received(:on_standby)
      end
    end
  end

  describe '::read_without_timeout' do
    let(:pg_statment_timeout) { Panoptes.pg_statement_timeout }
    let(:default_set_timeout) { "SET statement_timeout = #{pg_statment_timeout}" }
    let(:no_timeout) { 'SET statement_timeout = 0' }
    let(:connection_double) do
      connection_double = instance_double('ActiveRecord::ConnectionAdapters::PostgreSQLAdapter')
      allow(connection_double).to receive(:execute)
      connection_double
    end

    it 'defaults to reading from the primary db' do
      described_class.read_without_timeout(flipper_key) { nil }
      expect(Standby).not_to have_received(:on_standby)
    end

    # rubocop:disable RSpec/MultipleExpectations
    it 'sets the connection to not timeout and resets to default' do
      allow(ActiveRecord::Base).to receive(:connection).and_return(connection_double)
      described_class.read_without_timeout(flipper_key) { nil }

      expect(connection_double).to have_received(:execute).with(no_timeout).ordered
      expect(connection_double).to have_received(:execute).with(default_set_timeout).ordered
    end
    # rubocop:enable RSpec/MultipleExpectations

    context 'with read replica feature flag on' do
      before do
        Panoptes.flipper.enable(flipper_key)
      end

      it 'uses standby gem to read from replica' do
        described_class.read_without_timeout(flipper_key) { nil }
        expect(Standby).to have_received(:on_standby)
      end

      # rubocop:disable RSpec/MultipleExpectations
      it 'sets the connection to not timeout and resets to default' do
        allow(ActiveRecord::Base).to receive(:connection).and_return(connection_double)
        described_class.read_without_timeout(flipper_key) { nil }

        expect(connection_double).to have_received(:execute).with(no_timeout).ordered
        expect(connection_double).to have_received(:execute).with(default_set_timeout).ordered
      end
      # rubocop:enable RSpec/MultipleExpectations
    end
  end
end


text:
presenter
=========

Automates the display of powerpoint presentations