text:
package com.example.saurab.abc.base.activity;

/**
 * Created by saurab on 2/6/2016.
 */
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DialogFragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Build;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Base64;
import android.util.Log;
import android.view.Display;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.saurab.abc.R;
import com.example.saurab.abc.async.callback.AsyncCallBackInterface;
import com.example.saurab.abc.util.Constants;
import com.example.saurab.abc.util.SharedPreferenceHelper;
import com.example.saurab.abc.vo.HttpResponseVO;
import com.google.android.gms.maps.model.LatLng;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class BaseActivity extends FragmentActivity implements AsyncCallBackInterface{

    public static int STORE_LOCATION = 0;
    public static int MULTI_STORE_LOCATION = 1;
    public static int ORDER_LIST = 2;
    public static int ORDER_DETAILS = 3;
    public static int FEED_BACK = 4;
    public static int THANK_YOU = 5;
    public static int CHANGE_PASSWORD = 6;

    protected Map<String, String> getCommonAuthHeaders(String name,
                                                       String email, String pwd) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(
                Constants.HTTP_HEADER_AUTHORIZATION,
                Constants.HTTP_HEADER_AUTHORIZATION_BASIC_APPEND
                        + " "
                        + BaseActivity.getAuthorizationHeader(name, email, pwd));
        headers.put(Constants.HTTP_HEADER_CONTENT_TYPE,
                Constants.HTTP_HEADER_ACCEPT_VAUE_JSON);
        return headers;
    }

    protected Map<String, String> getCommonAuthHeaders(String usr, String pwd) {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put(
                Constants.HTTP_HEADER_AUTHORIZATION,
                Constants.HTTP_HEADER_AUTHORIZATION_BASIC_APPEND
                        + " "
                        + BaseActivity.getAuthorizationHeader(usr, pwd));
        headers.put(Constants.HTTP_HEADER_CONTENT_TYPE,
                Constants.HTTP_HEADER_ACCEPT_VAUE_JSON);
        headers.put(Constants.HTTP_HEADER_TOKEN,
                SharedPreferenceHelper.getToken(this));
        return headers;
    }

    protected Map<String, String> getCommonAuthHeaders() {
        Map<String, String> headers = new HashMap<String, String>();
       /* headers.put(
                Constants.HTTP_HEADER_AUTHORIZATION,*/
                /*Constants.HTTP_HEADER_AUTHORIZATION_BASIC_APPEND
                        + Constants.SPACE
                        + BaseActivity.getAuthorizationHeader(
                        SharedPreferenceHelper.getUserEmailAndPassword(
                                this).getEmailID(),
                        SharedPreferenceHelper.getUserEmailAndPassword(
                                this).getPassword()));*/
        headers.put(Constants.HTTP_HEADER_CONTENT_TYPE,
                Constants.HTTP_HEADER_ACCEPT_VAUE_JSON);
        return headers;
    }

    protected void gotoClass(Class<?> classTo) {
        startActivity(new Intent(this, classTo));
        finish();
    }

    protected void gotoClassWithoutfinish(Class<?> classTo) {
        startActivity(new Intent(this, classTo));

    }

   /* @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    protected Point getScreenDimentions() {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        return size;
    }*/

    protected void removeFragmentFromStack() {
        final FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.popBackStack(null,
                FragmentManager.POP_BACK_STACK_INCLUSIVE);

    }

    protected void clearCurrentFragment() {
        FragmentManager manager = getSupportFragmentManager();
        if (manager.getBackStackEntryCount() > 0) {
            FragmentManager.BackStackEntry first = manager.getBackStackEntryAt(0);
            manager.popBackStack(first.getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
        }
    }

    /*protected void addfragment(Fragment fragment) {
        FragmentTransaction transaction;
        transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.home_frame_layout_for_fragments, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    protected void addfragment(Fragment fragment, boolean isBackStack) {
        FragmentTransaction transaction;
        transaction = getSupportFragmentManager()
                .beginTransaction();
        transaction.replace(R.id.home_frame_layout_for_fragments, fragment);
        if (isBackStack) {
            transaction.addToBackStack(null);
        }
        transaction.commit();
    }*/
    public static Bitmap getFacebookProfilePicture(String userID) {
        Bitmap bitmap = null;
        try {
            URL imageURL = new URL("https://graph.facebook.com/" + userID + "/picture?type=large");
            bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    // hide softkey pad
    public static void hideSoftKeyboard(Activity activity) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }

    // load google plus profile image

    protected class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public LoadProfileImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }

    protected void gotoClass(Intent intent) {
        startActivity(intent);
        finish();
    }

    public static String getAuthorizationHeader(String uname, String email,
                                                String pswd) {
        return Base64.encodeToString((uname + Constants.STR_COLON + email
                + Constants.STR_COLON + pswd).getBytes(), Base64.NO_WRAP);
    }

    public static String getAuthorizationHeader(String uname, String pswd) {
        return Base64
                .encodeToString(
                        (uname + Constants.STR_COLON + pswd).getBytes(),
                        Base64.NO_WRAP);
    }

    protected boolean isOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        return (cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo()
                .isConnectedOrConnecting());
    }

    protected void showMessage(String msg) {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        //  alertDialog.setTitle(Constants.STR_INFO);
        alertDialog.setMessage(msg);
        alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                Constants.STR_CLOSE, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    // protected Intent buildIntentForUserNameAndPassword(Class<?> classTo) {
    // Intent intent = new Intent(this, classTo);
    // intent.putExtra("username", SharedPreferenceHelper
    // .getUserNameAndPassword(this).getUserName());
    // intent.putExtra("password", SharedPreferenceHelper
    // .getUserNameAndPassword(this).getUserName());
    // startActivity(intent);
    // finish();
    // return intent;
    //
    // }

    public String getSubLocality(double lattitude, double longitude) {
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        String sublocality = "";
        try {
            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                sublocality = address.getSubLocality(); //+" ,"+addresses.get(0).getSubLocality()
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sublocality;
    }

    protected void showErrorMessage(String msg) {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        // alertDialog.setTitle(Constants.STR_ERROR);
        alertDialog.setMessage(msg);
        alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                Constants.STR_CLOSE, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                    }
                });
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    public String getCompleteAddressString(double LATITUDE, double LONGITUDE) {
        String strAdd = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        try {
            List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
            if (addresses != null) {
                Address returnedAddress = addresses.get(0);
                StringBuilder strReturnedAddress = new StringBuilder("");

                for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) {
                    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
                }
                strAdd = strReturnedAddress.toString();
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return strAdd;
    }

    protected void showErrorMessage(String msg, final Intent intent) {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        //alertDialog.setTitle(Constants.STR_ERROR);
        alertDialog.setMessage(msg);
        alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                Constants.STR_CLOSE, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                        gotoClass(intent);
                    }
                });
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    protected void showAlert(String message, String positive, String negative, final Intent neg, final Intent pos) {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);

        // Setting Dialog Title
        alertDialog.setTitle("Kid details...");

        // Setting Dialog Message
        alertDialog.setMessage(message);

        // Setting Positive "Yes" Button
        alertDialog.setCancelable(false);
        alertDialog.setPositiveButton(positive, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                gotoClass(pos);
                //  Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                // dialog.dismiss();
            }
        });

        alertDialog.setNegativeButton(negative, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                // Write your code here to invoke NO event
                //  Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();
                gotoClass(neg);
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

// getting location from address

    protected LatLng getLocationFromAddress(String strAddress) {

        Geocoder coder = new Geocoder(this);
        List<Address> address = null;
        try {
            address = coder.getFromLocationName(strAddress, 5);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {

        }
        if (address == null) {
            // return null;
        }
        Address location = address.get(0);
        double lat = (double) location.getLatitude();
        double lng = (double) location.getLongitude();

        LatLng dest = new LatLng(lat, lng);
        return dest;

    }

    // for geting location...

    public Location getLocation() {
        Location location = null;
        try {
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
            boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            boolean canGetLocation;

            double latitude;
            double longitude;
            long MIN_TIME_BW_UPDATES = 1000;
            float MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
            if (!isGPSEnabled && !isNetworkEnabled) {
            } else {
                canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 10, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {

                        }

                        @Override
                        public void onStatusChanged(String provider, int status, Bundle extras) {

                        }

                        @Override
                        public void onProviderEnabled(String provider) {

                        }

                        @Override
                        public void onProviderDisabled(String provider) {

                        }
                    });
                    Log.d("Network", "Network Enabled");
                    if (locationManager != null) {
                        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 10, new LocationListener() {
                            @Override
                            public void onLocationChanged(Location location) {

                            }

                            @Override
                            public void onStatusChanged(String provider, int status, Bundle extras) {

                            }

                            @Override
                            public void onProviderEnabled(String provider) {

                            }

                            @Override
                            public void onProviderDisabled(String provider) {

                            }
                        });
                        Log.d("GPS", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return location;
    }

    protected void showMessage(String msg, final Intent intent) {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        //alertDialog.setTitle(Constants.STR_INFO);
        alertDialog.setMessage(msg);
        alertDialog.setButton(DialogInterface.BUTTON_NEUTRAL,
                Constants.STR_CLOSE, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        alertDialog.dismiss();
                        gotoClass(intent);
                    }
                });
        alertDialog.setCancelable(false);
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.show();
    }

    public static boolean isNullOrEmpty(EditText s) {
        return s == null || s.getText() == null || s.getText().toString() == null
                || s.getText().toString().trim().equals(Constants.STR_BLANK);
    }

    public static boolean isNullOrEmpty(TextView s) {
        return s == null || s.getText() == null || s.getText().toString() == null
                || s.getText().toString().trim().equals(Constants.STR_BLANK);
    }

    public static boolean isNullOrEmpty(String s) {
        return s == null || s.toString().trim().equals(Constants.STR_BLANK)
                || s.equalsIgnoreCase(Constants.STR_NULL);
    }

    protected void setHeader(String text) {
       // ((TextView) findViewById(R.id.header_text)).setText(text);
    }

    protected void setHeaderBack(Class classTo) {

    }

    protected String getLocationName(double lattitude, double longitude) {

        String cityName = "Not Found";
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        try {

            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            cityName = addresses.get(0).getLocality();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cityName;

    }

    public String getAddressLine(double lattitude, double longitude) {
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        String addressLine = "";
        try {
            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                addressLine = address.getAddressLine(0) + " ," + addresses.get(0).getSubLocality();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addressLine;
    }

    public String getState(double lattitude, double longitude) {
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        String state = "";
        try {
            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                state = address.getAdminArea();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return state;
    }

    public String getCountryNmae(double lattitude, double longitude) {
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        String country = "";
        try {
            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                country = address.getCountryName();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return country;
    }

    // get pincode..

    public String getPinCode(double lattitude, double longitude) {
        Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
        String pincode = "";
        try {
            List<Address> addresses = gcd.getFromLocation(lattitude, longitude,
                    1);

            if (addresses != null && addresses.size() > 0) {
                Address address = addresses.get(0);
                pincode = address.getPostalCode();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return pincode;
    }

    protected Location getLastKnownLocation() {
        LocationManager mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        List<String> providers = mLocationManager.getProviders(true);
        Location bestLocation = null;
        for (String provider : providers) {
            Location l = mLocationManager.getLastKnownLocation(provider);

            if (l == null) {
                continue;
            }
            if (bestLocation == null
                    || l.getAccuracy() < bestLocation.getAccuracy()) {
                bestLocation = l;
            }
        }
        if (bestLocation == null) {
            return null;
        }
        return bestLocation;
    }

   /* public void callSearch(Context context) {
        DialogFragment newFragment = SearchPopUp.newInstance();
        newFragment.show(getFragmentManager(), "Enter Info");

    }*/

    @Override
    public void asyncCallBackFunction(HttpResponseVO result, String apiUrl) {

    }
}


text:
A light-weight SockJS client for Bunkr https://bunkr.chat

# Install

`npm install bunkr-client --save`

# Usage

```javascript
var Client = require('bunkr-client');

const client = new Client('https://bunkr.chat', 'iEQMABvhNfnC4XnMHXDsZ92TFLvikuhNA559m3gMFmEC4W');
client.connect()
  .then(client => client.get('account'))
  .then(packet => {
    console.log(packet.body);
  });
```

# License

MIT

redpajama_set_name: RedPajamaGithub


text:
package com.facebook.buck.cxx;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import com.facebook.buck.rules.DefaultTargetNodeToBuildRuleTransformer;
import com.facebook.buck.cli.FakeBuckConfig;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.BuildTargetFactory;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildTargetSourcePath;
import com.facebook.buck.rules.FakeBuildRule;
import com.facebook.buck.rules.FakeBuildRuleParamsBuilder;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.args.Arg;
import com.facebook.buck.rules.args.SourcePathArg;
import com.facebook.buck.rules.args.StringArg;
import com.facebook.buck.rules.coercer.FrameworkPath;
import com.facebook.buck.step.Step;
import com.google.common.base.Functions;
import com.google.common.base.Optional;
import com.google.common.base.Predicates;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;

import org.junit.Test;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Pattern;

public class CxxLibraryTest {

  @Test
  public void cxxLibraryInterfaces() {
    SourcePathResolver pathResolver = new SourcePathResolver(
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())
    );
    BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
    BuildRuleParams params = new FakeBuildRuleParamsBuilder(target).build();
    CxxPlatform cxxPlatform =
        DefaultCxxPlatforms.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));

    // Setup some dummy values for the header info.
    final BuildTarget publicHeaderTarget = BuildTargetFactory.newInstance("//:header");
    final BuildTarget publicHeaderSymlinkTreeTarget = BuildTargetFactory.newInstance("//:symlink");
    final BuildTarget privateHeaderTarget = BuildTargetFactory.newInstance("//:privateheader");
    final BuildTarget privateHeaderSymlinkTreeTarget = BuildTargetFactory.newInstance(
        "//:privatesymlink");

    // Setup some dummy values for the library archive info.
    final BuildRule archive = new FakeBuildRule("//:archive", pathResolver);

    // Setup some dummy values for the library archive info.
    final BuildRule sharedLibrary = new FakeBuildRule("//:shared", pathResolver);
    final Path sharedLibraryOutput = Paths.get("output/path/lib.so");
    final String sharedLibrarySoname = "lib.so";

    // Construct a CxxLibrary object to test.
    FakeCxxLibrary cxxLibrary = new FakeCxxLibrary(
        params,
        pathResolver,
        publicHeaderTarget,
        publicHeaderSymlinkTreeTarget,
        privateHeaderTarget,
        privateHeaderSymlinkTreeTarget,
        archive,
        sharedLibrary,
        sharedLibraryOutput,
        sharedLibrarySoname,
        ImmutableSortedSet.<BuildTarget>of());

    // Verify that we get the header/symlink targets and root via the CxxPreprocessorDep
    // interface.
    CxxPreprocessorInput expectedPublicCxxPreprocessorInput = CxxPreprocessorInput.builder()
        .addIncludes(
            CxxSymlinkTreeHeaders.builder()
                .setIncludeType(CxxPreprocessables.IncludeType.LOCAL)
                .putNameToPathMap(
                    Paths.get("header.h"),
                    new BuildTargetSourcePath(publicHeaderTarget))
                .setRoot(new BuildTargetSourcePath(publicHeaderSymlinkTreeTarget))
                .build())
        .build();
    assertEquals(
        expectedPublicCxxPreprocessorInput,
        cxxLibrary.getCxxPreprocessorInput(
            cxxPlatform,
            HeaderVisibility.PUBLIC));

    CxxPreprocessorInput expectedPrivateCxxPreprocessorInput = CxxPreprocessorInput.builder()
        .addIncludes(
            CxxSymlinkTreeHeaders.builder()
                .setIncludeType(CxxPreprocessables.IncludeType.LOCAL)
                .setRoot(new BuildTargetSourcePath(privateHeaderSymlinkTreeTarget))
                .putNameToPathMap(
                    Paths.get("header.h"),
                    new BuildTargetSourcePath(privateHeaderTarget))
                .build())
        .build();
    assertEquals(
        expectedPrivateCxxPreprocessorInput,
        cxxLibrary.getCxxPreprocessorInput(
            cxxPlatform,
            HeaderVisibility.PRIVATE));

    // Verify that we get the static archive and its build target via the NativeLinkable
    // interface.
    NativeLinkableInput expectedStaticNativeLinkableInput = NativeLinkableInput.of(
        ImmutableList.<Arg>of(
            new SourcePathArg(
                pathResolver,
                new BuildTargetSourcePath(archive.getBuildTarget()))),
        ImmutableSet.<FrameworkPath>of(),
        ImmutableSet.<FrameworkPath>of());
    assertEquals(
        expectedStaticNativeLinkableInput,
        cxxLibrary.getNativeLinkableInput(
            cxxPlatform,
            Linker.LinkableDepType.STATIC));

    // Verify that we get the static archive and its build target via the NativeLinkable
    // interface.
    NativeLinkableInput expectedSharedNativeLinkableInput = NativeLinkableInput.of(
        ImmutableList.<Arg>of(
            new SourcePathArg(
                pathResolver,
                new BuildTargetSourcePath(sharedLibrary.getBuildTarget()))),
        ImmutableSet.<FrameworkPath>of(),
        ImmutableSet.<FrameworkPath>of());
    assertEquals(
        expectedSharedNativeLinkableInput,
        cxxLibrary.getNativeLinkableInput(
            cxxPlatform,
            Linker.LinkableDepType.SHARED));

    // Verify that the implemented BuildRule methods are effectively unused.
    assertEquals(ImmutableList.<Step>of(), cxxLibrary.getBuildSteps(null, null));
    assertNull(cxxLibrary.getPathToOutput());
  }

  @Test
  public void headerOnlyExports() throws Exception {
    BuildRuleResolver ruleResolver =
        new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer());
    SourcePathResolver pathResolver = new SourcePathResolver(ruleResolver);
    BuildTarget target = BuildTargetFactory.newInstance("//foo:bar");
    BuildRuleParams params = new FakeBuildRuleParamsBuilder(target).build();
    CxxPlatform cxxPlatform =
        DefaultCxxPlatforms.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));

    BuildTarget staticPicLibraryTarget = params.getBuildTarget().withAppendedFlavors(
        cxxPlatform.getFlavor(),
        CxxDescriptionEnhancer.STATIC_PIC_FLAVOR);
    ruleResolver.addToIndex(
        new FakeBuildRule(
            new FakeBuildRuleParamsBuilder(staticPicLibraryTarget).build(),
            pathResolver));

    FrameworkPath frameworkPath = FrameworkPath.ofSourcePath(
        new BuildTargetSourcePath(BuildTargetFactory.newInstance("//foo:baz")));

    // Construct a CxxLibrary object to test.
    CxxLibrary cxxLibrary = new CxxLibrary(
        params,
        ruleResolver,
        pathResolver,
        FluentIterable.from(params.getDeclaredDeps()),
        /* hasExportedHeaders */ Predicates.<CxxPlatform>alwaysTrue(),
        /* headerOnly */ Predicates.<CxxPlatform>alwaysTrue(),
        Functions.constant(ImmutableMultimap.<CxxSource.Type, String>of()),
        Functions.constant(StringArg.from("-ldl")),
        /* linkTargetInput */ Functions.constant(NativeLinkableInput.of()),
        /* supportedPlatformsRegex */ Optional.<Pattern>absent(),
        ImmutableSet.of(frameworkPath),
        ImmutableSet.<FrameworkPath>of(),
        NativeLinkable.Linkage.STATIC,
        /* linkWhole */ false,
        Optional.<String>absent(),
        ImmutableSortedSet.<BuildTarget>of(),
        /* isAsset */ false);

    NativeLinkableInput expectedSharedNativeLinkableInput =
        NativeLinkableInput.of(
            StringArg.from("-ldl"),
            ImmutableSet.of(frameworkPath),
            ImmutableSet.<FrameworkPath>of());

    assertEquals(
        expectedSharedNativeLinkableInput,
        cxxLibrary.getNativeLinkableInput(
            cxxPlatform,
            Linker.LinkableDepType.SHARED));
  }

}


text:
goog.provide('ol.control.Control');

goog.require('goog.dom');
goog.require('goog.events');
goog.require('ol');
goog.require('ol.MapEventType');
goog.require('ol.Object');

/**
 * @classdesc
 * A control is a visible widget with a DOM element in a fixed position on the
 * screen. They can involve user input (buttons), or be informational only;
 * the position is determined using CSS. By default these are placed in the
 * container with CSS class name `ol-overlaycontainer-stopevent`, but can use
 * any outside DOM element.
 *
 * This is the base class for controls. You can use it for simple custom
 * controls by creating the element with listeners, creating an instance:
 * ```js
 * var myControl = new ol.control.Control({element: myElement});
 * ```
 * and then adding this to the map.
 *
 * The main advantage of having this as a control rather than a simple separate
 * DOM element is that preventing propagation is handled for you. Controls
 * will also be `ol.Object`s in a `ol.Collection`, so you can use their
 * methods.
 *
 * You can also extend this base for your own control class. See
 * examples/custom-controls for an example of how to do this.
 *
 * @constructor
 * @extends {ol.Object}
 * @implements {oli.control.Control}
 * @param {olx.control.ControlOptions} options Control options.
 * @api stable
 */
ol.control.Control = function(options) {

  goog.base(this);

  /**
   * @protected
   * @type {Element}
   */
  this.element = options.element ? options.element : null;

  /**
   * @private
   * @type {Element}
   */
  this.target_ = null;

  /**
   * @private
   * @type {ol.Map}
   */
  this.map_ = null;

  /**
   * @protected
   * @type {!Array.<?number>}
   */
  this.listenerKeys = [];

  /**
   * @type {function(ol.MapEvent)}
   */
  this.render = options.render ? options.render : ol.nullFunction;

  if (options.target) {
    this.setTarget(options.target);
  }

};
goog.inherits(ol.control.Control, ol.Object);

/**
 * @inheritDoc
 */
ol.control.Control.prototype.disposeInternal = function() {
  goog.dom.removeNode(this.element);
  goog.base(this, 'disposeInternal');
};

/**
 * Get the map associated with this control.
 * @return {ol.Map} Map.
 * @api stable
 */
ol.control.Control.prototype.getMap = function() {
  return this.map_;
};

/**
 * Remove the control from its current map and attach it to the new map.
 * Subclasses may set up event handlers to get notified about changes to
 * the map here.
 * @param {ol.Map} map Map.
 * @api stable
 */
ol.control.Control.prototype.setMap = function(map) {
  if (this.map_) {
    goog.dom.removeNode(this.element);
  }
  if (this.listenerKeys.length > 0) {
    this.listenerKeys.forEach(goog.events.unlistenByKey);
    this.listenerKeys.length = 0;
  }
  this.map_ = map;
  if (this.map_) {
    var target = this.target_ ?
        this.target_ : map.getOverlayContainerStopEvent();
    target.appendChild(this.element);
    if (this.render !== ol.nullFunction) {
      this.listenerKeys.push(goog.events.listen(map,
          ol.MapEventType.POSTRENDER, this.render, false, this));
    }
    map.render();
  }
};

/**
 * This function is used to set a target element for the control. It has no
 * effect if it is called after the control has been added to the map (i.e.
 * after `setMap` is called on the control). If no `target` is set in the
 * options passed to the control constructor and if `setTarget` is not called
 * then the control is added to the map's overlay container.
 * @param {Element|string} target Target.
 * @api
 */
ol.control.Control.prototype.setTarget = function(target) {
  this.target_ = goog.dom.getElement(target);
};


text:
#ifdef AVMPLUS_SHELL
#include "avmshell.h"
#else
// player
#include "platformbuild.h"
#include "avmplayer.h"
#include "DictionaryGlue.h"
#endif

using namespace MMgc;

namespace avmplus
{
	DictionaryClass::DictionaryClass(VTable *vtable)
	: ClassClosure(vtable)
	{
		createVanillaPrototype();
		vtable->traits->itraits->isDictionary = true;
	}

	ScriptObject *DictionaryClass::createInstance(VTable *ivtable, ScriptObject* /*delegate*/)
	{
 		GCAssert(ivtable->traits->isDictionary == true);
		return new (core()->GetGC(), ivtable->getExtraSize()) DictionaryObject(ivtable, prototype);
	}

	DictionaryObject::DictionaryObject(VTable *vtable, ScriptObject *delegate)
		: ScriptObject(vtable, delegate)
	{
		GCAssert(vtable->traits->isDictionary == true);
	}

	DictionaryObject::~DictionaryObject()
	{
		weakKeys = false;
	}

	void DictionaryObject::init(bool weakKeys)
	{
		GCAssert(vtable->traits->isDictionary == true);
		this->weakKeys = weakKeys;
		table = weakKeys ? new (gc()) WeakKeyHashtable(gc()) : new (gc()) Hashtable(gc());
	}

	Atom DictionaryObject::getKeyFromObject(Atom key) const
	{
		AvmAssert(AvmCore::isObject(key));
		ScriptObject *obj = AvmCore::atomToScriptObject(key);
		AvmAssert(obj->traits() != core()->traits.qName_itraits);
		AvmAssert(MMgc::GC::Size(obj) >= sizeof(ScriptObject));
		(void)obj;

		// FIXME: this doesn't work, need to convert back to an XMLObject
		// on the way out or intern XMLObject's somehow
		//if(AvmCore::isXML(key))
		//	key = AvmCore::gcObjectToAtom(AvmCore::atomToXML(key));

		return key;
	}

	Atom DictionaryObject::getAtomProperty(Atom key) const
	{
		if(AvmCore::isObject(key)) {
			key = getKeyFromObject(key);
			if(weakKeys)
				return weakTable()->get(key);
			else
				return table->get(key);
		} else
			return ScriptObject::getAtomProperty(key);
	}

	bool DictionaryObject::hasAtomProperty(Atom key) const
	{
		if(AvmCore::isObject(key)) {
			key = getKeyFromObject(key);
			if(weakKeys)
				return weakTable()->contains(key);
			else
				return table->contains(key);
		} else
			return ScriptObject::hasAtomProperty(key);
	}

	bool DictionaryObject::deleteAtomProperty(Atom key)
	{
		if(AvmCore::isObject(key)) {
			key = getKeyFromObject(key);
			if(weakKeys)
				weakTable()->remove(key);
			else
				table->remove(key);
			return true;
		} else {
			return ScriptObject::deleteAtomProperty(key);
		}
	}

	void DictionaryObject::setAtomProperty(Atom key, Atom value)
	{
		if(AvmCore::isObject(key)) {
			key = getKeyFromObject(key);
			if(weakKeys)
				weakTable()->add(key, value);
			else
				table->add(key, value);
		} else
			ScriptObject::setAtomProperty(key, value);
	}

	Atom DictionaryObject::nextName(int index)
	{
		Atom k = ScriptObject::nextName(index);

		if(weakKeys && AvmCore::isGCObject(k)) {
			GCWeakRef *ref = (GCWeakRef*) (k&~7);
			if(ref->get()) {
				ScriptObject *key = ((ScriptObject*)ref->get());
				AvmAssert(key->traits() != NULL);
				return key->atom();
			} else
				return undefinedAtom;
		}

		return k;
	}

	int DictionaryObject::nextNameIndex(int index)
	{
		AvmAssert(index >= 0);

		if (index != 0) {
			index = index<<1;
		}

		Hashtable *ht = getTable();

		// this can happen if you break in debugger in a subclasses constructor before super
		// has been called -- let's do it in all builds, it's better than crashing.
		if (!ht)
		{
			return 0;
		}

		// Advance to first non-empty slot.
		int numAtoms = ht->getNumAtoms();
		while (index < numAtoms) {
			Atom a = ht->getAtoms()[index];
			if(weakKeys && AvmCore::isGCObject(a)) {
				GCWeakRef *weakRef = (GCWeakRef*)AvmCore::atomToGCObject(a);
				if(weakRef->get())
					return (index>>1)+1;
				else {
					ht->getAtoms()[index] = Hashtable::DELETED;
					ht->getAtoms()[index+1] = Hashtable::DELETED;
					ht->setHasDeletedItems(true);
				}
			} else if(a != 0 && a != Hashtable::DELETED) {
					return (index>>1)+1;
			}
			index += 2;
		}
		return 0;
	}
}


text:
package com.jivesoftware.os.amza.service;

import com.jivesoftware.os.amza.api.partition.PartitionName;
import com.jivesoftware.os.amza.api.partition.VersionedPartitionName;
import com.jivesoftware.os.amza.api.ring.RingMember;
import com.jivesoftware.os.amza.api.ring.TimestampedRingHost;
import java.io.DataOutputStream;

public interface AmzaInstance {

    Iterable<PartitionName> getAllPartitionNames() throws Exception;

    Iterable<PartitionName> getMemberPartitionNames() throws Exception;

    Iterable<PartitionName> getSystemPartitionNames() throws Exception;

    void destroyPartition(PartitionName partitionName) throws Exception;

    long getTimestamp(long timestamp, long millisAgo) throws Exception;

    void availableRowsStream(boolean system,
        ChunkWriteable writeable,
        RingMember remoteRingMember,
        TimestampedRingHost remoteTimestampedRingHost,
        long takeSessionId,
        long sharedKey,
        long timeoutMillis) throws Exception;

    void rowsStream(DataOutputStream dos,
        RingMember remoteRingMember,
        VersionedPartitionName localVersionedPartitionName,
        long takeSessionId,
        long sharedKey,
        long localTxId,
        long leadershipToken,
        long limit) throws Exception;

    void rowsTaken(RingMember remoteRingMember,
        long takeSessionId,
        long sharedKey,
        VersionedPartitionName localVersionedPartitionName,
        long localTxId,
        long leadershipToken) throws Exception;

    void pong(RingMember remoteRingMember, long takeSessionId, long sharedKey) throws Exception;

    void invalidate(RingMember ringMember, long takeSessionId, long sharedKey, VersionedPartitionName versionedPartitionName) throws Exception;
}


text:
namespace ecs_test
{
    struct PositionComponent : public Component
    {
        PositionComponent(int x, int y)
            : x(x), y(y) { }

        int x, y;
    };

    struct VelocityComponent : public Component
    {
        VelocityComponent(int x, int y)
            : x(x), y(y) { }

        int x, y;
    };

    struct RenderComponent : public Component
    {
        float someValue = 0.f;
        uint16_t usefulValue = 10;
    };

    struct AnimationComponent : public Component
    {
        float time = 0.f;
    };

    class PhysicsSystem : public System
    {
    public:
        void update(EntityManager& manager) override
        {
            for (Entity entity : manager.getEntitiesWithComponents<PositionComponent, VelocityComponent>())
            {
                auto posComponent = entity.getComponent<PositionComponent>();
                auto velocityComponent = entity.getComponent<VelocityComponent>();

                posComponent->x += velocityComponent->x;
                posComponent->y += velocityComponent->y;
            }
        }
    };

    template <class... Components>
    void assertNumberOfEntitiesWithComponents(EntityManager& entityManager, int size)
    {
        assert(int(entityManager.numberOfEntitiesWithComponents<Components...>()) == size);
    }

    template <class T1, class T2>
    bool allEqual(const T1& v1, const T2& v2) { return v1 == v2; }

    template <class T1, class T2, class... Args>
    bool allEqual(const T1& v1, const T2& v2, const Args& ... args) { return v1 == v2 && allEqual(v2, args...); }

    template <class T1, class T2>
    bool allNotEqual(const T1& v1, const T2& v2) { return v1 != v2; }

    template <class T1, class T2, class... Args>
    bool allNotEqual(const T1& v1, const T2& v2, const Args& ... args) { return v1 != v2 && allNotEqual(v2, args...) && allNotEqual(v1, args...); }

    template <class T1, class T2, class... Args>
    bool allDifferent(const T1& v1, const T2& v2, const Args& ... args) { return allNotEqual(v1, v2, args...); }

#ifdef RUN_ECS_TESTS
    struct ECSTestRunner
    {
        ECSTestRunner()
        {
            ECSTest::runTests();
        }
    };

    ECSTestRunner ecsTestRunner;
#endif
}

using namespace ecs_test;

void ECSTest::runTests()
{
    testComponentTypeID();
    testEntityCreateDestroyValid();
    testHasGetAddRemoveComponent();
    testGetEntitiesWithComponents();
    testSystem();
}

void ECSTest::testComponentTypeID()
{
    // Make 2 tests with 2 different EntityManager instances where in the second test a new component comes in
    // to ensure that the type id doesn't break functionality with multiple instances. They should all be different.
    {
        // Setup a test environment
        EntityManager entityManager;

        assert(allDifferent(
                entityManager.getComponentTypeID<PositionComponent>(),
            entityManager.getComponentTypeID<VelocityComponent>(),
            entityManager.getComponentTypeID<RenderComponent>()));
    }

    {
        // Setup a test environment
        EntityManager entityManager;

        assert(allDifferent(
                entityManager.getComponentTypeID<PositionComponent>(),
            entityManager.getComponentTypeID<VelocityComponent>(),
            entityManager.getComponentTypeID<RenderComponent>(),
            entityManager.getComponentTypeID<AnimationComponent>()));
    }
}

void ECSTest::testGetEntitiesWithComponents()
{
    // Setup a test environment
    EntityManager entityManager;

    int entitySize = 100;

    for (int i = 0; i < entitySize; ++i)
    {
        Entity entity = entityManager.create();
        entity.addComponent<PositionComponent>(i, 0);
        entity.addComponent<VelocityComponent>(0, 1);

        if (i % 2 == 0)
            entity.addComponent<RenderComponent>();
    }

    assertNumberOfEntitiesWithComponents<RenderComponent>(entityManager, entitySize / 2);
    assertNumberOfEntitiesWithComponents<AnimationComponent>(entityManager, 0);
    assertNumberOfEntitiesWithComponents<PositionComponent, VelocityComponent>(entityManager, entitySize);
    assertNumberOfEntitiesWithComponents<PositionComponent>(entityManager, entitySize);
    assertNumberOfEntitiesWithComponents<VelocityComponent>(entityManager, entitySize);
}

void ECSTest::testEntityCreateDestroyValid()
{
    // Setup a test environment
    EntityManager entityManager;
    Entity entity = entityManager.create();
    assert(entity.valid() && entity);

    entity.destroy();
    assert(!entity && !entity.valid());

    Entity entity2 = entityManager.create();
    assert(entity2.m_id == 0);
    assert(entity2.valid() && entity2);
    assert(!entity && !entity.valid() && "Old Entity that has been destroyed is valid after index reuse.");
    assert(!Entity() && !Entity().valid() && "Default constructed Entity should not be valid.");
}

void ECSTest::testHasGetAddRemoveComponent()
{
    // Setup a test environment
    EntityManager entityManager;
    Entity entity = entityManager.create();
    assert(
        !(entity.hasComponent<PositionComponent>() &&
        entity.hasComponent<RenderComponent>() &&
        entity.hasComponent<AnimationComponent>() &&
        entity.hasComponent<VelocityComponent>()));

    entity.addComponent<PositionComponent>(1, 2);
    entity.addComponent<RenderComponent>();
    entity.addComponent<AnimationComponent>();
    assert(entity.hasComponent<PositionComponent>() && entity.hasComponent<RenderComponent>() && entity.hasComponent<AnimationComponent>());

    ComponentPtr<PositionComponent> position = entity.getComponent<PositionComponent>();
    assert(position && position->x == 1.f && position->y == 2.f);
    assert(entity.getComponent<AnimationComponent>() && entity.getComponent<RenderComponent>());

    entity.removeComponent<PositionComponent>();
    assert(!entity.hasComponent<PositionComponent>());
    assert(entity.hasComponent<RenderComponent>() && entity.hasComponent<AnimationComponent>());
    entity.removeComponent<AnimationComponent>();
    assert(!entity.hasComponent<PositionComponent>() && !entity.hasComponent<AnimationComponent>());
    assert(entity.hasComponent<RenderComponent>());
    entity.removeComponent<RenderComponent>();
    assert(!entity.hasComponent<PositionComponent>() && !entity.hasComponent<AnimationComponent>() && !entity.hasComponent<RenderComponent>());

    assert(!entity.getComponent<PositionComponent>() && !entity.getComponent<RenderComponent>() && !entity.getComponent<AnimationComponent>());
}

void ECSTest::testSystem()
{
    // Setup a test environment
    ECS::addSystem<PhysicsSystem>();

    int entitySize = 100;
    int numIterations = 100;

    for (int i = 0; i < entitySize; ++i)
    {
        Entity entity = ECS::createEntity();
        entity.addComponent<PositionComponent>(0, 0);
        entity.addComponent<VelocityComponent>(0, 1);

        if (i % 2 == 0)
            entity.addComponent<RenderComponent>();
    }

    for (int i = 0; i < numIterations; ++i)
        ECS::update();

    for (Entity entity : ECS::getEntitiesWithComponents<PositionComponent>())
    {
        assert(entity.getComponent<PositionComponent>()->y == numIterations);
        assert(entity.getComponent<PositionComponent>()->x == 0.f);
    }
}


text:
Analyzes an uploaded file and returns the file size in bytes.
A simple example of an HTML/JavaScript frontend making an AJAX
call to a node backend.

## Use
Use the file upload field to select a file and click the
submit button. The file will be uploaded and the file size will
be returned with an alert dialog.


text:
@implementation PTASite
+ (PTASite *) sharedSite
{
    static PTASite *sharedSite = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedSite = [PTASite new];
    });
    return sharedSite;
}

- (void) loginWithUsername: (NSString *)username password: (NSString *)password result: (void (^)(NSError *error, PTAUser *user))resultBlock
{
    STHTTPRequest *req = [STHTTPRequest requestWithURLString: @"http://www.perfume-web.jp/pta/index.php"];
    req.POSTDictionary = @{@"id": username, @"pass": password, @"submit_login": @"LOGIN"};
    req.HTTPMethod = @"POST";
    req.completionBlock = ^(NSDictionary *header, NSString *body) {
        NSLog(@"h: %@", header);
        //        NSLog(@"b: %@", body);

        PTAUser *user = [PTAUser userFromHTML: body];
        //        NSArray *articles = [PTAArticle articlesFromHTML: body];
        resultBlock(nil, user);
    };
    req.errorBlock = ^(NSError *error) {

    };
    [req startAsynchronous];
}

- (void) fetchMemberBlogWithPage: (NSNumber *)page result: (void (^)(NSError *error, NSArray *blogs, NSNumber *nextPage))resultBlock
{
    STHTTPRequest *req = [STHTTPRequest requestWithURLString: [NSString stringWithFormat: @"http://www.perfume-web.jp/pta/blog/?page=%@", page ?: @1]];
    req.completionBlock = ^(NSDictionary *header, NSString *body) {
        NSArray *blogs = [PTAArticle articlesFromHTML: body];

        OCGumboDocument *document = [[OCGumboDocument alloc] initWithHTMLString: body];
#define GetAttr(e, a) (e ? e.attr(a) : nil)
        NSString *nextURL = GetAttr(document.Query(@"#pagination-next").find(@"a").first(), @"href");

        NSString *nextPageString = [[nextURL componentsSeparatedByString: @"="] lastObject];
        NSNumber *nextPage = (nextPageString.length > 0) ? @(nextPageString.intValue) : nil;
        resultBlock(nil, blogs, nextPage);
    };
    [req startAsynchronous];
}

- (void) fetchMemberBlogArchiveWithPage:(NSNumber *)page result:(void (^)(NSError *, NSArray *, NSNumber *))resultBlock
{
    STHTTPRequest *req = [STHTTPRequest requestWithURLString: [NSString stringWithFormat: @"http://archive.perfume-web.jp/pta/blog/index.php?blogid=19&page=%@", page ?: @1]];
    req.completionBlock = ^(NSDictionary *header, NSString *body) {
        NSArray *blogs = [PTAArticle articlesFromHTML: body];

        OCGumboDocument *document = [[OCGumboDocument alloc] initWithHTMLString: body];
        NSString *nextURL = GetAttr(document.Query(@".npsb_nextlink").parent(@"a").first(), @"href");

        NSString *nextPageString = [[nextURL componentsSeparatedByString: @"="] lastObject];
        NSNumber *nextPage = (nextPageString.length > 0) ? @(nextPageString.intValue) : nil;
        resultBlock(nil, blogs, nextPage);
    };
    [req startAsynchronous];
}

@end


text:
title: "Serhii Braslavets"
permalink: /alumni/Serhii_Braslavets
author_profile: false
comments: false
sidebar: false
---


text:
var module = require('./module');

module.directive('markdown', function () {
  return {
    restrict: 'EA',
    require: '?ngModel',
    priority: 1,
    compile: function compile ( tElement, tAttrs ) {
      if ( !window.markdown ) {
        throw new Error('markdown needs markdown to work!');
      }

      var initialValue = tElement.text();

      return function postLink ( scope, iElement, iAttrs, ngModel ) {
        function updateModel ( newValue ) {
          if ( ngModel && newValue !== ngModel.$viewValue ) {
            ngModel.$setViewValue(newValue);

            if ( !scope.$$phase ) {
              scope.$apply();
            }
          }
        }

        if ( ngModel ) {
          ngModel.$render = function () {
            tElement.html(window.markdown.toHTML(ngModel.$viewValue || ''));
          }

          updateModel(initialValue);
        }
      };
    }
  };
});


text:
<?php

declare(strict_types = 1);
namespace Rebing\GraphQL\Tests\Unit\LaravelValidatorTests;

use Illuminate\Support\Facades\Validator;
use Rebing\GraphQL\Tests\TestCase;

class LaravelValidatorTest extends TestCase
{
    public function testInPassRulePass(): void
    {
        $rules = [
            'arg' => [
                'in:valid_name',
                new RuleObjectPass(),
            ],
        ];

        $data = [
            'arg' => 'valid_name',
        ];

        $validator = Validator::make($data, $rules);

        self::assertSame([], $validator->errors()->all());
    }

    public function testInPassRuleFail(): void
    {
        $rules = [
            'arg' => [
                'in:valid_name',
                new RuleObjectFail(),
            ],
        ];

        $data = [
            'arg' => 'valid_name',
        ];

        $validator = Validator::make($data, $rules);

        $expectedMessages = [
            'rule object validation fails',
        ];
        self::assertSame($expectedMessages, $validator->errors()->all());
    }

    public function testInFailRulePass(): void
    {
        $rules = [
            'arg' => [
                'in:valid_name',
                new RuleObjectPass(),
            ],
        ];

        $data = [
            'arg' => 'invalid_name',
        ];

        $validator = Validator::make($data, $rules);

        $expectedMessages = [
            'The selected arg is invalid.',
        ];
        self::assertSame($expectedMessages, $validator->errors()->all());
    }

    public function testInFailRuleFail(): void
    {
        $rules = [
            'arg' => [
                'in:valid_name',
                new RuleObjectFail(),
            ],
        ];

        $data = [
            'The selected arg is invalid.',
            'rule object validation fails',
        ];

        $validator = Validator::make($data, $rules);

        self::assertSame([], $validator->errors()->all());
    }
}


text:
module ChiliPepper
  module MenusHelper
  end
end


text:
//-----------------------------------------------------------------------
// <copyright file="RemainingTests.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using Xunit;

namespace Akka.TestKit.Tests.Xunit2.TestKitBaseTests
{
    public class RemainingTests : TestKit.Xunit2.TestKit
    {
        [Fact]
        public void Throw_if_remaining_is_called_outside_Within()
        {
            Assert.Throws<InvalidOperationException>(() => Remaining);
        }
    }
}


text:
namespace Facebook
{
    enum HttpMethod
    {
        Get,
        Post,
        Delete
    };
}


text:
for studying YAML

## install dependencies

1. Run `./install.sh` command

## Java compile and execution

```bash
$ ./bin/javae path/to/source.java
```

## See

**Java**

* [asomov / snakeyaml — Bitbucket](https://bitbucket.org/asomov/snakeyaml)
* [Documentation - snakeyaml - YAML parser and emitter for Java - Google Project Hosting](https://code.google.com/p/snakeyaml/wiki/Documentation)

**PHP**

* [php-yaml: YAML-1.1 parser and emitter PECL package](http://bd808.com/pecl-file_formats-yaml/)

**Lua**

* [Lua beginner: Table dump to console - Stack Overflow](http://stackoverflow.com/questions/9168058/lua-beginner-table-dump-to-console)


text:
from gii.core.model import *

from PropertyEditor import FieldEditor, registerSimpleFieldEditorFactory
from gii.SearchView import requestSearchView
from gii.qt.IconCache  import getIcon

from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt

##----------------------------------------------------------------##
class ActionFieldButton( QtGui.QToolButton ):
	def sizeHint( self ):
		return QtCore.QSize( 20, 20)

##----------------------------------------------------------------##
class ActionFieldEditor( FieldEditor ):
	def setTarget( self, parent, field ):
		super( ActionFieldEditor, self ).setTarget( parent, field )
		t = field.getType()
		self.actionName    = t.actionName

	def get( self ):
		pass

	def set( self, value ):
		pass

	def setValue( self, value ):
		pass

	def initLabel( self, label, container ):
		self.label = label
		self.labelWidget = QtGui.QLabel( container )
		self.labelWidget.setText( '' )
		self.labelWidget.setMinimumSize( 50, 16 )
		self.labelWidget.setSizePolicy(
			QtGui.QSizePolicy.Expanding,
			QtGui.QSizePolicy.Expanding
			)
		return self.labelWidget

	def initEditor( self, container ):
		self.button = ActionFieldButton( container )
		self.button.setSizePolicy(
			QtGui.QSizePolicy.Expanding,
			QtGui.QSizePolicy.Expanding
			)
		self.button.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
		self.button.setText( self.label )
		icon = self.getOption( 'icon', 'play' )
		self.button.setIcon( getIcon(icon) )
		self.button.clicked.connect( self.doAction )
		return self.button

	def doAction( self ):
		self.notifyChanged( True )
		self.notifyObjectChanged()

	def setFocus( self ):
		self.button.setFocus()

registerSimpleFieldEditorFactory( ActionType, ActionFieldEditor )


text:
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>svnmailer.stream.DevNullStream</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css" />

         Home

         Trees

         Indices

         Help

        Package svnmailer ::
        Module stream ::
        Class DevNullStream

[hide private]

Class DevNullStream

source code

 object --+
          |
_BaseStream --+
              |
             DevNullStream

Dummy stream, which throws away all data

        Instance Methods
        [hide private]

          __init__(self)

      Initialization

            source code

          write(self,
        towrite)

      throw away stuff

            source code

          writelines(self,
        lines)

      throw away stuff

            source code

Inherited from _BaseStream:
      __getattr__,
      close

Inherited from object:
      __delattr__,
      __format__,
      __getattribute__,
      __hash__,
      __new__,
      __reduce__,
      __reduce_ex__,
      __repr__,
      __setattr__,
      __sizeof__,
      __str__,
      __subclasshook__

        Instance Variables
        [hide private]

Inherited from _BaseStream:
      stream

        Properties
        [hide private]

Inherited from object:
      __class__

        Method Details
        [hide private]

__init__(self)

(Constructor)

  	source code

Initialization

Parameters:

stream - The stream to wrap

Overrides:
        object.__init__

write(self,
        towrite)

  	source code

throw away stuff

Parameters:

towrite - stuff to write

Overrides:
        _BaseStream.write

writelines(self,
        lines)

  	source code

throw away stuff

Parameters:

lines - The lines to write (including \n)

Overrides:
        _BaseStream.writelines

         Home

         Trees

         Indices

         Help

    Generated by Epydoc 3.0.1 on Sun Sep 25 21:07:33 2011

      http://epydoc.sourceforge.net


text:
package org.oxymores.chronix.web.api;

import java.util.List;
import java.util.UUID;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.jaxrs.whiteboard.propertytypes.JaxrsResource;
import org.oxymores.chronix.core.engine.api.DTOApplication;
import org.oxymores.chronix.core.engine.api.DTOApplicationShort;
import org.oxymores.chronix.core.engine.api.PlanAccessService;
import org.oxymores.chronix.dto.DTOEnvironment;
import org.oxymores.chronix.dto.DTOValidationError;
import org.oxymores.chronix.engine.modularity.web.RestServiceApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles all the metadata related services. JSON only.
 */
@Component(service = ServiceMeta.class)
@JaxrsResource
@Path("/meta")
public class ServiceMeta implements RestServiceApi
{
    private static final Logger log = LoggerFactory.getLogger(ServiceMeta.class);

    private PlanAccessService api;

    @Reference
    public void setApi(PlanAccessService api)
    {
        this.api = api;
    }

    public void unsetApi()
    {
        this.api = null;
    }

    public ServiceMeta()
    {
        // Default constructor - for OSGI construction
    }

    public ServiceMeta(PlanAccessService api)
    {
        // Constructor for non-OSGI servlet containers
        this.api = api;
    }

    @GET
    @Path("ping")
    @Produces(MediaType.TEXT_PLAIN)
    public String sayHello()
    {
        log.debug("Ping service was called");
        return "houba hop";
    }

    @GET
    @Path("environment")
    @Produces(MediaType.APPLICATION_JSON)
    public DTOEnvironment getEnvironment()
    {
        return api.getEnvironment();
    }

    @POST
    @Path("environment")
    @Consumes(MediaType.APPLICATION_JSON)
    public void saveEnvironmentDraft(DTOEnvironment e)
    {
        api.saveEnvironmentDraft(e);
    }

    @POST
    @Path("liveenvironment")
    @Consumes(MediaType.APPLICATION_JSON)
    public void promoteEnvironmentDraft()
    {
        api.promoteEnvironmentDraft("commit web");
    }

    @POST
    @Path("environment/newdemo")
    @Produces(MediaType.APPLICATION_JSON)
    public DTOEnvironment createTestEnvironment()
    {
        return api.createMinimalEnvironment();
    }

    @GET
    @Path("app/{appid}")
    @Produces(MediaType.APPLICATION_JSON)
    public DTOApplication getApplication(@PathParam("appid") UUID id)
    {
        log.info("getApplication was called");
        try
        {
            return api.getApplication(id);
        }
        catch (Exception e)
        {
            log.error("hhh", e);
            throw e;
        }
    }

    @POST
    @Path("app")
    @Consumes(MediaType.APPLICATION_JSON)
    public void saveApplicationDraft(DTOApplication app)
    {
        api.saveApplicationDraft(app);
    }

    @POST
    @Path("liveapp")
    @Consumes(MediaType.APPLICATION_JSON)
    public void promoteApplicationDraft(DTOApplication app)
    {
        api.promoteApplicationDraft(app.getId(), "commit message");
    }

    @POST
    @Path("xappunstage")
    @Consumes(MediaType.APPLICATION_JSON)
    public void resetApplicationDraft(DTOApplication app)
    {
        api.resetApplicationDraft(app);
    }

    // TODO: save this.
    /*
     * @POST
     *
     * @Path("rrule/test")
     *
     * @Produces(MediaType.APPLICATION_JSON)
     *
     * @Consumes(MediaType.APPLICATION_JSON) public DTOResultClock getNextRRuleOccurrences(DTORRule rule) { return
     * api.testRecurrenceRule(rule); }
     */

    @GET
    @Path("app")
    @Produces(MediaType.APPLICATION_JSON)
    public List<DTOApplicationShort> getAllApplications()
    {
        log.info("getAllApplications was called");
        try
        {
            return api.getAllApplications();
        }
        catch (Exception e)
        {
            log.error("hhh", e);
            throw e;
        }
    }

    @GET
    @Path("newapp")
    @Produces(MediaType.APPLICATION_JSON)
    public DTOApplication createMinimalApplication()
    {
        return api.createMinimalApplication();
    }

    @POST
    @Path("app/newdemo")
    @Produces(MediaType.APPLICATION_JSON)
    public DTOApplication createTestApplication()
    {
        return api.createTestApplication();
    }

    @POST
    @Path("app/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public List<DTOValidationError> validateApplication(DTOApplication app)
    {
        return api.validateApplication(app);
    }

    @POST
    @Path("environment/test")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public List<DTOValidationError> validateEnvironment(DTOEnvironment nn)
    {
        return api.validateEnvironment(nn);
    }
}


text:
VERSION_MAJOR = 1
VERSION_MINOR = 4
VERSION_BUILD = 5
VERSION_INFO = (VERSION_MAJOR, VERSION_MINOR, VERSION_BUILD)
VERSION_STRING = "%d.%d.%d" % VERSION_INFO

__version__ = VERSION_INFO


text:
<?php

namespace Recca0120\LaravelTracy\Panels;

use Closure;
use Illuminate\Support\Arr;
use Recca0120\LaravelTracy\Contracts\IAjaxPanel;

class AuthPanel extends AbstractPanel implements IAjaxPanel
{
    /**
     * The user resolver callable.
     *
     * @var callable|null
     */
    protected $userResolver;

    /**
     * setUserResolver.
     *
     * @param Closure $userResolver
     * @return $this
     */
    public function setUserResolver(Closure $userResolver)
    {
        $this->userResolver = $userResolver;

        return $this;
    }

    /**
     * getAttributes.
     *
     ** @return array
     */
    protected function getAttributes()
    {
        $attributes = [];
        if (is_null($this->userResolver) === false) {
            $attributes['rows'] = call_user_func($this->userResolver);
        } elseif ($this->hasLaravel() === true) {
            $attributes = isset($this->laravel['sentinel']) === true ?
                $this->fromSentinel() : $this->fromGuard();
        }

        return $this->identifier($attributes);
    }

    /**
     * fromGuard.
     *
     * @return array
     */
    protected function fromGuard()
    {
        $auth = $this->laravel['auth'];
        $user = $auth->user();

        return is_null($user) === true ? [] : [
            'id' => $user->getAuthIdentifier(),
            'rows' => $user->toArray(),
        ];
    }

    /**
     * fromSentinel.
     *
     * @return array
     */
    protected function fromSentinel()
    {
        $user = $this->laravel['sentinel']->check();

        return empty($user) === true ? [] : [
            'id' => null,
            'rows' => $user->toArray(),
        ];
    }

    /**
     * identifier.
     *
     * @param array $attributes
     * @return array
     */
    protected function identifier($attributes = [])
    {
        $id = Arr::get($attributes, 'id');
        $rows = Arr::get($attributes, 'rows', []);

        if (empty($rows) === true) {
            $id = 'Guest';
        } elseif (is_numeric($id) === true || empty($id) === true) {
            $id = 'UnKnown';
            foreach (['username', 'account', 'email', 'name', 'id'] as $key) {
                if (isset($rows[$key]) === true) {
                    $id = $rows[$key];
                    break;
                }
            }
        }

        return [
            'id' => $id,
            'rows' => $rows,
        ];
    }
}


text:
class PermissionQueueController;
class PermissionRequestID;
class Profile;

namespace content {
class WebContents;
}

using BrowserPermissionCallback = base::Callback<void(ContentSetting)>;

// This base class contains common operations for granting permissions.
// It offers the following functionality:
//   - Creates a bubble or infobar when a permission is needed
//   - If accepted/denied the permission is saved in content settings for
//     future uses (for the domain that requested it).
//   - If dismissed the permission is not saved but it's considered denied for
//     this one request
//   - In any case the BrowserPermissionCallback is executed once a decision
//     about the permission is made by the user.
// The bare minimum you need to create a new permission request is
//   - Define your new permission in the ContentSettingsType enum.
//   - Create a class that inherits from PermissionContextBase and passes the
//     new permission.
//   - Inherit from PermissionInfobarDelegate and implement
//     |GetMessageText|
//   - Edit the PermissionBubbleRequestImpl methods to add the new text for
//     the bubble.
//   - Hit several asserts for the missing plumbing and fix them :)
// After this you can override several other methods to customize behavior,
// in particular it is advised to override UpdateTabContext in order to manage
// the permission from the omnibox.
// It is mandatory to override IsRestrictedToSecureOrigin.
// See midi_permission_context.h/cc or push_permission_context.cc/h for some
// examples.

class PermissionContextBase : public KeyedService {
 public:
  PermissionContextBase(Profile* profile,
                        const ContentSettingsType permission_type);
  ~PermissionContextBase() override;

  // The renderer is requesting permission to push messages.
  // When the answer to a permission request has been determined, |callback|
  // should be called with the result.
  virtual void RequestPermission(content::WebContents* web_contents,
                                 const PermissionRequestID& id,
                                 const GURL& requesting_frame,
                                 bool user_gesture,
                                 const BrowserPermissionCallback& callback);

  // Returns whether the permission has been granted, denied...
  virtual ContentSetting GetPermissionStatus(
      const GURL& requesting_origin,
      const GURL& embedding_origin) const;

  // Resets the permission to its default value.
  virtual void ResetPermission(const GURL& requesting_origin,
                               const GURL& embedding_origin);

  // Withdraw an existing permission request, no op if the permission request
  // was already cancelled by some other means.
  virtual void CancelPermissionRequest(content::WebContents* web_contents,
                                       const PermissionRequestID& id);

 protected:
  // Decide whether the permission should be granted.
  // Calls PermissionDecided if permission can be decided non-interactively,
  // or NotifyPermissionSet if permission decided by presenting an infobar.
  virtual void DecidePermission(content::WebContents* web_contents,
                                const PermissionRequestID& id,
                                const GURL& requesting_origin,
                                const GURL& embedding_origin,
                                bool user_gesture,
                                const BrowserPermissionCallback& callback);

  // Called when permission is granted without interactively asking the user.
  void PermissionDecided(const PermissionRequestID& id,
                         const GURL& requesting_origin,
                         const GURL& embedding_origin,
                         const BrowserPermissionCallback& callback,
                         bool persist,
                         ContentSetting content_setting);

  virtual void NotifyPermissionSet(const PermissionRequestID& id,
                                   const GURL& requesting_origin,
                                   const GURL& embedding_origin,
                                   const BrowserPermissionCallback& callback,
                                   bool persist,
                                   ContentSetting content_setting);

  // Implementors can override this method to update the icons on the
  // url bar with the result of the new permission.
  virtual void UpdateTabContext(const PermissionRequestID& id,
                                const GURL& requesting_origin,
                                bool allowed) {}

  // Return an instance of the infobar queue controller, creating it if needed.
  PermissionQueueController* GetQueueController();

  // Returns the profile associated with this permission context.
  Profile* profile() const;

  // Store the decided permission as a content setting.
  // virtual since the permission might be stored with different restrictions
  // (for example for desktop notifications).
  virtual void UpdateContentSetting(const GURL& requesting_origin,
                                    const GURL& embedding_origin,
                                    ContentSetting content_setting);

  // Whether the permission should be restricted to secure origins.
  virtual bool IsRestrictedToSecureOrigins() const = 0;

 private:
  // Called when a bubble is no longer used so it can be cleaned up.
  void CleanUpBubble(const PermissionRequestID& id);

  Profile* profile_;
  const ContentSettingsType permission_type_;
  scoped_ptr<PermissionQueueController> permission_queue_controller_;
  base::ScopedPtrHashMap<std::string, scoped_ptr<PermissionBubbleRequest>>
      pending_bubbles_;

  // Must be the last member, to ensure that it will be
  // destroyed first, which will invalidate weak pointers
  base::WeakPtrFactory<PermissionContextBase> weak_factory_;
};

#endif  // CHROME_BROWSER_PERMISSIONS_PERMISSION_CONTEXT_BASE_H_


text:
json-to-framer
==============

Cleate framer layouts declaratively


text:
var parent = require('../../es/symbol/for');

module.exports = parent;


text:
using Xunit.Sdk;

namespace ExRam.Gremlinq.Core.Tests
{
    public class SideEffectTestCaseOrderer : ITestCaseOrderer
    {
        private sealed class TestCaseComparer<TTestCase> : IComparer<TTestCase>
             where TTestCase : ITestCase
        {
            public static readonly TestCaseComparer<TTestCase> Instance = new();

            private TestCaseComparer()
            {
            }

            public int Compare(TTestCase? x, TTestCase? y) => GetIndex(x!.TestMethod.Method.Name).CompareTo(GetIndex(y!.TestMethod.Method.Name));

            private static int GetIndex(string str) => str.StartsWith("Drop")
                ? 0
                : str.StartsWith("Add")
                    ? 1
                    : 2;
        }

        public IEnumerable<TTestCase> OrderTestCases<TTestCase>(IEnumerable<TTestCase> testCases) where TTestCase : ITestCase
        {
            return testCases
                .Where(testCase =>
                {
                    return (testCase.TestMethod.TestClass.Class.Name is { } className && className.EndsWith("IntegrationTests"))
                        ? Environment.GetEnvironmentVariable($"Run{className.Split('.')[^1]}") is { } env && bool.TryParse(env, out var enabled) && enabled
                        : true;
                })
                .OrderBy(x => x, TestCaseComparer<TTestCase>.Instance)
                .ThenBy(x => x!.TestMethod.Method.Name, StringComparer.OrdinalIgnoreCase);
        }
    }
}


text:
'use strict';

var Db = require('./db.mock');

function Client(db) {
    this.db = db || new Db();
    this.connect = function (url, callback) {
        return callback(null, this.db);
    };
}

module.exports = Client;


text:
<?php

namespace Proxies\__CG__\Ei\einstitutBundle\Entity;

/**
 * THIS CLASS WAS GENERATED BY THE DOCTRINE ORM. DO NOT EDIT THIS FILE.
 */
class CommentaireForum extends \Ei\einstitutBundle\Entity\CommentaireForum implements \Doctrine\ORM\Proxy\Proxy
{
    private $_entityPersister;
    private $_identifier;
    public $__isInitialized__ = false;
    public function __construct($entityPersister, $identifier)
    {
        $this->_entityPersister = $entityPersister;
        $this->_identifier = $identifier;
    }
    /** @private */
    public function __load()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;

            if (method_exists($this, "__wakeup")) {
                // call this after __isInitialized__to avoid infinite recursion
                // but before loading to emulate what ClassMetadata::newInstance()
                // provides.
                $this->__wakeup();
            }

            if ($this->_entityPersister->load($this->_identifier, $this) === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            unset($this->_entityPersister, $this->_identifier);
        }
    }

    /** @private */
    public function __isInitialized()
    {
        return $this->__isInitialized__;
    }

    public function getForumComment()
    {
        $this->__load();
        return parent::getForumComment();
    }

    public function setForumComment($u2)
    {
        $this->__load();
        return parent::setForumComment($u2);
    }

    public function getCommentUser()
    {
        $this->__load();
        return parent::getCommentUser();
    }

    public function setCommentUser($u2)
    {
        $this->__load();
        return parent::setCommentUser($u2);
    }

    public function getId()
    {
        if ($this->__isInitialized__ === false) {
            return (int) $this->_identifier["id"];
        }
        $this->__load();
        return parent::getId();
    }

    public function setCommentaire($commentaire)
    {
        $this->__load();
        return parent::setCommentaire($commentaire);
    }

    public function getCommentaire()
    {
        $this->__load();
        return parent::getCommentaire();
    }

    public function setDate($date)
    {
        $this->__load();
        return parent::setDate($date);
    }

    public function getDate()
    {
        $this->__load();
        return parent::getDate();
    }

    public function setStatut($statut)
    {
        $this->__load();
        return parent::setStatut($statut);
    }

    public function getStatut()
    {
        $this->__load();
        return parent::getStatut();
    }

    public function __sleep()
    {
        return array('__isInitialized__', 'id', 'commentaire', 'date', 'statut', 'forum_comment', 'comment_user');
    }

    public function __clone()
    {
        if (!$this->__isInitialized__ && $this->_entityPersister) {
            $this->__isInitialized__ = true;
            $class = $this->_entityPersister->getClassMetadata();
            $original = $this->_entityPersister->load($this->_identifier);
            if ($original === null) {
                throw new \Doctrine\ORM\EntityNotFoundException();
            }
            foreach ($class->reflFields as $field => $reflProperty) {
                $reflProperty->setValue($this, $reflProperty->getValue($original));
            }
            unset($this->_entityPersister, $this->_identifier);
        }

    }
}


text:
package com.roy.wolf.application;

import android.app.Application;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.baidu.mapapi.map.MKEvent;
import com.roy.wolf.model.UserInfoEntry;

public class WolfApplication extends Application {

	public static final String strKey = "C12fe738d81c558952faa3896af365e3";

	public boolean m_bKeyRight = true;
	public BMapManager mBMapManager = null;

	public UserInfoEntry userInfo = new UserInfoEntry();

	public int mainLive = 0;

	public String imei = "";
	public String phone = "";
	public String cid = "";

	@Override
	public void onCreate() {
		super.onCreate();
		initEngineManager(this);
		init();
	}

	private void init() {
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		imei = tm.getDeviceId();
		phone = "" + tm.getLine1Number();
	}

	public void initEngineManager(Context context) {
		if (mBMapManager == null) {
			mBMapManager = new BMapManager(context);
		}

		if (!mBMapManager.init(strKey, new MyGeneralListener())) {
			Toast.makeText(getApplicationContext(), "BMapManager  初始化错误!",
					Toast.LENGTH_LONG).show();
		}
	}

	// 常用事件监听,用来处理通常的网络错误,授权验证错误等
	class MyGeneralListener implements MKGeneralListener {

		@Override
		public void onGetNetworkState(int iError) {
			if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
				Toast.makeText(getApplicationContext(), "您的网络出错啦!",
						Toast.LENGTH_LONG).show();
			} else if (iError == MKEvent.ERROR_NETWORK_DATA) {
				Toast.makeText(getApplicationContext(), "输入正确的检索条件!",
						Toast.LENGTH_LONG).show();
			}
			// ...
		}

		@Override
		public void onGetPermissionState(int iError) {
			if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
				// 授权Key错误:
				Toast.makeText(getApplicationContext(),
						"请在 WolfApplication.java文件输入正确的授权Key!",
						Toast.LENGTH_LONG).show();
			}
		}
	}
}


text:
namespace SqlEditor.Models
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Diagnostics;
    using System.Linq;

    using SqlEditor.Models.Database;
    using SqlEditor.Models.Dojo.Dgrid;

    using StructureMap;

    /// <inheritdoc />
    public class DGridModel : IDGridModel
    {
        /// <summary>
        /// The IOC container.
        /// </summary>
        private readonly IContainer container;

        /// <summary>
        /// Initializes a new instance of the <see cref="DGridModel"/> class.
        /// </summary>
        /// <param name="container">The IOC container.</param>
        public DGridModel(IContainer container)
        {
            this.container = container;
        }

        /// <inheritdoc />
        public QueryResult Query(string sql, ConnectionStringSettings settings)
        {
            var database = this.container.With("settings").EqualTo(settings).GetInstance<IDatabase>();
            using (var connection = database.GetConnection())
            {
                using (var command = connection.CreateCommand())
                {
                    command.CommandText = sql;
                    connection.Open();
                    var stopWatch = new Stopwatch();
                    stopWatch.Start();
                    using (var reader = command.ExecuteReader())
                    {
                        var results = FetchAll(reader).ToList();
                        stopWatch.Stop();
                        var time = stopWatch.Elapsed;
                        var queryResult = new QueryResult
                                               {
                                                   Data = results,
                                                   ElapsedTime = time,
                                                   RowCount = results.Count,
                                                   Columns = GetColumns(results)
                                               };
                        this.AddIdColumn(queryResult);
                        return queryResult;
                    }
                }
            }
        }

        /// <summary>
        /// Fetches all records in the reader.
        /// </summary>
        /// <param name="reader">The data reader.</param>
        /// <returns>A list where each item is a dictionary of column field and value.</returns>
        private static IEnumerable<Dictionary<string, dynamic>> FetchAll(IDataReader reader)
        {
            var list = new List<Dictionary<string, dynamic>>();
            while (reader.Read())
            {
                list.Add(Enumerable.Range(0, reader.FieldCount).ToDictionary(reader.GetName, reader.GetValue));
            }

            return list;
        }

        /// <summary>
        /// Returns a list of column names.
        /// </summary>
        /// <param name="queryResult">The result of a query.</param>
        /// <returns>The columns names in the query.</returns>
        private static IEnumerable<Column> GetColumns(IEnumerable<Dictionary<string, dynamic>> queryResult)
        {
            var result = queryResult.FirstOrDefault();
            if (result == null)
            {
                return new List<Column>();
            }

            return
                result.Select(
                    column =>
                    new Column
                        {
                            Formatter = column.Value is DateTime ? "dotNetDate" : string.Empty,
                            Field = column.Key
                        });
        }

        /// <summary>
        /// Adds an "id" column to the result set.
        /// This is needed by the dojo grid.
        /// </summary>
        /// <param name="result">The query result.</param>
        private void AddIdColumn(QueryResult result)
        {
            const string IdField = "_id";
            result.IdField = IdField;
            var list = result.Data.ToList();
            for (var i = 0; i < list.Count; i++)
            {
                list[i].Add(IdField, i);
            }

            result.Data = list;

            var columns = result.Columns.ToList();
            columns.Add(new Column
                            {
                                Field = IdField,
                                Label = "ID()",
                                Hidden = true
                            });

            result.Columns = columns;
        }
    }
}


text:
"""Compatibility code for handling string/bytes changes from Python 2.x to Py3k

In Python 2.x, strings (of type ''str'') contain binary data, including encoded
Unicode text (e.g. UTF-8).  The separate type ''unicode'' holds Unicode text.
Unicode literals are specified via the u'...' prefix.  Indexing or slicing
either type always produces a string of the same type as the original.
Data read from a file is always of '''str'' type.

In Python 3.x, strings (type ''str'') may only contain Unicode text. The u'...'
prefix and the ''unicode'' type are now redundant.  A new type (called
''bytes'') has to be used for binary data (including any particular
''encoding'' of a string).  The b'...' prefix allows one to specify a binary
literal.  Indexing or slicing a string produces another string.  Slicing a byte
string produces another byte string, but the indexing operation produces an
integer.  Data read from a file is of '''str'' type if the file was opened in
text mode, or of ''bytes'' type otherwise.

Since PyCrypto aims at supporting both Python 2.x and 3.x, the following helper
functions are used to keep the rest of the library as independent as possible
from the actual Python version.

In general, the code should always deal with binary strings, and use integers
instead of 1-byte character strings.

b(s)
    Take a text string literal (with no prefix or with u'...' prefix) and
    make a byte string.
bchr(c)
    Take an integer and make a 1-character byte string.
bord(c)
    Take the result of indexing on a byte string and make an integer.
tobytes(s)
    Take a text string, a byte string, or a sequence of character taken from
    a byte string and make a byte string.
"""

__revision__ = "$Id$"

import sys

if sys.version_info[0] == 2:
    def b(s):
        return s
    def bchr(s):
        return chr(s)
    def bstr(s):
        return str(s)
    def bord(s):
        return ord(s)
    if sys.version_info[1] == 1:
        def tobytes(s):
            try:
                return s.encode('latin-1')
            except:
                return ''.join(s)
    else:
        def tobytes(s):
            if isinstance(s, str):
                return s.encode("latin-1")
            else:
                return ''.join(s)
else:
    def b(s):
       return s.encode("latin-1") # utf-8 would cause some side-effects we don't want
    def bchr(s):
        return bytes([s])
    def bstr(s):
        if isinstance(s,str):
            return bytes(s,"latin-1")
        else:
            return bytes(s)
    def bord(s):
        return s
    def tobytes(s):
        if isinstance(s,bytes):
            return s
        else:
            if isinstance(s,str):
                return s.encode("latin-1")
            else:
                return bytes(s)

# vim:set ts=4 sw=4 sts=4 expandtab:


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.daytron.sqlcontainer;

import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.data.util.sqlcontainer.connection.JDBCConnectionPool;
import com.vaadin.data.util.sqlcontainer.query.QueryDelegate;
import com.vaadin.data.util.sqlcontainer.query.TableQuery;
import com.vaadin.ui.Button;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Ryan Gilera
 */
public class DatabaseTableScreen extends VerticalLayout {

    private SQLContainer container;
    private Table table;

    public DatabaseTableScreen() {
        setMargin(true);

        table = new Table();
        table.setPageLength(10);
        table.setEditable(true);
        table.setSizeFull();

        table.addGeneratedColumn("", new RemoveItemColumnGenerator());

        HorizontalLayout buttonBar = new HorizontalLayout();

        buttonBar.setMargin(true);
        buttonBar.setSpacing(true);

        Button commitButton = new Button("Commit");
        commitButton.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    container.commit();
                    Notification.show("Changes committed");
                } catch (UnsupportedOperationException | SQLException ex) {
                    Logger.getLogger(DatabaseTableScreen.class.getName()).log(Level.SEVERE, null, ex);
                    Notification.show("Unable to commit", Notification.Type.ERROR_MESSAGE);
                }

            }
        });

        buttonBar.addComponent(commitButton);
        Button rollbackButton = new Button("Rollback");

        rollbackButton.addClickListener(new Button.ClickListener() {

            @Override
            public void buttonClick(Button.ClickEvent event) {
                try {
                    container.rollback();
                    Notification.show("Changes rollback");
                } catch (UnsupportedOperationException | SQLException ex) {
                    Logger.getLogger(DatabaseTableScreen.class.getName()).log(Level.SEVERE, null, ex);
                    Notification.show("Unable to rollback", Notification.Type.ERROR_MESSAGE);
                }
            }
        });

        buttonBar.addComponent(rollbackButton);
        addComponent(table);
        addComponent(buttonBar);
    }

    public class RemoveItemColumnGenerator implements Table.ColumnGenerator {

        @Override
        public Object generateCell(Table source, Object itemId, Object columnId) {
            Button button = new Button("Delete");
            button.setData(itemId);

            button.addClickListener(new Button.ClickListener() {

                @Override
                public void buttonClick(Button.ClickEvent event) {
                    Object itemId = event.getButton().getData();
                    container.removeItem(itemId);
                }
            });

            return button;
        }

    }

    public void populate(String tableName, JDBCConnectionPool connectionPool) {
        QueryDelegate query = new TableQuery(tableName, connectionPool);

        try {
            container = new SQLContainer(query);
            table.setContainerDataSource(container);
        } catch (SQLException ex) {
            Logger.getLogger(DatabaseTableScreen.class.getName()).log(Level.SEVERE, null, ex);
            throw new RuntimeException(ex);
        }
    }
}


text:
var test = require("tap").test;
var defaultFormater = require('../../format.js');
var produce = require('../produce.js');

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

test("set Error.prepareStackTrace uses stack-chain formater", function (t) {
  // Save original formatter
  var restore = Error.prepareStackTrace;

  // Overwrite formatter
  Error.prepareStackTrace = function (error, frames) {
    if (error.test) {
      Object.defineProperty(error, '__some_secret', {
        value: 'you can\'t compare pain.'
      });
    }

    // Maintain .stack format
    return restore(error, frames);
  };

  // Prope the error using custom prepareStackTrace
  var testError = new Error();
  testError.test = true;
  testError.stack;
  t.equal(testError.__some_secret, 'you can\'t compare pain.');

  // Restore
  Error.prepareStackTrace = restore;

  t.equal(produce.real(3), produce.fake([
    'Error: trace',
    '    at {where}:18:17',
    '    at deepStack ({where}:5:5)',
    '    at deepStack ({where}:7:5)'
  ]));

  t.end();
});

test("set Error.prepareStackTrace uses other formater", function (t) {
  // Another module sets up a formater
  Error.prepareStackTrace = function () {
    return 'custom';
  };

  // Save original formatter
  var restore = Error.prepareStackTrace;

  // Overwrite formatter
  Error.prepareStackTrace = function (error, frames) {
    if (error.test) {
      Object.defineProperty(error, '__some_secret', {
        value: 'you can\'t compare pain.'
      });
    }

    // Maintain .stack format
    return restore(error, frames);
  };

  // Prope the error using custom prepareStackTrace
  var testError = new Error();
  testError.test = true;
  testError.stack;
  t.equal(testError.__some_secret, 'you can\'t compare pain.');

  // Restore
  Error.prepareStackTrace = restore;

  t.equal(produce.real(3), 'custom');

  // Perform an actual restore of the formater, to prevent test conflicts
  chain.format.restore();

  t.equal(produce.real(3), produce.fake([
    'Error: trace',
    '    at {where}:18:17',
    '    at deepStack ({where}:5:5)',
    '    at deepStack ({where}:7:5)'
  ]));

  t.end();
});


text:
// TypeScript Version: 2.0

/**
* Two-element array holding a `key` and corresponding `value`.
*/
type KeyValuePair = [ string, any ];

/**
* Returns an array of an object's own and inherited enumerable property `[key, value]` pairs.
*
* @param obj - input object
* @returns array containing key-value pairs
*
* @example
* function Foo() {
*     this.beep = 'boop';
*     return this;
* }
*
* Foo.prototype.foo = 'bar';
*
* var obj = new Foo();
*
* var entries = objectEntriesIn( obj );
* // e.g., returns [ ['beep', 'boop'], ['foo', 'bar'] ]
*/
declare function objectEntriesIn( obj: any ): Array<KeyValuePair>;

// EXPORTS //

export = objectEntriesIn;


text:
if __name__ == "__main__":
    import sys
    from time import time
    import linecache
    import glob
    from textindex import textindex
    import traceback
    import linecache
    from mutagen.mp3 import MP3
    import os

    ti = textindex()

    try:
        start = time()
        ti.read('mp3.ti')
        print 'Loading time : %.2fs'%(time()-start)
    except:
        traceback.print_exc()

        start = time()
        lines = 0

        for root, dirnames, filenames in os.walk(sys.argv[1]):
            for filename in filenames:
                if filename[-4:].lower() == '.mp3':
                    try:
                        full_filename = os.path.join(root,filename)
                        mp3 = MP3(full_filename)
                        title = mp3.get('TIT2')
                        artist = mp3.get('TPE2')
                        album = mp3.get('TALB')
                        if title:
                            title = title.text[0].decode('iso-8859-1').lower()
                            ti.put_text(title,full_filename)
                        else:
                            ti.put_text(filename[:-4].lower(),mp3)
                        if artist:
                            artist = artist.text[0].decode('iso-8859-1').lower()
                            ti.put_text(artist,full_filename)
                        if album:
                            album = album.text[0].decode('iso-8859-1').lower()
                            ti.put_text(album,full_filename)
                        print title, album, artist
                    except:
                        pass

        ti.pack()
        print 'Indexing time : %.2fs for %i lines'%(time()-start,lines)

        ti.write('mp3.ti')

    def lines(text,intersection=True):
        for ln, r in ti.find_text(text.lower(),intersection):
            print '%02i:%s'%(
                r,
                ln
            ),

    def ilines(text,intersection=True):
        for ln, r in ti.find_text(text.lower(),intersection):
            print '%02i:%s'%(
                r,
                ln,
            ),

    if len(sys.argv)>1 and sys.argv[-1]=='gui':
        from Tkinter import *
        class Explorer(object):
            def __init__(self,master):
                self.frame = Frame(master)
                self.frame.pack(fill=BOTH, expand=1)

                self.entry = Entry(self.frame, name='input')
                self.entry.pack(fill=X)
                self.entry.bind('<KeyRelease>',self.keyPressed)

                frame = Frame(self.frame)
                frame.pack(fill=BOTH, expand=1)
                scrollbar = Scrollbar(frame, orient=VERTICAL)
                self.list = Listbox(frame, name='list', yscrollcommand=scrollbar.set)
                scrollbar.config(command=self.list.yview)
                scrollbar.pack(side=RIGHT, fill=Y)
                self.list.pack(side=LEFT, fill=BOTH, expand=1)

                self.label = Label(self.frame, name='count')
                self.label.pack()

            def keyPressed(self,event):
                self.list.delete(0,END)
                start = time()
                result = ti.find_text(self.entry.get().lower(),True)
                # result.sort(key=lambda i : -i[1])
                elapsed = time() - start
                for ln, r in result[:100]:
                    self.list.insert(END,'%02i:%s'%(
                        r,
                        ln
                    ))
                self.label.config(text = '%i lines in %.2fs'%(
                    len(result),
                    elapsed
                ))

        root = Tk()
        explorer = Explorer(root)
        root.mainloop()


text:
title: Service Mesh
test: n/a
---

A *service mesh* or simply *mesh* is an infrastructure layer that enables
managed, observable and secure communication between
[workload instances](/docs/reference/glossary/#workload-instance).

Service names combined with a namespace are unique within a mesh.
In a [multicluster](/docs/reference/glossary/#multicluster) mesh, for example,
the `bar` service in the `foo` namespace in `cluster-1` is considered the same
service as the `bar` service in the `foo` namespace in `cluster-2`.

Since [identities](/docs/reference/glossary/#identity) are shared within the service
mesh, [workload instances](/docs/reference/glossary/#workload-instance) can authenticate communication with any other [workload
instance](/docs/reference/glossary/#workload-instance) within the same service mesh.


text:
@implementation XFunction
+ (void)writeLog:(NSString*)log,...{
    va_list args;
    va_start(args,log);
    NSLogv(log,args);
    va_end(args);
}
@end