code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.buffer.BufferObjectManager;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class UnloadResourcesExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mClickToUnloadTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mClickToUnloadTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "click_to_unload.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int x = (CAMERA_WIDTH - this.mClickToUnloadTextureRegion.getWidth()) / 2;
final int y = (CAMERA_HEIGHT - this.mClickToUnloadTextureRegion.getHeight()) / 2;
final Sprite clickToUnload = new Sprite(x, y, this.mClickToUnloadTextureRegion) {
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
/* Completely remove all resources associated with this sprite. */
BufferObjectManager.getActiveInstance().unloadBufferObject(this.getVertexBuffer());
BufferObjectManager.getActiveInstance().unloadBufferObject(UnloadResourcesExample.this.mClickToUnloadTextureRegion.getTextureBuffer());
UnloadResourcesExample.this.mEngine.getTextureManager().unloadTexture(UnloadResourcesExample.this.mBitmapTextureAtlas);
/* And remove the sprite from the Scene. */
final Sprite thisRef = this;
UnloadResourcesExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
scene.detachChild(thisRef);
}
});
return true;
}
};
scene.attachChild(clickToUnload);
scene.registerTouchArea(clickToUnload);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/UnloadResourcesExample.java | Java | lgpl | 4,680 |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.anddev.andengine.entity.modifier.ParallelEntityModifier;
import org.anddev.andengine.entity.modifier.RotationByModifier;
import org.anddev.andengine.entity.modifier.RotationModifier;
import org.anddev.andengine.entity.modifier.ScaleModifier;
import org.anddev.andengine.entity.modifier.SequenceEntityModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.util.modifier.IModifier;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 21:42:39 - 06.07.2010
*/
public class EntityModifierIrregularExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Shapes can have variable rotation and scale centers.", Toast.LENGTH_LONG).show();
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2;
final AnimatedSprite face1 = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion);
face1.setRotationCenter(0, 0);
face1.setScaleCenter(0, 0);
face1.animate(100);
final AnimatedSprite face2 = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion);
face2.animate(100);
final SequenceEntityModifier entityModifier = new SequenceEntityModifier(
new IEntityModifierListener() {
@Override
public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) {
EntityModifierIrregularExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierIrregularExample.this, "Sequence started.", Toast.LENGTH_LONG).show();
}
});
}
@Override
public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) {
EntityModifierIrregularExample.this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(EntityModifierIrregularExample.this, "Sequence finished.", Toast.LENGTH_LONG).show();
}
});
}
},
new ScaleModifier(2, 1.0f, 0.75f, 1.0f, 2.0f),
new ScaleModifier(2, 0.75f, 2.0f, 2.0f, 1.25f),
new ParallelEntityModifier(
new ScaleModifier(3, 2.0f, 5.0f, 1.25f, 5.0f),
new RotationByModifier(3, 180)
),
new ParallelEntityModifier(
new ScaleModifier(3, 5, 1),
new RotationModifier(3, 180, 0)
)
);
face1.registerEntityModifier(entityModifier);
face2.registerEntityModifier(entityModifier.deepCopy());
scene.attachChild(face1);
scene.attachChild(face2);
/* Create some not-modified sprites, that act as fixed references to the modified ones. */
final AnimatedSprite face1Reference = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion);
final AnimatedSprite face2Reference = new AnimatedSprite(centerX + 100, centerY, this.mFaceTextureRegion);
scene.attachChild(face1Reference);
scene.attachChild(face2Reference);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/EntityModifierIrregularExample.java | Java | lgpl | 6,326 |
package org.anddev.andengine.examples.util;
import java.util.Set;
import org.anddev.andengine.examples.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
/**
* This Activity appears as a dialog. It lists any paired devices and
* devices detected in the area after discovery. When a device is chosen
* by the user, the MAC address of the device is sent back to the parent
* Activity in the result Intent.
*
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga Inc.
*
* @author Nicolas Gramlich
* @since 12:19:52 - 06.03.2011
*/
public class BluetoothListDevicesActivity extends Activity {
// ===========================================================
// Constants
// ===========================================================
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// ===========================================================
// Fields
// ===========================================================
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
private final OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
@Override
public void onItemClick(final AdapterView<?> pAdapterView, final View pView, final int pPosition, final long pID) {
// Cancel discovery because it's costly and we're about to connect
BluetoothListDevicesActivity.this.mBluetoothAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
final String info = ((TextView) pView).getText().toString();
final String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
final Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
BluetoothListDevicesActivity.this.setResult(Activity.RESULT_OK, intent);
BluetoothListDevicesActivity.this.finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context pContext, final Intent pIntent) {
final String action = pIntent.getAction();
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
final BluetoothDevice device = pIntent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
BluetoothListDevicesActivity.this.setProgressBarIndeterminateVisibility(false);
BluetoothListDevicesActivity.this.setTitle("Select a device to connect...");
if (BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.getCount() == 0) {
BluetoothListDevicesActivity.this.mNewDevicesArrayAdapter.add("No devices found!");
}
}
}
};
// ===========================================================
// Constructors
// ===========================================================
@Override
protected void onCreate(final Bundle pSavedInstanceState) {
super.onCreate(pSavedInstanceState);
this.requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
this.setContentView(R.layout.list_bluetooth_devices);
// Set result CANCELED in case the user backs out
this.setResult(Activity.RESULT_CANCELED);
final Button scanButton = (Button) this.findViewById(R.id.button_scan);
scanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View v) {
BluetoothListDevicesActivity.this.discoverBluetoothDevices();
v.setVisibility(View.GONE);
}
});
this.mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
this.mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
final ListView pairedListView = (ListView) this.findViewById(R.id.paired_devices);
pairedListView.setAdapter(this.mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(this.mDeviceClickListener);
final ListView newDevicesListView = (ListView) this.findViewById(R.id.new_devices);
newDevicesListView.setAdapter(this.mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(this.mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(this.mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(this.mReceiver, filter);
this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
final Set<BluetoothDevice> pairedDevices = this.mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
this.findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (final BluetoothDevice device : pairedDevices) {
this.mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
this.mPairedDevicesArrayAdapter.add("No devices have been paired!");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (this.mBluetoothAdapter != null) {
this.mBluetoothAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(this.mReceiver);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
private void discoverBluetoothDevices() {
this.setProgressBarIndeterminateVisibility(true);
this.setTitle("Scanning for devices...");
this.findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
if (this.mBluetoothAdapter.isDiscovering()) {
this.mBluetoothAdapter.cancelDiscovery();
}
this.mBluetoothAdapter.startDiscovery();
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
} | 0bigdream10-tungclone | src/org/anddev/andengine/examples/util/BluetoothListDevicesActivity.java | Java | lgpl | 7,370 |
package org.anddev.andengine.examples;
import javax.microedition.khronos.opengles.GL10;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.particle.ParticleSystem;
import org.anddev.andengine.entity.particle.emitter.PointParticleEmitter;
import org.anddev.andengine.entity.particle.initializer.AccelerationInitializer;
import org.anddev.andengine.entity.particle.initializer.ColorInitializer;
import org.anddev.andengine.entity.particle.initializer.RotationInitializer;
import org.anddev.andengine.entity.particle.initializer.VelocityInitializer;
import org.anddev.andengine.entity.particle.modifier.AlphaModifier;
import org.anddev.andengine.entity.particle.modifier.ColorModifier;
import org.anddev.andengine.entity.particle.modifier.ExpireModifier;
import org.anddev.andengine.entity.particle.modifier.ScaleModifier;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class ParticleSystemCoolExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mParticleTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "particle_fire.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f));
/* Left to right Particle System. */
{
final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(0, CAMERA_HEIGHT), 6, 10, 200, this.mParticleTextureRegion);
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(15, 22, -60, -90));
particleSystem.addParticleInitializer(new AccelerationInitializer(5, 15));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
particleSystem.addParticleInitializer(new ColorInitializer(1.0f, 0.0f, 0.0f));
particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5));
particleSystem.addParticleModifier(new ExpireModifier(11.5f));
particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f));
particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f));
particleSystem.addParticleModifier(new ColorModifier(1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 11.5f));
particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f));
scene.attachChild(particleSystem);
}
/* Right to left Particle System. */
{
final ParticleSystem particleSystem = new ParticleSystem(new PointParticleEmitter(CAMERA_WIDTH - 32, CAMERA_HEIGHT), 8, 12, 200, this.mParticleTextureRegion);
particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE);
particleSystem.addParticleInitializer(new VelocityInitializer(-15, -22, -60, -90));
particleSystem.addParticleInitializer(new AccelerationInitializer(-5, 15));
particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f));
particleSystem.addParticleInitializer(new ColorInitializer(0.0f, 0.0f, 1.0f));
particleSystem.addParticleModifier(new ScaleModifier(0.5f, 2.0f, 0, 5));
particleSystem.addParticleModifier(new ExpireModifier(11.5f));
particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 2.5f, 3.5f));
particleSystem.addParticleModifier(new AlphaModifier(0.0f, 1.0f, 3.5f, 4.5f));
particleSystem.addParticleModifier(new ColorModifier(0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 11.5f));
particleSystem.addParticleModifier(new AlphaModifier(1.0f, 0.0f, 4.5f, 11.5f));
scene.attachChild(particleSystem);
}
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/ParticleSystemCoolExample.java | Java | lgpl | 6,397 |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 11:54:51 - 03.04.2010
*/
public class AnimatedSpritesExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 480;
private static final int CAMERA_HEIGHT = 320;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mSnapdragonTextureRegion;
private TiledTextureRegion mHelicopterTextureRegion;
private TiledTextureRegion mBananaTextureRegion;
private TiledTextureRegion mFaceTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(512, 256, TextureOptions.BILINEAR);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mSnapdragonTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "snapdragon_tiled.png", 0, 0, 4, 3);
this.mHelicopterTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "helicopter_tiled.png", 400, 0, 2, 2);
this.mBananaTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "banana_tiled.png", 0, 180, 4, 2);
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 132, 180, 2, 1);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
/* Quickly twinkling face. */
final AnimatedSprite face = new AnimatedSprite(100, 50, this.mFaceTextureRegion);
face.animate(100);
scene.attachChild(face);
/* Continuously flying helicopter. */
final AnimatedSprite helicopter = new AnimatedSprite(320, 50, this.mHelicopterTextureRegion);
helicopter.animate(new long[] { 100, 100 }, 1, 2, true);
scene.attachChild(helicopter);
/* Snapdragon. */
final AnimatedSprite snapdragon = new AnimatedSprite(300, 200, this.mSnapdragonTextureRegion);
snapdragon.animate(100);
scene.attachChild(snapdragon);
/* Funny banana. */
final AnimatedSprite banana = new AnimatedSprite(100, 220, this.mBananaTextureRegion);
banana.animate(100);
scene.attachChild(banana);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/AnimatedSpritesExample.java | Java | lgpl | 4,790 |
package org.anddev.andengine.examples;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.Scene.ITouchArea;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags;
import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage;
import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage;
import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler;
import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient;
import org.anddev.andengine.extension.multiplayer.protocol.client.SocketServerDiscoveryClient.ISocketServerDiscoveryClientListener;
import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector;
import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector;
import org.anddev.andengine.extension.multiplayer.protocol.client.connector.SocketConnectionServerConnector.ISocketConnectionServerConnectorListener;
import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer;
import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServer.ISocketServerListener;
import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer;
import org.anddev.andengine.extension.multiplayer.protocol.server.SocketServerDiscoveryServer.ISocketServerDiscoveryServerListener;
import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector;
import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector;
import org.anddev.andengine.extension.multiplayer.protocol.server.connector.SocketConnectionClientConnector.ISocketConnectionClientConnectorListener;
import org.anddev.andengine.extension.multiplayer.protocol.shared.IDiscoveryData.DefaultDiscoveryData;
import org.anddev.andengine.extension.multiplayer.protocol.shared.SocketConnection;
import org.anddev.andengine.extension.multiplayer.protocol.util.IPUtils;
import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool;
import org.anddev.andengine.extension.multiplayer.protocol.util.WifiUtils;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.util.Debug;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.widget.Toast;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 17:10:24 - 19.06.2010
*/
public class MultiplayerServerDiscoveryExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final int SERVER_PORT = 4444;
private static final int DISCOVERY_PORT = 4445;
private static final int LOCAL_PORT = 4446;
private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1;
private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1;
private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TextureRegion mFaceTextureRegion;
private int mFaceIDCounter;
private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>();
private SocketServer<SocketConnectionClientConnector> mSocketServer;
private ServerConnector<SocketConnection> mServerConnector;
private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>();
private SocketServerDiscoveryServer<DefaultDiscoveryData> mSocketServerDiscoveryServer;
private SocketServerDiscoveryClient<DefaultDiscoveryData> mSocketServerDiscoveryClient;
// ===========================================================
// Constructors
// ===========================================================
public MultiplayerServerDiscoveryExample() {
this.initMessagePool();
}
private void initMessagePool() {
this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class);
this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class);
}
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID);
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0);
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f));
/* We allow only the server to actively send around messages. */
if(MultiplayerServerDiscoveryExample.this.mSocketServer != null) {
scene.setOnSceneTouchListener(new IOnSceneTouchListener() {
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(pSceneTouchEvent.isActionDown()) {
try {
final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE);
addFaceServerMessage.set(MultiplayerServerDiscoveryExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(addFaceServerMessage);
MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(addFaceServerMessage);
} catch (final IOException e) {
Debug.e(e);
}
return true;
} else {
return false;
}
}
});
scene.setOnAreaTouchListener(new IOnAreaTouchListener() {
@Override
public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
try {
final Sprite face = (Sprite)pTouchArea;
final Integer faceID = (Integer)face.getUserData();
final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerServerDiscoveryExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE);
moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
MultiplayerServerDiscoveryExample.this.mSocketServer.sendBroadcastServerMessage(moveFaceServerMessage);
MultiplayerServerDiscoveryExample.this.mMessagePool.recycleMessage(moveFaceServerMessage);
} catch (final IOException e) {
Debug.e(e);
return false;
}
return true;
}
});
scene.setTouchAreaBindingEnabled(true);
}
return scene;
}
@Override
public void onLoadComplete() {
}
@Override
protected Dialog onCreateDialog(final int pID) {
switch(pID) {
case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID:
return new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle("Be Server or Client ...")
.setMessage("For automatic ServerDiscovery to work, all devices need to be on the same WiFi!")
.setCancelable(false)
.setPositiveButton("Client", new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
MultiplayerServerDiscoveryExample.this.initServerDiscovery();
}
})
.setNeutralButton("Server", new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
MultiplayerServerDiscoveryExample.this.toast("You can add and move sprites, which are only shown on the clients.");
MultiplayerServerDiscoveryExample.this.initServer();
}
})
.setNegativeButton("Both", new OnClickListener() {
@Override
public void onClick(final DialogInterface pDialog, final int pWhich) {
MultiplayerServerDiscoveryExample.this.toast("You can add sprites and move them, by dragging them.");
MultiplayerServerDiscoveryExample.this.initServerAndClient();
}
})
.create();
default:
return super.onCreateDialog(pID);
}
}
@Override
protected void onDestroy() {
if(this.mSocketServer != null) {
try {
this.mSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage());
} catch (final IOException e) {
Debug.e(e);
}
this.mSocketServer.terminate();
}
if(this.mSocketServerDiscoveryServer != null) {
this.mSocketServerDiscoveryServer.terminate();
}
if(this.mServerConnector != null) {
this.mServerConnector.terminate();
}
if(this.mSocketServerDiscoveryClient != null) {
this.mSocketServerDiscoveryClient.terminate();
}
super.onDestroy();
}
@Override
public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) {
switch(pKeyCode) {
case KeyEvent.KEYCODE_BACK:
this.finish();
return true;
}
return super.onKeyUp(pKeyCode, pEvent);
}
// ===========================================================
// Methods
// ===========================================================
public void addFace(final int pID, final float pX, final float pY) {
final Scene scene = this.mEngine.getScene();
/* Create the face and add it to the scene. */
final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion);
face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f);
face.setUserData(pID);
this.mFaces.put(pID, face);
scene.registerTouchArea(face);
scene.attachChild(face);
}
public void moveFace(final int pID, final float pX, final float pY) {
/* Find and move the face. */
final Sprite face = this.mFaces.get(pID);
face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f);
}
private void initServerAndClient() {
this.initServer();
/* Wait some time after the server has been started, so it actually can start up. */
try {
Thread.sleep(500);
} catch (final Throwable t) {
Debug.e(t);
}
this.initServerDiscovery();
}
private void initServer() {
this.mSocketServer = new SocketServer<SocketConnectionClientConnector>(SERVER_PORT, new ExampleClientConnectorListener(), new ExampleServerStateListener()) {
@Override
protected SocketConnectionClientConnector newClientConnector(final SocketConnection pSocketConnection) throws IOException {
return new SocketConnectionClientConnector(pSocketConnection);
}
};
this.mSocketServer.start();
try {
final byte[] wifiIPv4Address = WifiUtils.getWifiIPv4AddressRaw(this);
this.mSocketServerDiscoveryServer = new SocketServerDiscoveryServer<DefaultDiscoveryData>(DISCOVERY_PORT, new ExampleSocketServerDiscoveryServerListener()) {
@Override
protected DefaultDiscoveryData onCreateDiscoveryResponse() {
return new DefaultDiscoveryData(wifiIPv4Address, SERVER_PORT);
}
};
this.mSocketServerDiscoveryServer.start();
} catch (final Throwable t) {
Debug.e(t);
}
}
private void initServerDiscovery() {
try {
this.mSocketServerDiscoveryClient = new SocketServerDiscoveryClient<DefaultDiscoveryData>(WifiUtils.getBroadcastIPAddressRaw(this), DISCOVERY_PORT, LOCAL_PORT, DefaultDiscoveryData.class, new ISocketServerDiscoveryClientListener<DefaultDiscoveryData>() {
@Override
public void onDiscovery(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final DefaultDiscoveryData pDiscoveryData) {
try {
final String ipAddressAsString = IPUtils.ipAddressToString(pDiscoveryData.getServerIP());
MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Server discovered at: " + ipAddressAsString + ":" + pDiscoveryData.getServerPort());
MultiplayerServerDiscoveryExample.this.initClient(ipAddressAsString, pDiscoveryData.getServerPort());
} catch (final UnknownHostException e) {
MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: IPException: " + e);
}
}
@Override
public void onTimeout(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final SocketTimeoutException pSocketTimeoutException) {
Debug.e(pSocketTimeoutException);
MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Timeout: " + pSocketTimeoutException);
}
@Override
public void onException(final SocketServerDiscoveryClient<DefaultDiscoveryData> pSocketServerDiscoveryClient, final Throwable pThrowable) {
Debug.e(pThrowable);
MultiplayerServerDiscoveryExample.this.toast("DiscoveryClient: Exception: " + pThrowable);
}
});
this.mSocketServerDiscoveryClient.discoverAsync();
} catch (final Throwable t) {
Debug.e(t);
}
}
private void initClient(final String pIPAddress, final int pPort) {
try {
this.mServerConnector = new SocketConnectionServerConnector(new SocketConnection(new Socket(pIPAddress, pPort)), new ExampleServerConnectorListener());
this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<SocketConnection>() {
@Override
public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException {
MultiplayerServerDiscoveryExample.this.finish();
}
});
this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() {
@Override
public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException {
final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage;
MultiplayerServerDiscoveryExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY);
}
});
this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<SocketConnection>() {
@Override
public void onHandleMessage(final ServerConnector<SocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException {
final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage;
MultiplayerServerDiscoveryExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY);
}
});
this.mServerConnector.getConnection().start();
} catch (final Throwable t) {
Debug.e(t);
}
}
private void log(final String pMessage) {
Debug.d(pMessage);
}
private void toast(final String pMessage) {
this.log(pMessage);
this.runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MultiplayerServerDiscoveryExample.this, pMessage, Toast.LENGTH_SHORT).show();
}
});
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static class AddFaceServerMessage extends ServerMessage {
private int mID;
private float mX;
private float mY;
public AddFaceServerMessage() {
}
public AddFaceServerMessage(final int pID, final float pX, final float pY) {
this.mID = pID;
this.mX = pX;
this.mY = pY;
}
public void set(final int pID, final float pX, final float pY) {
this.mID = pID;
this.mX = pX;
this.mY = pY;
}
@Override
public short getFlag() {
return FLAG_MESSAGE_SERVER_ADD_FACE;
}
@Override
protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException {
this.mID = pDataInputStream.readInt();
this.mX = pDataInputStream.readFloat();
this.mY = pDataInputStream.readFloat();
}
@Override
protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException {
pDataOutputStream.writeInt(this.mID);
pDataOutputStream.writeFloat(this.mX);
pDataOutputStream.writeFloat(this.mY);
}
}
public static class MoveFaceServerMessage extends ServerMessage {
private int mID;
private float mX;
private float mY;
public MoveFaceServerMessage() {
}
public MoveFaceServerMessage(final int pID, final float pX, final float pY) {
this.mID = pID;
this.mX = pX;
this.mY = pY;
}
public void set(final int pID, final float pX, final float pY) {
this.mID = pID;
this.mX = pX;
this.mY = pY;
}
@Override
public short getFlag() {
return FLAG_MESSAGE_SERVER_MOVE_FACE;
}
@Override
protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException {
this.mID = pDataInputStream.readInt();
this.mX = pDataInputStream.readFloat();
this.mY = pDataInputStream.readFloat();
}
@Override
protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException {
pDataOutputStream.writeInt(this.mID);
pDataOutputStream.writeFloat(this.mX);
pDataOutputStream.writeFloat(this.mY);
}
}
private class ExampleServerConnectorListener implements ISocketConnectionServerConnectorListener {
@Override
public void onStarted(final ServerConnector<SocketConnection> pConnector) {
MultiplayerServerDiscoveryExample.this.toast("Client: Connected to server.");
}
@Override
public void onTerminated(final ServerConnector<SocketConnection> pConnector) {
MultiplayerServerDiscoveryExample.this.toast("Client: Disconnected from Server...");
MultiplayerServerDiscoveryExample.this.finish();
}
}
private class ExampleServerStateListener implements ISocketServerListener<SocketConnectionClientConnector> {
@Override
public void onStarted(final SocketServer<SocketConnectionClientConnector> pSocketServer) {
MultiplayerServerDiscoveryExample.this.toast("Server: Started.");
}
@Override
public void onTerminated(final SocketServer<SocketConnectionClientConnector> pSocketServer) {
MultiplayerServerDiscoveryExample.this.toast("Server: Terminated.");
}
@Override
public void onException(final SocketServer<SocketConnectionClientConnector> pSocketServer, final Throwable pThrowable) {
Debug.e(pThrowable);
MultiplayerServerDiscoveryExample.this.toast("Server: Exception: " + pThrowable);
}
}
private class ExampleClientConnectorListener implements ISocketConnectionClientConnectorListener {
@Override
public void onStarted(final ClientConnector<SocketConnection> pConnector) {
MultiplayerServerDiscoveryExample.this.toast("Server: Client connected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress());
}
@Override
public void onTerminated(final ClientConnector<SocketConnection> pConnector) {
MultiplayerServerDiscoveryExample.this.toast("Server: Client disconnected: " + pConnector.getConnection().getSocket().getInetAddress().getHostAddress());
}
}
public class ExampleSocketServerDiscoveryServerListener implements ISocketServerDiscoveryServerListener<DefaultDiscoveryData> {
@Override
public void onStarted(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) {
MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Started.");
}
@Override
public void onTerminated(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer) {
MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Terminated.");
}
@Override
public void onException(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final Throwable pThrowable) {
Debug.e(pThrowable);
MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Exception: " + pThrowable);
}
@Override
public void onDiscovered(final SocketServerDiscoveryServer<DefaultDiscoveryData> pSocketServerDiscoveryServer, final InetAddress pInetAddress, final int pPort) {
MultiplayerServerDiscoveryExample.this.toast("DiscoveryServer: Discovered by: " + pInetAddress.getHostAddress() + ":" + pPort);
}
}
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/MultiplayerServerDiscoveryExample.java | Java | lgpl | 23,177 |
package org.anddev.andengine.examples;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.entity.modifier.LoopEntityModifier;
import org.anddev.andengine.entity.modifier.PathModifier;
import org.anddev.andengine.entity.modifier.PathModifier.IPathModifierListener;
import org.anddev.andengine.entity.modifier.PathModifier.Path;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.background.RepeatingSpriteBackground;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.atlas.bitmap.source.AssetBitmapTextureAtlasSource;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 13:58:48 - 19.07.2010
*/
public class RepeatingSpriteBackgroundExample extends BaseExample {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
// ===========================================================
// Fields
// ===========================================================
private Camera mCamera;
private RepeatingSpriteBackground mGrassBackground;
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mPlayerTextureRegion;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera));
}
@Override
public void onLoadResources() {
this.mBitmapTextureAtlas = new BitmapTextureAtlas(128, 128, TextureOptions.DEFAULT);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "player.png", 0, 0, 3, 4);
this.mGrassBackground = new RepeatingSpriteBackground(CAMERA_WIDTH, CAMERA_HEIGHT, this.mEngine.getTextureManager(), new AssetBitmapTextureAtlasSource(this, "background_grass.png"));
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
final Scene scene = new Scene();
scene.setBackground(this.mGrassBackground);
/* Calculate the coordinates for the face, so its centered on the camera. */
final int centerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2;
final int centerY = (CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight()) / 2;
/* Create the sprite and add it to the scene. */
final AnimatedSprite player = new AnimatedSprite(centerX, centerY, 48, 64, this.mPlayerTextureRegion);
final Path path = new Path(5).to(10, 10).to(10, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, CAMERA_HEIGHT - 74).to(CAMERA_WIDTH - 58, 10).to(10, 10);
player.registerEntityModifier(new LoopEntityModifier(new PathModifier(30, path, null, new IPathModifierListener() {
@Override
public void onPathStarted(final PathModifier pPathModifier, final IEntity pEntity) {
}
@Override
public void onPathWaypointStarted(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
switch(pWaypointIndex) {
case 0:
player.animate(new long[]{200, 200, 200}, 6, 8, true);
break;
case 1:
player.animate(new long[]{200, 200, 200}, 3, 5, true);
break;
case 2:
player.animate(new long[]{200, 200, 200}, 0, 2, true);
break;
case 3:
player.animate(new long[]{200, 200, 200}, 9, 11, true);
break;
}
}
@Override
public void onPathWaypointFinished(final PathModifier pPathModifier, final IEntity pEntity, final int pWaypointIndex) {
}
@Override
public void onPathFinished(final PathModifier pPathModifier, final IEntity pEntity) {
}
})));
scene.attachChild(player);
return scene;
}
@Override
public void onLoadComplete() {
}
// ===========================================================
// Methods
// ===========================================================
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/RepeatingSpriteBackgroundExample.java | Java | lgpl | 5,664 |
package org.anddev.andengine.examples;
import static org.anddev.andengine.extension.physics.box2d.util.constants.PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.primitive.Rectangle;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.shape.Shape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.extension.physics.box2d.PhysicsConnector;
import org.anddev.andengine.extension.physics.box2d.PhysicsFactory;
import org.anddev.andengine.extension.physics.box2d.PhysicsWorld;
import org.anddev.andengine.extension.physics.box2d.util.Vector2Pool;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.util.Debug;
import android.hardware.SensorManager;
import android.widget.Toast;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
/**
* (c) 2010 Nicolas Gramlich
* (c) 2011 Zynga
*
* @author Nicolas Gramlich
* @since 18:47:08 - 19.03.2010
*/
public class PhysicsExample extends BaseExample implements IAccelerometerListener, IOnSceneTouchListener {
// ===========================================================
// Constants
// ===========================================================
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final FixtureDef FIXTURE_DEF = PhysicsFactory.createFixtureDef(1, 0.5f, 0.5f);
// ===========================================================
// Fields
// ===========================================================
private BitmapTextureAtlas mBitmapTextureAtlas;
private TiledTextureRegion mBoxFaceTextureRegion;
private TiledTextureRegion mCircleFaceTextureRegion;
private TiledTextureRegion mTriangleFaceTextureRegion;
private TiledTextureRegion mHexagonFaceTextureRegion;
private Scene mScene;
private PhysicsWorld mPhysicsWorld;
private int mFaceCount = 0;
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public Engine onLoadEngine() {
Toast.makeText(this, "Touch the screen to add objects.", Toast.LENGTH_LONG).show();
final Camera camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), camera);
engineOptions.getTouchOptions().setRunOnUpdateThread(true);
return new Engine(engineOptions);
}
@Override
public void onLoadResources() {
/* Textures. */
this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");
/* TextureRegions. */
this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_box_tiled.png", 0, 0, 2, 1); // 64x32
this.mCircleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_circle_tiled.png", 0, 32, 2, 1); // 64x32
this.mTriangleFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_triangle_tiled.png", 0, 64, 2, 1); // 64x32
this.mHexagonFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "face_hexagon_tiled.png", 0, 96, 2, 1); // 64x32
this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas);
}
@Override
public Scene onLoadScene() {
this.mEngine.registerUpdateHandler(new FPSLogger());
this.mScene = new Scene();
this.mScene.setBackground(new ColorBackground(0, 0, 0));
this.mScene.setOnSceneTouchListener(this);
this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);
final Shape ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2);
final Shape roof = new Rectangle(0, 0, CAMERA_WIDTH, 2);
final Shape left = new Rectangle(0, 0, 2, CAMERA_HEIGHT);
final Shape right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT);
final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef);
PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef);
this.mScene.attachChild(ground);
this.mScene.attachChild(roof);
this.mScene.attachChild(left);
this.mScene.attachChild(right);
this.mScene.registerUpdateHandler(this.mPhysicsWorld);
return this.mScene;
}
@Override
public void onLoadComplete() {
}
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if(this.mPhysicsWorld != null) {
if(pSceneTouchEvent.isActionDown()) {
this.addFace(pSceneTouchEvent.getX(), pSceneTouchEvent.getY());
return true;
}
}
return false;
}
@Override
public void onAccelerometerChanged(final AccelerometerData pAccelerometerData) {
final Vector2 gravity = Vector2Pool.obtain(pAccelerometerData.getX(), pAccelerometerData.getY());
this.mPhysicsWorld.setGravity(gravity);
Vector2Pool.recycle(gravity);
}
@Override
public void onResumeGame() {
super.onResumeGame();
this.enableAccelerometerSensor(this);
}
@Override
public void onPauseGame() {
super.onPauseGame();
this.disableAccelerometerSensor();
}
// ===========================================================
// Methods
// ===========================================================
private void addFace(final float pX, final float pY) {
this.mFaceCount++;
Debug.d("Faces: " + this.mFaceCount);
final AnimatedSprite face;
final Body body;
if(this.mFaceCount % 4 == 0) {
face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion);
body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else if (this.mFaceCount % 4 == 1) {
face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion);
body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else if (this.mFaceCount % 4 == 2) {
face = new AnimatedSprite(pX, pY, this.mTriangleFaceTextureRegion);
body = PhysicsExample.createTriangleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
} else {
face = new AnimatedSprite(pX, pY, this.mHexagonFaceTextureRegion);
body = PhysicsExample.createHexagonBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);
}
face.animate(200);
this.mScene.attachChild(face);
this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(face, body, true, true));
}
/**
* Creates a {@link Body} based on a {@link PolygonShape} in the form of a triangle:
* <pre>
* /\
* /__\
* </pre>
*/
private static Body createTriangleBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {
/* Remember that the vertices are relative to the center-coordinates of the Shape. */
final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;
final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;
final float top = -halfHeight;
final float bottom = halfHeight;
final float left = -halfHeight;
final float centerX = 0;
final float right = halfWidth;
final Vector2[] vertices = {
new Vector2(centerX, top),
new Vector2(right, bottom),
new Vector2(left, bottom)
};
return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef);
}
/**
* Creates a {@link Body} based on a {@link PolygonShape} in the form of a hexagon:
* <pre>
* /\
* / \
* | |
* | |
* \ /
* \/
* </pre>
*/
private static Body createHexagonBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {
/* Remember that the vertices are relative to the center-coordinates of the Shape. */
final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;
final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;
/* The top and bottom vertex of the hexagon are on the bottom and top of hexagon-sprite. */
final float top = -halfHeight;
final float bottom = halfHeight;
final float centerX = 0;
/* The left and right vertices of the heaxgon are not on the edge of the hexagon-sprite, so we need to inset them a little. */
final float left = -halfWidth + 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;
final float right = halfWidth - 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;
final float higher = top + 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;
final float lower = bottom - 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;
final Vector2[] vertices = {
new Vector2(centerX, top),
new Vector2(right, higher),
new Vector2(right, lower),
new Vector2(centerX, bottom),
new Vector2(left, lower),
new Vector2(left, higher)
};
return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef);
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
}
| 0bigdream10-tungclone | src/org/anddev/andengine/examples/PhysicsExample.java | Java | lgpl | 11,304 |
{\rtf1\adeflang1054\ansi\ansicpg1252\uc1\adeff31507\deff0\stshfdbch31505\stshfloch31506\stshfhich31506\stshfbi31507\deflang1033\deflangfe1033\themelang1033\themelangfe0\themelangcs0{\fonttbl{\f0\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\f23\fbidi \fswiss\fcharset0\fprq2{\*\panose 020b0304020202020204}Cordia New;}
{\f34\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria Math;}{\f37\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}{\f39\fbidi \fnil\fcharset222\fprq0{\*\panose 00000000000000000000}Thonburi;}
{\f40\fbidi \fswiss\fcharset0\fprq0{\*\panose 00000000000000000000}ArialMT{\*\falt Arial};}{\flomajor\f31500\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
{\fdbmajor\f31501\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhimajor\f31502\fbidi \froman\fcharset0\fprq2{\*\panose 02040503050406030204}Cambria;}
{\fbimajor\f31503\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Angsana New;}{\flominor\f31504\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}
{\fdbminor\f31505\fbidi \froman\fcharset0\fprq2{\*\panose 02020603050405020304}Times New Roman;}{\fhiminor\f31506\fbidi \fswiss\fcharset0\fprq2{\*\panose 020f0502020204030204}Calibri;}
{\fbiminor\f31507\fbidi \fswiss\fcharset0\fprq2{\*\panose 020b0304020202020204}Cordia New;}{\f459\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\f460\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\f462\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\f463\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\f464\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\f465\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\f466\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\f467\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\f698\fbidi \fswiss\fcharset222\fprq2 Cordia New (Thai);}{\f799\fbidi \froman\fcharset238\fprq2 Cambria Math CE;}
{\f800\fbidi \froman\fcharset204\fprq2 Cambria Math Cyr;}{\f802\fbidi \froman\fcharset161\fprq2 Cambria Math Greek;}{\f803\fbidi \froman\fcharset162\fprq2 Cambria Math Tur;}{\f806\fbidi \froman\fcharset186\fprq2 Cambria Math Baltic;}
{\f807\fbidi \froman\fcharset163\fprq2 Cambria Math (Vietnamese);}{\f829\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\f830\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}{\f832\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}
{\f833\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\f836\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}{\f837\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\flomajor\f31508\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
{\flomajor\f31509\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flomajor\f31511\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\flomajor\f31512\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
{\flomajor\f31513\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flomajor\f31514\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\flomajor\f31515\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
{\flomajor\f31516\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbmajor\f31518\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\fdbmajor\f31519\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}
{\fdbmajor\f31521\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbmajor\f31522\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\fdbmajor\f31523\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}
{\fdbmajor\f31524\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbmajor\f31525\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\fdbmajor\f31526\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}
{\fhimajor\f31528\fbidi \froman\fcharset238\fprq2 Cambria CE;}{\fhimajor\f31529\fbidi \froman\fcharset204\fprq2 Cambria Cyr;}{\fhimajor\f31531\fbidi \froman\fcharset161\fprq2 Cambria Greek;}{\fhimajor\f31532\fbidi \froman\fcharset162\fprq2 Cambria Tur;}
{\fhimajor\f31535\fbidi \froman\fcharset186\fprq2 Cambria Baltic;}{\fhimajor\f31536\fbidi \froman\fcharset163\fprq2 Cambria (Vietnamese);}{\fbimajor\f31547\fbidi \froman\fcharset222\fprq2 Angsana New (Thai);}
{\flominor\f31548\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}{\flominor\f31549\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\flominor\f31551\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}
{\flominor\f31552\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}{\flominor\f31553\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\flominor\f31554\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}
{\flominor\f31555\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}{\flominor\f31556\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fdbminor\f31558\fbidi \froman\fcharset238\fprq2 Times New Roman CE;}
{\fdbminor\f31559\fbidi \froman\fcharset204\fprq2 Times New Roman Cyr;}{\fdbminor\f31561\fbidi \froman\fcharset161\fprq2 Times New Roman Greek;}{\fdbminor\f31562\fbidi \froman\fcharset162\fprq2 Times New Roman Tur;}
{\fdbminor\f31563\fbidi \froman\fcharset177\fprq2 Times New Roman (Hebrew);}{\fdbminor\f31564\fbidi \froman\fcharset178\fprq2 Times New Roman (Arabic);}{\fdbminor\f31565\fbidi \froman\fcharset186\fprq2 Times New Roman Baltic;}
{\fdbminor\f31566\fbidi \froman\fcharset163\fprq2 Times New Roman (Vietnamese);}{\fhiminor\f31568\fbidi \fswiss\fcharset238\fprq2 Calibri CE;}{\fhiminor\f31569\fbidi \fswiss\fcharset204\fprq2 Calibri Cyr;}
{\fhiminor\f31571\fbidi \fswiss\fcharset161\fprq2 Calibri Greek;}{\fhiminor\f31572\fbidi \fswiss\fcharset162\fprq2 Calibri Tur;}{\fhiminor\f31575\fbidi \fswiss\fcharset186\fprq2 Calibri Baltic;}
{\fhiminor\f31576\fbidi \fswiss\fcharset163\fprq2 Calibri (Vietnamese);}{\fbiminor\f31587\fbidi \fswiss\fcharset222\fprq2 Cordia New (Thai);}{\f688\fbidi \froman\fcharset222\fprq2 Angsana New (Thai);}}{\colortbl;\red0\green0\blue0;\red0\green0\blue255;
\red0\green255\blue255;\red0\green255\blue0;\red255\green0\blue255;\red255\green0\blue0;\red255\green255\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue128;\red0\green128\blue0;\red128\green0\blue128;\red128\green0\blue0;
\red128\green128\blue0;\red128\green128\blue128;\red192\green192\blue192;\red38\green38\blue38;}{\*\defchp \fs22\loch\af31506\hich\af31506\dbch\af31505 }{\*\defpap \ql \li0\ri0\sa200\sl276\slmult1
\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 }\noqfpromote {\stylesheet{\ql \li0\ri0\sa200\sl276\slmult1\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs28\alang1054
\ltrch\fcs0 \fs22\lang1033\langfe1033\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 \snext0 \sqformat \spriority0 Normal;}{\*\cs10 \additive \ssemihidden \sunhideused \spriority1 Default Paragraph Font;}{\*
\ts11\tsrowd\trftsWidthB3\trpaddl108\trpaddr108\trpaddfl3\trpaddft3\trpaddfb3\trpaddfr3\trcbpat1\trcfpat1\tblind0\tblindtype3\tscellwidthfts0\tsvertalt\tsbrdrt\tsbrdrl\tsbrdrb\tsbrdrr\tsbrdrdgl\tsbrdrdgr\tsbrdrh\tsbrdrv \ql \li0\ri0\sa200\sl276\slmult1
\widctlpar\wrapdefault\aspalpha\aspnum\faauto\adjustright\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs28\alang1054 \ltrch\fcs0 \fs22\lang1033\langfe1033\loch\f31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033
\snext11 \ssemihidden \sunhideused \sqformat Normal Table;}}{\*\rsidtbl \rsid7697659}{\mmathPr\mmathFont34\mbrkBin0\mbrkBinSub0\msmallFrac0\mdispDef1\mlMargin0\mrMargin0\mdefJc1\mwrapIndent1440\mintLim0\mnaryLim1}{\info{\operator iJoop-mac}
{\creatim\yr2012\mo8\dy8\hr21\min6}{\revtim\yr2012\mo8\dy8\hr21\min8}{\version2}{\edmins2}{\nofpages1}{\nofwords74}{\nofchars267}{\nofcharsws340}{\vern32859}}{\*\xmlnstbl {\xmlns1 http://schemas.microsoft.com/office/word/2003/wordml}}
\paperw11905\paperh16837\margl1440\margr1440\margt1440\margb1440\gutter0\ltrsect
\widowctrl\ftnbj\aenddoc\trackmoves1\trackformatting1\donotembedsysfont0\relyonvml0\donotembedlingdata1\grfdocevents0\validatexml0\showplaceholdtext0\ignoremixedcontent0\saveinvalidxml0\showxmlerrors0\horzdoc\dghspace120\dgvspace120\dghorigin1701
\dgvorigin1984\dghshow0\dgvshow3\jcompress\viewkind1\viewscale90\ApplyBrkRules\rsidroot7697659 \fet0{\*\wgrffmtfilter 2450}\ilfomacatclnup0\ltrpar \sectd \ltrsect\linex0\sectdefaultcl\sftnbj {\*\pnseclvl1\pnucrm\pnstart1\pnindent720\pnhang {\pntxta .}}
{\*\pnseclvl2\pnucltr\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl3\pndec\pnstart1\pnindent720\pnhang {\pntxta .}}{\*\pnseclvl4\pnlcltr\pnstart1\pnindent720\pnhang {\pntxta )}}{\*\pnseclvl5\pndec\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}
{\*\pnseclvl6\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl7\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl8\pnlcltr\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}{\*\pnseclvl9
\pnlcrm\pnstart1\pnindent720\pnhang {\pntxtb (}{\pntxta )}}\pard\plain \ltrpar\ql \li0\ri0\sa200\nowidctlpar\wrapdefault\faauto\rin0\lin0\itap0 \rtlch\fcs1 \af31507\afs28\alang1054 \ltrch\fcs0
\fs22\lang1033\langfe1033\loch\af31506\hich\af31506\dbch\af31505\cgrid\langnp1033\langfenp1033 {\rtlch\fcs0 \afs32 \ltrch\fcs1 \f39\fs32\cf17\lang1054\insrsid7697659\charrsid7697659 \'e1\'b5\'e8\'c1\'d5}{\rtlch\fcs0 \af40\afs32 \ltrch\fcs1
\f40\fs32\cf17\lang1054\insrsid7697659\charrsid7697659 3 }{\rtlch\fcs0 \afs32 \ltrch\fcs1 \f39\fs32\cf17\lang1054\insrsid7697659\charrsid7697659 \'a4\'d3\'b6\'d2\'c1\'b7\'d5\'e8\'a4\'d8\'b3\'a8\'d0\'b5\'e9\'cd\'a7\'b6\'d2\'c1\'b5\'d1\'c7\'e0\'cd\'a7\'a1
\'e8\'cd\'b9\'b7\'d5\'e8\'a8\'d0\'b7\'d3\'e1\'ba\'c3\'b9\'b4\'ec\'c7\'e8\'d2}{\rtlch\fcs1 \af40\afs32 \ltrch\fcs0 \f40\fs32\cf17\insrsid7697659\charrsid7697659 \loch\af40\dbch\af31505\hich\f40 \'85.}{\rtlch\fcs0 \af40\afs32 \ltrch\fcs1
\f698\fs32\cf17\lang1054\insrsid7697659\charrsid7697659 \'b7\'d3\'cd\'d0\'e4\'c3 \'e0\'be\'d7\'e8\'cd\'cd\'d0\'e4\'c3 \'e4\'b4\'e9\'cd\'d0\'e4\'c3}{\rtlch\fcs0 \af40\afs32 \ltrch\fcs1 \f23\fs32\cf17\lang1054\insrsid7697659\charrsid7697659
\par }{\rtlch\fcs0 \afs24 \ltrch\fcs1 \f39\fs24\cf17\lang1054\insrsid7697659 \'ca\'d5\'cd\'d0\'e4\'c3\'a8\'d6\'a7\'a8\'d0\'cb\'c1\'d2\'c2\'b6\'d6\'a7\'ba\'d8\'a4\'c5\'d4\'a1\'a2\'cd\'a7\'b5\'c3\'d2\'ca\'d4\'b9\'a4\'e9\'d2\'a4\'d8\'b3}{\rtlch\fcs0 \af40\afs24
\ltrch\fcs1 \f40\fs24\cf17\lang1054\insrsid7697659 (}{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659 \hich\af40\dbch\af31505\loch\f40 \hich\f40 Brand Personality)\'85.}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1
\f698\fs30\cf17\lang1054\insrsid7697659 \'ca\'d5\'b7\'d5\'e8\'e4\'c1\'e8\'a2\'d1\'b4\'a1\'d1\'ba\'ca\'d4\'b9\'a4\'e9\'d2}{\rtlch\fcs1 \af23\afs30 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659\charrsid7697659
\par }{\rtlch\fcs0 \afs24 \ltrch\fcs1 \f39\fs24\cf17\lang1054\insrsid7697659 \'ca\'d5\'cd\'d0\'e4\'c3\'b7\'d5\'e8\'e0\'cb\'c1\'d2\'d0\'ca\'c1\'a1\'d1\'ba\'c5\'d1\'a1\'c9\'b3\'d0\'a2\'cd\'a7\'ca\'d4\'b9\'a4\'e9\'d2}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1
\f40\fs24\cf17\lang1054\insrsid7697659 / }{\rtlch\fcs0 \afs24 \ltrch\fcs1 \f39\fs24\cf17\lang1054\insrsid7697659 \'ba\'c3\'d4\'a1\'d2\'c3\'a4\'d8\'b3}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1 \f40\fs24\cf17\lang1054\insrsid7697659 (}{\rtlch\fcs1 \af40\afs24
\ltrch\fcs0 \f40\fs24\cf17\insrsid7697659 \hich\af40\dbch\af31505\loch\f40 \hich\f40 Brand Characteristic)\'85.}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1 \f698\fs30\cf17\lang1054\insrsid7697659 \'ca\'d5\'b7\'d5\'e8\'e4\'c1\'e8\'a2\'d1\'b4\'a1\'d1\'ba\'ca\'d4
\'b9\'a4\'e9\'d2}{\rtlch\fcs1 \af23\afs30 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659\charrsid7697659
\par }{\rtlch\fcs0 \afs24 \ltrch\fcs1 \f39\fs24\cf17\lang1054\insrsid7697659 \'ca\'d4\'e8\'a7\'b7\'d5\'e8\'ca\'d5\'a4\'d9\'e8\'e1\'a2\'e8\'a7\'e3\'aa\'e9\'a7\'d2\'b9\'e0\'bb\'e7\'b9\'cd\'c2\'e8\'d2\'a7\'e4\'c3}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1
\f40\fs24\cf17\lang1054\insrsid7697659 (}{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659 \hich\af40\dbch\af31505\loch\f40 Br}{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659 \hich\af40\dbch\af31505\loch\f40 \hich\f40
and Competitor Comparisons)\'85}{\rtlch\fcs0 \af40\afs24 \ltrch\fcs1 \f698\fs30\cf17\lang1054\insrsid7697659 \'ca\'d5\'ca\'b4\'e3\'ca}{\rtlch\fcs1 \af23\afs30 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659\charrsid7697659
\par }{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659
\par }{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659
\par }{\rtlch\fcs1 \af40\afs24 \ltrch\fcs0 \f40\fs24\cf17\insrsid7697659
\par \hich\af40\dbch\af31505\loch\f40 Prompt Design}{\rtlch\fcs1 \af31507 \ltrch\fcs0 \insrsid7697659
\par }{\*\themedata 504b030414000600080000002100828abc13fa0000001c020000130000005b436f6e74656e745f54797065735d2e786d6cac91cb6ac3301045f785fe83d0b6d8
72ba28a5d8cea249777d2cd20f18e4b12d6a8f843409c9df77ecb850ba082d74231062ce997b55ae8fe3a00e1893f354e9555e6885647de3a8abf4fbee29bbd7
2a3150038327acf409935ed7d757e5ee14302999a654e99e393c18936c8f23a4dc072479697d1c81e51a3b13c07e4087e6b628ee8cf5c4489cf1c4d075f92a0b
44d7a07a83c82f308ac7b0a0f0fbf90c2480980b58abc733615aa2d210c2e02cb04430076a7ee833dfb6ce62e3ed7e14693e8317d8cd0433bf5c60f53fea2fe7
065bd80facb647e9e25c7fc421fd2ddb526b2e9373fed4bb902e182e97b7b461e6bfad3f010000ffff0300504b030414000600080000002100a5d6a7e7c00000
00360100000b0000005f72656c732f2e72656c73848fcf6ac3300c87ef85bd83d17d51d2c31825762fa590432fa37d00e1287f68221bdb1bebdb4fc7060abb08
84a4eff7a93dfeae8bf9e194e720169aaa06c3e2433fcb68e1763dbf7f82c985a4a725085b787086a37bdbb55fbc50d1a33ccd311ba548b63095120f88d94fbc
52ae4264d1c910d24a45db3462247fa791715fd71f989e19e0364cd3f51652d73760ae8fa8c9ffb3c330cc9e4fc17faf2ce545046e37944c69e462a1a82fe353
bd90a865aad41ed0b5b8f9d6fd010000ffff0300504b0304140006000800000021006b799616830000008a0000001c0000007468656d652f7468656d652f7468
656d654d616e616765722e786d6c0ccc4d0ac3201040e17da17790d93763bb284562b2cbaebbf600439c1a41c7a0d29fdbd7e5e38337cedf14d59b4b0d592c9c
070d8a65cd2e88b7f07c2ca71ba8da481cc52c6ce1c715e6e97818c9b48d13df49c873517d23d59085adb5dd20d6b52bd521ef2cdd5eb9246a3d8b4757e8d3f7
29e245eb2b260a0238fd010000ffff0300504b03041400060008000000210096b5ade296060000501b0000160000007468656d652f7468656d652f7468656d65
312e786d6cec594f6fdb3614bf0fd87720746f6327761a07758ad8b19b2d4d1bc46e871e698996d850a240d2497d1bdae38001c3ba618715d86d87615b8116d8
a5fb34d93a6c1dd0afb0475292c5585e9236d88aad3e2412f9e3fbff1e1fa9abd7eec70c1d1221294fda5efd72cd4324f1794093b0eddd1ef62fad79482a9c04
98f184b4bd2991deb58df7dfbb8ad755446282607d22d771db8b944ad79796a40fc3585ee62949606ecc458c15bc8a702910f808e8c66c69b9565b5d8a314d3c
94e018c8de1a8fa94fd05093f43672e23d06af89927ac06762a049136785c10607758d9053d965021d62d6f6804fc08f86e4bef210c352c144dbab999fb7b471
7509af678b985ab0b6b4ae6f7ed9ba6c4170b06c788a705430adf71bad2b5b057d03606a1ed7ebf5babd7a41cf00b0ef83a6569632cd467faddec9699640f671
9e76b7d6ac355c7c89feca9cccad4ea7d36c65b258a206641f1b73f8b5da6a6373d9c11b90c537e7f08dce66b7bbeae00dc8e257e7f0fd2badd5868b37a088d1
e4600ead1ddaef67d40bc898b3ed4af81ac0d76a197c86826828a24bb318f3442d8ab518dfe3a20f000d6458d104a9694ac6d88728eee2782428d60cf03ac1a5
193be4cbb921cd0b495fd054b5bd0f530c1931a3f7eaf9f7af9e3f45c70f9e1d3ff8e9f8e1c3e3073f5a42ceaa6d9c84e5552fbffdeccfc71fa33f9e7ef3f2d1
17d57859c6fffac327bffcfc793510d26726ce8b2f9ffcf6ecc98baf3efdfdbb4715f04d814765f890c644a29be408edf3181433567125272371be15c308d3f2
8acd249438c19a4b05fd9e8a1cf4cd296699771c393ac4b5e01d01e5a30a787d72cf1178108989a2159c77a2d801ee72ce3a5c545a6147f32a99793849c26ae6
6252c6ed637c58c5bb8b13c7bfbd490a75330f4b47f16e441c31f7184e140e494214d273fc80900aedee52ead87597fa824b3e56e82e451d4c2b4d32a423279a
668bb6690c7e9956e90cfe766cb37b077538abd27a8b1cba48c80acc2a841f12e698f13a9e281c57911ce298950d7e03aba84ac8c154f8655c4f2af074481847
bd804859b5e696007d4b4edfc150b12addbecba6b18b148a1e54d1bc81392f23b7f84137c2715a851dd0242a633f900710a218ed715505dfe56e86e877f0034e
16bafb0e258ebb4faf06b769e888340b103d3311da9750aa9d0a1cd3e4efca31a3508f6d0c5c5c398602f8e2ebc71591f5b616e24dd893aa3261fb44f95d843b
5974bb5c04f4edafb95b7892ec1108f3f98de75dc97d5772bdff7cc95d94cf672db4b3da0a6557f70db629362d72bcb0431e53c6066acac80d699a6409fb44d0
8741bdce9c0e4971624a2378cceaba830b05366b90e0ea23aaa241845368b0eb9e2612ca8c742851ca251ceccc70256d8d87265dd96361531f186c3d9058edf2
c00eafe8e1fc5c509031bb4d680e9f39a3154de0accc56ae644441edd76156d7429d995bdd88664a9dc3ad50197c38af1a0c16d684060441db02565e85f3b966
0d0713cc48a0ed6ef7dedc2dc60b17e92219e180643ed27acffba86e9c94c78ab90980d8a9f0913ee49d62b512b79626fb06dccee2a432bbc60276b9f7dec44b
7904cfbca4f3f6443ab2a49c9c2c41476dafd55c6e7ac8c769db1bc399161ee314bc2e75cf8759081743be1236ec4f4d6693e5336fb672c5dc24a8c33585b5fb
9cc24e1d4885545b58463634cc5416022cd19cacfccb4d30eb45296023fd35a458598360f8d7a4003bbaae25e331f155d9d9a5116d3bfb9a95523e51440ca2e0
088dd844ec6370bf0e55d027a012ae264c45d02f708fa6ad6da6dce29c255df9f6cae0ec38666984b372ab5334cf640b37795cc860de4ae2816e95b21be5ceaf
8a49f90b52a51cc6ff3355f47e0237052b81f6800fd7b802239daf6d8f0b1571a8426944fdbe80c6c1d40e8816b88b8569082ab84c36ff0539d4ff6dce591a26
ade1c0a7f669880485fd484582903d284b26fa4e2156cff62e4b9265844c4495c495a9157b440e091bea1ab8aaf7760f4510eaa69a6465c0e04ec69ffb9e65d0
28d44d4e39df9c1a52ecbd3607fee9cec7263328e5d661d3d0e4f62f44acd855ed7ab33cdf7bcb8ae889599bd5c8b3029895b6825696f6af29c239b75a5bb1e6
345e6ee6c28117e73586c1a2214ae1be07e93fb0ff51e133fb65426fa843be0fb515c187064d0cc206a2fa926d3c902e907670048d931db4c1a44959d366ad93
b65abe595f70a75bf03d616c2dd959fc7d4e6317cd99cbcec9c58b34766661c7d6766ca1a9c1b327531486c6f941c638c67cd22a7f75e2a37be0e82db8df9f30
254d30c1372581a1f51c983c80e4b71ccdd28dbf000000ffff0300504b0304140006000800000021000dd1909fb60000001b010000270000007468656d652f74
68656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73848f4d0ac2301484f78277086f6fd3ba109126dd88d0add40384e4350d363f24
51eced0dae2c082e8761be9969bb979dc9136332de3168aa1a083ae995719ac16db8ec8e4052164e89d93b64b060828e6f37ed1567914b284d262452282e3198
720e274a939cd08a54f980ae38a38f56e422a3a641c8bbd048f7757da0f19b017cc524bd62107bd5001996509affb3fd381a89672f1f165dfe514173d9850528
a2c6cce0239baa4c04ca5bbabac4df000000ffff0300504b01022d0014000600080000002100828abc13fa0000001c0200001300000000000000000000000000
000000005b436f6e74656e745f54797065735d2e786d6c504b01022d0014000600080000002100a5d6a7e7c0000000360100000b000000000000000000000000
002b0100005f72656c732f2e72656c73504b01022d00140006000800000021006b799616830000008a0000001c00000000000000000000000000140200007468
656d652f7468656d652f7468656d654d616e616765722e786d6c504b01022d001400060008000000210096b5ade296060000501b000016000000000000000000
00000000d10200007468656d652f7468656d652f7468656d65312e786d6c504b01022d00140006000800000021000dd1909fb60000001b010000270000000000
00000000000000009b0900007468656d652f7468656d652f5f72656c732f7468656d654d616e616765722e786d6c2e72656c73504b050600000000050005005d010000960a00000000}
{\*\colorschememapping 3c3f786d6c2076657273696f6e3d22312e302220656e636f64696e673d225554462d3822207374616e64616c6f6e653d22796573223f3e0d0a3c613a636c724d
617020786d6c6e733a613d22687474703a2f2f736368656d61732e6f70656e786d6c666f726d6174732e6f72672f64726177696e676d6c2f323030362f6d6169
6e22206267313d226c743122207478313d22646b3122206267323d226c743222207478323d22646b322220616363656e74313d22616363656e74312220616363
656e74323d22616363656e74322220616363656e74333d22616363656e74332220616363656e74343d22616363656e74342220616363656e74353d22616363656e74352220616363656e74363d22616363656e74362220686c696e6b3d22686c696e6b2220666f6c486c696e6b3d22666f6c486c696e6b222f3e}
{\*\latentstyles\lsdstimax267\lsdlockeddef0\lsdsemihiddendef1\lsdunhideuseddef1\lsdqformatdef0\lsdprioritydef99{\lsdlockedexcept \lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority0 \lsdlocked0 Normal;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority9 \lsdlocked0 heading 1;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 2;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 3;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 4;
\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 5;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 6;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 7;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 8;\lsdqformat1 \lsdpriority9 \lsdlocked0 heading 9;
\lsdpriority39 \lsdlocked0 toc 1;\lsdpriority39 \lsdlocked0 toc 2;\lsdpriority39 \lsdlocked0 toc 3;\lsdpriority39 \lsdlocked0 toc 4;\lsdpriority39 \lsdlocked0 toc 5;\lsdpriority39 \lsdlocked0 toc 6;\lsdpriority39 \lsdlocked0 toc 7;
\lsdpriority39 \lsdlocked0 toc 8;\lsdpriority39 \lsdlocked0 toc 9;\lsdqformat1 \lsdpriority35 \lsdlocked0 caption;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority10 \lsdlocked0 Title;\lsdpriority1 \lsdlocked0 Default Paragraph Font;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority11 \lsdlocked0 Subtitle;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority22 \lsdlocked0 Strong;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority20 \lsdlocked0 Emphasis;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority59 \lsdlocked0 Table Grid;\lsdunhideused0 \lsdlocked0 Placeholder Text;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority1 \lsdlocked0 No Spacing;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 1;\lsdunhideused0 \lsdlocked0 Revision;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority34 \lsdlocked0 List Paragraph;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority29 \lsdlocked0 Quote;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority30 \lsdlocked0 Intense Quote;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 1;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 1;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 2;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 2;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 3;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 3;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 4;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 4;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 5;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 5;\lsdsemihidden0 \lsdunhideused0 \lsdpriority60 \lsdlocked0 Light Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority61 \lsdlocked0 Light List Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority62 \lsdlocked0 Light Grid Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority63 \lsdlocked0 Medium Shading 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority64 \lsdlocked0 Medium Shading 2 Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority65 \lsdlocked0 Medium List 1 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority66 \lsdlocked0 Medium List 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority67 \lsdlocked0 Medium Grid 1 Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority68 \lsdlocked0 Medium Grid 2 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority69 \lsdlocked0 Medium Grid 3 Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority70 \lsdlocked0 Dark List Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdpriority71 \lsdlocked0 Colorful Shading Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority72 \lsdlocked0 Colorful List Accent 6;\lsdsemihidden0 \lsdunhideused0 \lsdpriority73 \lsdlocked0 Colorful Grid Accent 6;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority19 \lsdlocked0 Subtle Emphasis;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority21 \lsdlocked0 Intense Emphasis;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority31 \lsdlocked0 Subtle Reference;\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority32 \lsdlocked0 Intense Reference;
\lsdsemihidden0 \lsdunhideused0 \lsdqformat1 \lsdpriority33 \lsdlocked0 Book Title;\lsdpriority37 \lsdlocked0 Bibliography;\lsdqformat1 \lsdpriority39 \lsdlocked0 TOC Heading;}}{\*\datastore 010500000200000018000000
4d73786d6c322e534158584d4c5265616465722e352e3000000000000000000000060000
d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff090006000000000000000000000001000000010000000000000000100000feffffff00000000feffffff0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
fffffffffffffffffdfffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
ffffffffffffffffffffffffffffffff52006f006f007400200045006e00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500ffffffffffffffffffffffffec69d9888b8b3d4c859eaf6cd158be0f000000000000000000000000f05d
924d6f75cd01feffffff00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff00000000000000000000000000000000000000000000000000000000
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ffffffffffffffffffffffff000000000000000000000000000000000000000000000000
0000000000000000000000000000000000000000000000000105000000000000}} | 029-kornkamol | trunk/คำถาม.rtf | Rich Text Format | gpl2 | 33,409 |
#include "OK.h"
#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
#include <list>
#include <ctime>
using namespace std;
int main(int argc, char *argv[])
{
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
try {
char* input=(argc>1?argv[1]:"data.dat");
char* output=(argc>2?argv[2]:"result.out");
int minSup = (argc>3?atoi(argv[3]):0);
bool asChars = (argc>4 && argv[4][0]=='c');
cout<<"asChars: "<<asChars<<endl;
DataStructure* data = loadDataSet(input);
data->printSummary(std::cout);
cout<<endl;
std::ofstream fc(output);
OK(data,&fc,minSup,NULL,asChars);
fc.close();
delete data;
}
catch (std::exception e) {
e.what();
}
_CrtDumpMemoryLeaks();
system("PAUSE");
return 0;
}
void OK(DataStructure *ds, std::ofstream *fc, unsigned int minSup, bool (*sort_f)(const OAPair &e1, const OAPair &e2), bool printAsChars){
long startTime = clock();
if(ds->getAllObjects()->data.size()<2){
cout<<"One object only"<<endl;
return;
}
ObjectSet* commonObjects=NULL;
FormalContext* initialContext = new FormalContext();
vector<const OAPair * const> *frequentClosedItemsets;
for (std::set<Attribute>::const_iterator i = ds->getAllAtributes()->data.begin(); i != ds->getAllAtributes()->data.end(); i++){
//if the objects exist for the atrribute in a number no less than minSup
ObjectSet* support = ds->getObjects(*i);
if(support->data.size() >= minSup){
//////initializing context as side-effect///////////
OAPair tmpPair = std::make_pair( support , new AttributeSet());
tmpPair.second->data.insert(Attribute(*i));
initialContext->data.push_back(tmpPair);
////////////////////////////////////////////////////
if(commonObjects==NULL){
//first one
commonObjects=new ObjectSet(*(ds->getObjects(*i)));
}else{
//remove non-matching ones
for(std::set<Object>::iterator stored = commonObjects->data.begin();
stored != commonObjects->data.end();){
if(ds->getObjects(*i)->data.find(*stored)==ds->getObjects(*i)->data.end()){
std::set<Object>::iterator toRemove = stored++;
commonObjects->data.erase(toRemove);
//perhaps all 've been removed
if(commonObjects->data.size()==0){
break;
}
continue;
}
stored++;
}
}
}else{
if(commonObjects!=NULL){
commonObjects->data.erase(commonObjects->data.begin(), commonObjects->data.end());
}
}
}
if(commonObjects==NULL){
cout<<endl<<"Not a single item has been found with sufficient support. Aborting"<<endl;
cleanUpFormalContext(initialContext, false, true);
return;
}else{
frequentClosedItemsets = new vector<const OAPair* const>();
if(commonObjects->data.size()>0){
OAPair *found = new OAPair();
found->first=commonObjects;
found->second=ds->getAllAtributes();
insertFrequentItemset(found, frequentClosedItemsets);
minSup=commonObjects->data.size()+1;
}else{
if(minSup==0){
++minSup;
}
frequentClosedItemsets->push_back(new pair<ObjectSet*, AttributeSet*>(new ObjectSet(), new AttributeSet(*ds->getAllAtributes())));
}
delete commonObjects;
}
if(ds->getAllObjects()->data.size()>=minSup){
ObjectSet *allObjectSet = new ObjectSet(*(ds->getAllObjects()));
AttributeSet *initialAttributeSet = new AttributeSet();
AttributeSet *attrSet4oa = new AttributeSet();
OAPair* oa = new pair<ObjectSet*, AttributeSet*>(allObjectSet, attrSet4oa);
FormalContext *localContext = OKLocalContext(*oa, initialContext);
Closure(*initialAttributeSet, *oa, *localContext);
insertFrequentItemset(oa, frequentClosedItemsets);
OKExtend(initialAttributeSet, localContext, sort_f, minSup, frequentClosedItemsets);
//printFrequentClosedItemsets(frequentClosedItemsets, printAsChars);
printFrequentClosedItemsets(frequentClosedItemsets, printAsChars, *fc);
cleanUpFormalContext(localContext, true, true);
delete initialAttributeSet;
cleanUpOAPair(oa);
cleanUpFormalContext(initialContext, false, true);
}
cleanUpFrequentClosedItemsets(frequentClosedItemsets);
float exTime=(clock()-startTime)/(float)1000;
*fc<<"OK completion time: "<<exTime<<" seconds"<<endl;
cout<<"OK completion time: "<<exTime<<" seconds"<<endl;
}
void OKExtend(AttributeSet * prefix, FormalContext *P, bool (*sort_f)(const OAPair &e1, const OAPair &e2), unsigned int minSup, vector<const OAPair* const> *frequentClosedItemsets){
Order((*P),sort_f);
if(!checkOrder(P)){
cout<<"Context in wrong order"<<endl;
system("PAUSE");
}
for(vector<OAPair>::iterator iter = P->data.begin()+P->processedNo; iter!=P->data.end() && iter!=--(P->data.end()); ++iter){
iter->second->processed=true;
if(isClosable(*iter, *P)){
FormalContext *poa = OKLocalContextMinSup(*iter, P, minSup);
Closure(*prefix, *iter, *poa);
insertFrequentItemset(&OAPair(*iter), frequentClosedItemsets);
if(poa->data.size()>poa->processedNo){
OKExtend(iter->second, poa, sort_f, minSup, frequentClosedItemsets);
}
cleanUpFormalContext(poa, true, true);
}
}
if(P->data.size()>0 && isClosable(*(P->data.rbegin()),*P)){
OAPair *oapair = new pair<ObjectSet*, AttributeSet*>(new ObjectSet(),new AttributeSet());
oapair->first->data.insert(P->data.rbegin()->first->data.begin(), P->data.rbegin()->first->data.end());
oapair->second->data.insert(P->data.rbegin()->second->data.begin(), P->data.rbegin()->second->data.end());
oapair->second->data.insert(prefix->data.begin(), prefix->data.end());
insertFrequentItemset(oapair, frequentClosedItemsets);
cleanUpOAPair(oapair);
}
}
bool isClosable(const OAPair & const oa_pair, FormalContext &local_fc){
if(!checkOrder(&local_fc)){
cout<<"Context elements order violated"<<endl;
system("PAUSE");
}
list<const OAPair* const> deltaClosureProcessed;
int offset = local_fc.data.size()-local_fc.processedNo;
for(vector<OAPair>::const_reverse_iterator iter = local_fc.data.rbegin()+offset; iter != local_fc.data.rend(); ++iter){
printOAPair(&*iter);
if(iter->first->data.size()>oa_pair.first->data.size()){
deltaClosureProcessed.push_back(&*iter);
}
}
if(deltaClosureProcessed.size()==0){
return true;
}
for(set<Object>::const_iterator itero = oa_pair.first->data.begin(); itero!=oa_pair.first->data.end(); ++itero){
for(list<const OAPair* const>::iterator iteryb = deltaClosureProcessed.begin(); iteryb!=deltaClosureProcessed.end(); ){
bool deltaClosureUnchanged=true;
for(set<Object>::const_iterator itery = (*iteryb)->first->data.begin(); itery!=(*iteryb)->first->data.end(); ++itery){
if(*itery<*itero){
continue;
}
if((*iteryb)->first->data.find(*itero)==(*iteryb)->first->data.end()){
deltaClosureProcessed.erase(iteryb++);
deltaClosureUnchanged=false;
break;
}else{
//nothing = skip o in Y
}
}
if(deltaClosureUnchanged){
++iteryb;
}
}
}
return(deltaClosureProcessed.size()==0);
}
void printFrequentClosedItemsets(const vector<const OAPair* const> * const fci, bool asChars, ostream &sink){
sink<<endl;
sink<<"FREQUENT CLOSED ITEMSETS:"<<endl;
for(vector<const OAPair* const>::const_iterator iter = fci->begin(); iter!=fci->end(); ++iter){
printOAPair(*iter, asChars, sink);
}
}
void printOAPair(const OAPair * const oa, bool asChars, ostream &sink){
ObjectSet *O = oa->first;
AttributeSet *A = oa->second;
sink<< "O:{ ";
for (std::set<Object>::const_iterator i = O->data.begin(); i != O->data.end(); i++){
sink<< *i << " ";
}
sink << "}, A:{ ";
for (std::set<Attribute>::const_iterator i = A->data.begin(); i != A->data.end(); i++){
if(asChars){
sink<< (char)('a'-1+*i) << " ";
}else{
sink<<(*i) << " ";
}
}
sink<< "}" <<endl;
}
void printFormalContext(const FormalContext * const fc, ostream &sink){
sink<<"**FORMAL CONTEXT DUMP ***proc: " <<fc->processedNo<<" ******" << endl;
for(vector<OAPair>::const_iterator iter = fc->data.begin(); iter!=fc->data.end(); ++iter){
printOAPair(&*iter);
}
sink<<""<<endl;
}
void cleanUpFormalContext(FormalContext* fc, bool removeObjects, bool removeAttributes){
for(vector<OAPair>::iterator iter = fc->data.begin(); iter!=fc->data.end(); ++iter){
if(removeObjects){
delete iter->first;
}if(removeAttributes){
delete iter->second;
}
}
delete fc;
}
void cleanUpOAPair(OAPair* oa){
delete oa->first;
delete oa->second;
delete oa;
}
void insertFrequentItemset(const OAPair* const oa, vector<const OAPair* const> * const fci){
for(vector<const OAPair* const>::const_iterator iter = fci->begin(); iter!=fci->end(); ++iter){
if(*((*iter)->second)==*(oa->second)){
return;
}
}
fci->push_back(new pair<ObjectSet*, AttributeSet*>(new ObjectSet(*(oa->first)), new AttributeSet(*(oa->second))));
}
void cleanUpFrequentClosedItemsets(vector<const OAPair* const>* fci){
for(vector<const OAPair* const>::iterator iter = fci->begin(); iter!=fci->end(); ){
vector<const OAPair* const>::iterator eraser = iter++;
OAPair* tmp = const_cast<OAPair*>(*eraser);
cleanUpOAPair(tmp);
}
delete fci;
}
bool checkOrder(const FormalContext * const fc){
//bool onFresh=false;
bool onProcessed=true;
for(vector<OAPair>::const_iterator iter = fc->data.begin(); iter!=fc->data.end(); ++iter ){
if(iter->second->processed){
if(onProcessed){
continue;
}else{
return false;
}
}else{
if(onProcessed){
onProcessed=false;
}
}
}
return true;
} | 12l-edami-okkov | trunk/ok/OK.cpp | C++ | gpl3 | 9,791 |
/**
* Implementation of Closure function
*
* author: Marcin Wachulski
*
*/
#include "OK.h"
#include <set>
#include <algorithm>
#include <iterator>
void Closure(const AttributeSet &prefix, OAPair &oa_pair, FormalContext &local_fc) {
oa_pair.second->data.insert(prefix.data.begin(), prefix.data.end());
if (local_fc.data.size() > local_fc.processedNo) {
OAPair &fc_last_p = local_fc.data.back();
if (fc_last_p.first->data.size() == oa_pair.first->data.size()) {
oa_pair.second->data.insert(fc_last_p.second->data.begin(),
fc_last_p.second->data.end());
local_fc.data.pop_back();
delete fc_last_p.first;
delete fc_last_p.second;
}
}
} | 12l-edami-okkov | trunk/ok/Closure.cpp | C++ | gpl3 | 760 |
/**
* Functions responsible for determining the local context for the OK algorithm.
*
* author: Maciej Rubikowski
*/
#include "ok.h"
typedef std::pair<ObjectSet, FormalContext*> ObjectContextPair;
typedef std::vector<ObjectContextPair> LocalContextGrouping;
FormalContext* OKLocalContext(const OAPair &oa, const FormalContext * const P) {
FormalContext *FC = new FormalContext;
LocalContextGrouping G;
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
ObjectContextPair ocp = std::pair<ObjectSet, FormalContext*>(ObjectSet(), new FormalContext(*P));
G.push_back(ocp);
for (std::set<Object>::const_iterator o = O->data.begin(); o != O->data.end(); ++o) {
LocalContextGrouping set_S;
ObjectSet *Z = NULL;
FormalContext *E = NULL;
for (std::vector<ObjectContextPair>::iterator j = G.begin(); j != G.end();) {
Z = &j->first;
E = j->second;
ObjectSet os = *Z;
os.data.insert(*o);
ObjectContextPair S = std::pair<ObjectSet, FormalContext*>(os, new FormalContext);
for (std::vector<OAPair>::iterator YB = E->data.begin(); YB != E->data.end(); ) {
// remove all y from Y such that y precedes o
// and BTW check if o belongs to Y
ObjectSet *Y = YB->first;
AttributeSet *B = YB->second;
bool oInY = false;
for (std::set<Object>::iterator y = Y->data.begin(); y != Y->data.end(); ) {
if (*y < *o)
y = Y->data.erase(y);
else if (*y == *o) {
oInY = true;
break;
} else {
++y;
}
}
// if object o belongs to Y...
if (oInY) {
Y->data.erase(*o); // remove o from Y
S.second->data.push_back(*YB);
YB = E->data.erase(YB); // remove (Y, B) from E
} else
++YB;
}
// if the second element of S is different from null_set then
if (!S.second->data.empty()) {
set_S.push_back(S);
if (E->data.empty()) {
j = G.erase(j);
delete E;
} else {
++j;
}
} else {
delete S.second;
++j;
}
}
G.insert(G.end(), set_S.begin(), set_S.end());
}
// prepare P<O, A>
for (LocalContextGrouping::iterator it = G.begin(); it != G.end();) {
if (it->second->data.empty()) {
++it;
continue;
}
ObjectSet *Z = new ObjectSet(it->first);
AttributeSet *D = new AttributeSet;
for (std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2)
D->data.insert(it2->second->data.begin(), it2->second->data.end());
D->processed = false;
FC->data.push_back(OAPair(Z, D));
++it;
}
// clean up
for(LocalContextGrouping::iterator it = G.begin(); it != G.end(); ++it) {
for(std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
delete it2->first;
delete it2->second;
}
delete it->second;
}
return FC;
}
FormalContext *OKLocalContextMinSup(const OAPair &oa, const FormalContext * const P, unsigned int minSup) {
LocalContextGrouping G;
FormalContext *FC = new FormalContext;
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
// prepare the initial grouping
FormalContext *FC2 = new FormalContext;
for (std::vector<OAPair>::const_iterator it = P->data.begin(); it != P->data.end(); ++it) {
if (*(oa.second) != *(it->second)) {
OAPair oap = OAPair(new ObjectSet(*it->first), new AttributeSet(*it->second));
FC2->data.push_back(oap);
}
}
ObjectContextPair ocp = std::pair<ObjectSet, FormalContext*>(ObjectSet(), FC2);
G.push_back(ocp);
for (std::set<Object>::const_iterator o = O->data.begin(); o != O->data.end(); ++o) {
LocalContextGrouping set_S;
ObjectSet *Z = NULL;
FormalContext *E = NULL;
for (std::vector<ObjectContextPair>::iterator j = G.begin(); j != G.end();) {
Z = &j->first;
E = j->second;
ObjectSet os = *Z;
os.data.insert(*o);
ObjectContextPair S = std::make_pair<ObjectSet, FormalContext*>(os, new FormalContext);
for (std::vector<OAPair>::iterator YB = E->data.begin(); YB != E->data.end();) {
// remove all y from Y such that y precedes o
// and BTW check if o belongs to Y
ObjectSet *Y = YB->first;
AttributeSet *B = YB->second;
bool oInY = false;
for (std::set<Object>::iterator y = YB->first->data.begin(); y != YB->first->data.end();) {
if (*y < *o)
y = Y->data.erase(y);
else if (*y == *o) {
oInY = true;
break;
} else {
++y;
}
}
// if object o belongs to Y...
if (oInY) {
Y->data.erase(*o); // remove o from Y
S.second->data.push_back(*YB);
YB = E->data.erase(YB); // remove (Y, B) from E
} else
++YB;
}
// if the second element of S is different from null_set then
if (!S.second->data.empty()) {
set_S.push_back(S);
if (E->data.empty()) {
j = G.erase(j);
delete E;
} else {
++j;
}
} else {
delete S.second;
++j;
}
}
G.insert(G.end(), set_S.begin(), set_S.end());
}
// prepare P<O, A>
for (LocalContextGrouping::iterator it = G.begin(); it != G.end();) {
bool isProcessed = false;
if (it->second->data.empty() || it->first.data.size() < minSup) {
++it;
continue;
}
ObjectSet *Z = new ObjectSet(it->first);
AttributeSet *D = new AttributeSet;
for (std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
D->data.insert(it2->second->data.begin(), it2->second->data.end());
isProcessed = it2->second->processed;
}
D->processed = isProcessed;
if (isProcessed) {
++(FC->processedNo);
//FC->data.push_back(OAPair(Z, D));
std::vector<OAPair>::iterator iter=FC->data.begin();
for(; iter!=FC->data.end(); ++iter){
if(!iter->second->processed){
break;
}
}
FC->data.insert(iter,OAPair(Z,D));
}else{
FC->data.push_back(OAPair(Z, D));
}
++it;
}
// clean up
for(LocalContextGrouping::iterator it = G.begin(); it != G.end(); ++it) {
for(std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
delete it2->first;
delete it2->second;
}
delete it->second;
}
return FC;
} | 12l-edami-okkov | trunk/ok/OKLocalContext.cpp | C++ | gpl3 | 6,268 |
/**
* Implementation of Order function
*
* author: Marcin Wachulski
*
*/
#include "OK.h"
#include <algorithm>
void Order(FormalContext &local_fc, bool (*sort_f)(const OAPair &e1, const OAPair &e2)) {
if (local_fc.data.size() < 2)
return;
// processed group
std::sort(local_fc.data.begin(), local_fc.data.begin() + local_fc.processedNo, OAPairCompare);
// non-processed group
std::sort(local_fc.data.begin() + local_fc.processedNo, local_fc.data.end(), OAPairCompare);
} | 12l-edami-okkov | trunk/ok/Order.cpp | C++ | gpl3 | 519 |
#ifndef _OK_H_
#define _OK_H_
// declaration of structures used in OK algorithm implementation
#include "Attribute.h"
#include "AttributeSet.h"
#include "Object.h"
#include "ObjectSet.h"
#include "OAPair.h"
#include "FormalContext.h"
#include "DataStructure.h"
#include "DataSetLoader.h"
#include <iostream>
// central data structure maintaining data loaded from external data source and
// reference pointers to speed up search operations
extern DataStructure data;
// closure computes a closure of OAPair element in local formal context
// represented by local_fc object
void Closure(const AttributeSet &prefix, OAPair &oa_pair, FormalContext &local_fc);
// sort_f is a sort function that compares two OAPair elements and returns true
// iff e1 is less or equal than e2, false conversely
void Order(FormalContext &local_fc, bool (*sort_f)(const OAPair &e1, const OAPair &e2) = NULL);
// determine local context for the first iteration of OK algorithm, i.e.
// w/o considering the minimal support
FormalContext *OKLocalContext(const OAPair &oa, const FormalContext * const P);
// determine local context for the next iterations of OK algorithm (OK-Extend), i.e.
// considering the minimal support
FormalContext *OKLocalContextMinSup(const OAPair &oa, const FormalContext * const P, unsigned int minSup);
void printFrequentClosedItemsets(const std::vector<const OAPair* const> *const fci, bool asChars=true, std::ostream &sink=std::cout);
void printOAPair(const OAPair * const oa, bool asChars=true, std::ostream &sink=std::cout);
void OK(DataStructure *ds, std::ofstream *fc, unsigned int minSup, bool (*sort_f)(const OAPair &e1, const OAPair &e2)=NULL, bool printAsChars=true);
bool isClosable(const OAPair & const oa_pair, FormalContext &local_fc);
void OKExtend(AttributeSet * prefix, FormalContext *P, bool (*sort_f)(const OAPair &e1, const OAPair &e2), unsigned int minSup, std::vector<const OAPair * const> *frequentClosedItemsets);
void printFormalContext(const FormalContext * const fc, std::ostream &sink=std::cout);
//cleans up the unwanted stuff related to formal contexts without messing with existing destructors
void cleanUpFormalContext(FormalContext* fc, bool removeObjects, bool removeAttributes);
//similar, yet for OAPair*
void cleanUpOAPair(OAPair* oa);
//and once more - for the closed itemsets collection
void cleanUpFrequentClosedItemsets(std::vector<const OAPair* const>* frequentClosedItemsets);
//a tool to perform safe insert (without overlaps)
void insertFrequentItemset(const OAPair* const oa, std::vector<const OAPair* const> * const fci);
bool checkOrder(const FormalContext * const fc);
#endif | 12l-edami-okkov | trunk/ok/OK.h | C++ | gpl3 | 2,700 |
/**
* Test collector and executor
*
* author: Marcin Wachulski
*
*/
#include "gtest\gtest.h"
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 12l-edami-okkov | trunk/kov.test/GTest.cpp | C++ | gpl3 | 223 |
/**
* OK test header
*
* author: Marcin Wachulski
*
*/
#include "OK.h"
#include "gtest\gtest.h"
bool is_sorted(const FormalContext &fc); | 12l-edami-okkov | trunk/test/ok/OKTest.h | C | gpl3 | 151 |
/**
* Local context function testing
*
* author: Maciej Rubikowski
*/
#include "OK.h"
#include <iostream>
int main(int argc, char *argv[]) {
FormalContext *FC = new FormalContext;
OAPair oa1;
OAPair oa2;
OAPair oa3;
OAPair oa4;
OAPair oa5;
OAPair oa6;
OAPair oa7;
OAPair oa;
/*
oa.first = new ObjectSet;
oa.first->data.insert(2);
oa.first->data.insert(3);
oa.first->data.insert(6);
oa.second = new AttributeSet;
oa.second->data.insert(Attribute(4));
oa1.first = new ObjectSet;
oa1.first->data.insert(Object(2));
oa1.first->data.insert(Object(4));
oa1.first->data.insert(Object(5));
oa1.first->data.insert(Object(6));
oa1.second = new AttributeSet;
oa1.second->data.insert(Attribute(1));
oa1.second->data.insert(Attribute(6));
oa2.first = new ObjectSet;
oa2.first->data.insert(Object(1));
oa2.first->data.insert(Object(2));
oa2.first->data.insert(Object(4));
oa2.first->data.insert(Object(6));
oa2.second = new AttributeSet;
oa2.second->data.insert(Attribute(3));
oa3.first = new ObjectSet;
oa3.first->data.insert(Object(1));
oa3.first->data.insert(Object(3));
oa3.first->data.insert(Object(4));
oa3.first->data.insert(Object(5));
oa3.second = new AttributeSet;
oa3.second->data.insert(Attribute(5));
oa4.first = new ObjectSet;
oa4.first->data.insert(Object(2));
oa4.first->data.insert(Object(3));
oa4.first->data.insert(Object(4));
oa4.first->data.insert(Object(6));
oa4.second = new AttributeSet;
oa4.second->data.insert(Attribute(8));
FC->data.push_back(oa1);
FC->data.push_back(oa2);
FC->data.push_back(oa3);
FC->data.push_back(oa4);
//commence local context w/o minSup and deltaClosure test
FormalContext *FC2 = OKLocalContext(oa, FC);*/
oa.first = new ObjectSet;
oa.first->data.insert(1);
oa.first->data.insert(4);
oa.first->data.insert(5);
oa.second = new AttributeSet;
oa.second->data.insert(Attribute(2));
oa1.first = new ObjectSet;
oa1.first->data.insert(Object(4));
oa1.second = new AttributeSet;
oa1.second->data.insert(Attribute(7));
oa2.first = new ObjectSet;
oa2.first->data.insert(Object(1));
oa2.first->data.insert(Object(4));
oa2.first->data.insert(Object(5));
oa2.second = new AttributeSet;
oa2.second->data.insert(Attribute(2));
oa3.first = new ObjectSet;
oa3.first->data.insert(Object(2));
oa3.first->data.insert(Object(3));
oa3.first->data.insert(Object(6));
oa3.second = new AttributeSet;
oa3.second->data.insert(Attribute(4));
oa4.first = new ObjectSet;
oa4.first->data.insert(Object(2));
oa4.first->data.insert(Object(4));
oa4.first->data.insert(Object(5));
oa4.first->data.insert(Object(6));
oa4.second = new AttributeSet;
oa4.second->data.insert(Attribute(1));
oa4.second->data.insert(Attribute(6));
oa5.first = new ObjectSet;
oa5.first->data.insert(Object(1));
oa5.first->data.insert(Object(2));
oa5.first->data.insert(Object(4));
oa5.first->data.insert(Object(6));
oa5.second = new AttributeSet;
oa5.second->data.insert(Attribute(3));
oa6.first = new ObjectSet;
oa6.first->data.insert(Object(1));
oa6.first->data.insert(Object(3));
oa6.first->data.insert(Object(4));
oa6.first->data.insert(Object(5));
oa6.second = new AttributeSet;
oa6.second->data.insert(Attribute(5));
oa7.first = new ObjectSet;
oa7.first->data.insert(Object(2));
oa7.first->data.insert(Object(3));
oa7.first->data.insert(Object(4));
oa7.first->data.insert(Object(6));
oa7.second = new AttributeSet;
oa7.second->data.insert(Attribute(8));
FC->data.push_back(oa1);
FC->data.push_back(oa2);
FC->data.push_back(oa3);
FC->data.push_back(oa4);
FC->data.push_back(oa5);
FC->data.push_back(oa6);
FC->data.push_back(oa7);
//AttributeSet as1;
//AttributeSet as2;
//as1.data.insert(2);
//as2.data.insert(5);
//DeltaClosure dc;
//dc.push_back(as1);
//dc.push_back(as2);
unsigned int minSup = 2;
FormalContext *FC2 = OKLocalContextMinSup(oa, FC, minSup);
for (int i = 0; i < FC2->data.size(); ++i) {
for(std::set<Object>::iterator j = FC2->data[i].first->data.begin(); j != FC2->data[i].first->data.end(); ++j)
std::cout << *j;
std::cout << " : ";
for(std::set<Attribute>::iterator j = FC2->data[i].second->data.begin(); j != FC2->data[i].second->data.end(); ++j)
std::cout << *j;
std::cout << std::endl;
}
for (std::vector<OAPair>::iterator it = FC2->data.begin(); it != FC2->data.end(); ++it) {
delete it->first;
delete it->second;
}
delete FC2;
for (std::vector<OAPair>::iterator it = FC->data.begin(); it != FC->data.end(); ++it) {
delete it->first;
delete it->second;
}
delete FC;
delete oa.first;
delete oa.second;
_CrtDumpMemoryLeaks();
system("PAUSE");
return 0;
}
| 12l-edami-okkov | trunk/test/ok/OKLocalContextTest.cpp | C++ | gpl3 | 4,846 |
/**
* Test of Order function
*
* author: Marcin Wachulski
*
*/
#include "OKTest.h"
class OrderTest : public testing::Test {
};
TEST_F(OrderTest, order_empty_seq) {
FormalContext fc;
Order(fc);
EXPECT_EQ(0, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_one_unproc_elem) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(1, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_one_proc_elem) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 1;
Order(fc);
EXPECT_EQ(1, fc.data.size());
EXPECT_EQ(1, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_two_elems_swap) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 0;
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(2, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_two_elems_noswap) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 1;
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(2, fc.data.size());
EXPECT_EQ(1, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, big_order) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(103);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(104);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 4;
attrSet = new AttributeSet();
attrSet->data.insert(105);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(106);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(107);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(108);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
} | 12l-edami-okkov | trunk/test/ok/OrderTest.cpp | C++ | gpl3 | 4,530 |
/**
* Test function to check whether Formal Context is sorted properly
*
* author: Marcin Wachulski
*
*/
#include "OK.h"
bool is_sorted(const FormalContext &fc) {
if (fc.processedNo > 1)
for (std::vector<OAPair>::const_iterator i = fc.data.begin();
(i+1) != fc.data.begin() + fc.processedNo; i++)
if (i->first->data.size() > (i+1)->first->data.size())
return false;
if (fc.data.size() - fc.processedNo > 1)
for (std::vector<OAPair>::const_iterator i = fc.data.begin() + fc.processedNo;
(i+1) != fc.data.end(); i++)
if (i->first->data.size() > (i+1)->first->data.size())
return false;
return true;
} | 12l-edami-okkov | trunk/test/ok/SortCheck.cpp | C++ | gpl3 | 732 |
/**
* Test of Closure function
*
* author: Marcin Wachulski
*
*/
#include "OKTest.h"
// checks whether all elements in sub set are included within super set
bool subsumes(AttributeSet *sub, AttributeSet *super) {
for (std::set<Attribute>::iterator i = sub->data.begin();
i != sub->data.end(); i++)
if (super->data.find(*i) == super->data.end())
return false;
return true;
}
class ClosureTest : public testing::Test {
protected:
virtual void SetUp() {
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(104);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(103);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 4;
attrSet = new AttributeSet();
attrSet->data.insert(107);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(105);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(108);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(106);
attrSet->data.insert(116);
attrSet->data.insert(126);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
prefix.data.insert(0);
prefix.data.insert(2);
prefix.data.insert(4);
prefix.data.insert(6);
prefix.data.insert(8);
}
FormalContext fc;
AttributeSet prefix;
};
TEST_F(ClosureTest, no_processing) {
AttributeSet attrSet;
unsigned int attrs_num = attrSet.data.size();
ObjectSet objSet;
Closure(prefix, OAPair(&objSet, &attrSet), fc);
EXPECT_EQ(prefix.data.size() + attrs_num, attrSet.data.size());
subsumes(&prefix, &attrSet);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(ClosureTest, nonequal_support) {
AttributeSet attrSet;
attrSet.data.insert(1);
attrSet.data.insert(2);
attrSet.data.insert(3);
unsigned int attrs_num = attrSet.data.size();
ObjectSet objSet;
Closure(prefix, OAPair(&objSet, &attrSet), fc);
EXPECT_EQ(7, attrSet.data.size());
subsumes(&prefix, &attrSet);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(ClosureTest, full_processing) {
AttributeSet attrSet;
attrSet.data.insert(1);
attrSet.data.insert(2);
attrSet.data.insert(3);
attrSet.data.insert(4);
attrSet.data.insert(5);
attrSet.data.insert(1001);
unsigned int attrs_num = attrSet.data.size();
ObjectSet objSet;
objSet.data.insert(3);
objSet.data.insert(4);
objSet.data.insert(5);
objSet.data.insert(6);
AttributeSet last_attrSet_inFC = *(fc.data.back().second);
Closure(prefix, OAPair(&objSet, &attrSet), fc);
EXPECT_EQ(12, attrSet.data.size());
subsumes(&prefix, &attrSet);
subsumes(&last_attrSet_inFC, &attrSet);
EXPECT_EQ(7, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
| 12l-edami-okkov | trunk/test/ok/ClosureTest.cpp | C++ | gpl3 | 4,541 |
/**
* Local context function testing
*
* author: Maciej Rubikowski
*/
#include "KOV.h"
#include <iostream>
int main(int argc, char *argv[]) {
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
{
FormalContext *FC = new FormalContext;
OAPair oa1;
OAPair oa2;
OAPair oa3;
OAPair oa4;
OAPair oa5;
OAPair oa6;
OAPair oa7;
OAPair oa;
/*
oa.first = new ObjectSet;
oa.first->data.insert(2);
oa.first->data.insert(3);
oa.first->data.insert(6);
oa.second = new AttributeSet;
oa.second->data.insert(Attribute(4));
oa1.first = new ObjectSet;
oa1.first->data.insert(Object(2));
oa1.first->data.insert(Object(4));
oa1.first->data.insert(Object(5));
oa1.first->data.insert(Object(6));
oa1.second = new AttributeSet;
oa1.second->data.insert(Attribute(1));
oa1.second->data.insert(Attribute(6));
oa2.first = new ObjectSet;
oa2.first->data.insert(Object(1));
oa2.first->data.insert(Object(2));
oa2.first->data.insert(Object(4));
oa2.first->data.insert(Object(6));
oa2.second = new AttributeSet;
oa2.second->data.insert(Attribute(3));
oa3.first = new ObjectSet;
oa3.first->data.insert(Object(1));
oa3.first->data.insert(Object(3));
oa3.first->data.insert(Object(4));
oa3.first->data.insert(Object(5));
oa3.second = new AttributeSet;
oa3.second->data.insert(Attribute(5));
oa4.first = new ObjectSet;
oa4.first->data.insert(Object(2));
oa4.first->data.insert(Object(3));
oa4.first->data.insert(Object(4));
oa4.first->data.insert(Object(6));
oa4.second = new AttributeSet;
oa4.second->data.insert(Attribute(8));
FC->data.push_back(oa1);
FC->data.push_back(oa2);
FC->data.push_back(oa3);
FC->data.push_back(oa4);
//commence local context w/o minSup and deltaClosure test
FormalContext *FC2 = LocalContext(oa, FC);//new FormalContext();
*/
oa.first = new ObjectSet;
oa.first->data.insert(1);
oa.first->data.insert(4);
oa.first->data.insert(5);
oa.second = new AttributeSet;
oa.second->data.insert(Attribute(2));
oa1.first = new ObjectSet;
oa1.first->data.insert(Object(4));
oa1.second = new AttributeSet;
oa1.second->data.insert(Attribute(7));
oa2.first = new ObjectSet;
oa2.first->data.insert(Object(1));
oa2.first->data.insert(Object(4));
oa2.first->data.insert(Object(5));
oa2.second = new AttributeSet;
oa2.second->data.insert(Attribute(2));
oa3.first = new ObjectSet;
oa3.first->data.insert(Object(2));
oa3.first->data.insert(Object(3));
oa3.first->data.insert(Object(6));
oa3.second = new AttributeSet;
oa3.second->data.insert(Attribute(4));
oa4.first = new ObjectSet;
oa4.first->data.insert(Object(2));
oa4.first->data.insert(Object(4));
oa4.first->data.insert(Object(5));
oa4.first->data.insert(Object(6));
oa4.second = new AttributeSet;
oa4.second->data.insert(Attribute(1));
oa4.second->data.insert(Attribute(6));
oa5.first = new ObjectSet;
oa5.first->data.insert(Object(1));
oa5.first->data.insert(Object(2));
oa5.first->data.insert(Object(4));
oa5.first->data.insert(Object(6));
oa5.second = new AttributeSet;
oa5.second->data.insert(Attribute(3));
oa6.first = new ObjectSet;
oa6.first->data.insert(Object(1));
oa6.first->data.insert(Object(3));
oa6.first->data.insert(Object(4));
oa6.first->data.insert(Object(5));
oa6.second = new AttributeSet;
oa6.second->data.insert(Attribute(5));
oa7.first = new ObjectSet;
oa7.first->data.insert(Object(2));
oa7.first->data.insert(Object(3));
oa7.first->data.insert(Object(4));
oa7.first->data.insert(Object(6));
oa7.second = new AttributeSet;
oa7.second->data.insert(Attribute(8));
FC->data.push_back(oa1);
FC->data.push_back(oa2);
FC->data.push_back(oa3);
FC->data.push_back(oa4);
FC->data.push_back(oa5);
FC->data.push_back(oa6);
FC->data.push_back(oa7);
AttributeSet as1;
AttributeSet as2;
as1.data.insert(2);
as2.data.insert(5);
DeltaClosure dc;
dc.push_back(as1);
dc.push_back(as2);
unsigned int minSup = 2;
FormalContext *FC2 = LocalContextMinSup(oa, dc, FC, minSup);
for (int i = 0; i < FC2->data.size(); ++i) {
for(std::set<Object>::iterator j = FC2->data[i].first->data.begin(); j != FC2->data[i].first->data.end(); ++j)
std::cout << *j;
std::cout << " : ";
for(std::set<Attribute>::iterator j = FC2->data[i].second->data.begin(); j != FC2->data[i].second->data.end(); ++j)
std::cout << *j;
std::cout << std::endl;
}
for (std::vector<OAPair>::iterator it = FC2->data.begin(); it != FC2->data.end(); ++it) {
delete it->first;
delete it->second;
}
delete FC2;
for (std::vector<OAPair>::iterator it = FC->data.begin(); it != FC->data.end(); ++it) {
delete it->first;
delete it->second;
}
delete FC;
delete oa.first;
delete oa.second;
}
_CrtDumpMemoryLeaks();
system("PAUSE");
return 0;
} | 12l-edami-okkov | trunk/test/kov/KOVLocalContextTest.cpp | C++ | gpl3 | 5,113 |
/**
* Test of Order function
*
* author: Marcin Wachulski
*
*/
#include "KOVTest.h"
class OrderTest : public testing::Test {
};
TEST_F(OrderTest, order_empty_seq) {
FormalContext fc;
Order(fc);
EXPECT_EQ(0, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_one_unproc_elem) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(1, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_one_proc_elem) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 1;
Order(fc);
EXPECT_EQ(1, fc.data.size());
EXPECT_EQ(1, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_two_elems_swap) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 0;
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(2, fc.data.size());
EXPECT_EQ(0, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, order_two_elems_noswap) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 1;
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(2, fc.data.size());
EXPECT_EQ(1, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
}
TEST_F(OrderTest, big_order) {
FormalContext fc;
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(101);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(102);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(103);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(104);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 4;
attrSet = new AttributeSet();
attrSet->data.insert(105);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(106);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
objSet->data.insert(4);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(107);
objSet = new ObjectSet();
objSet->data.insert(1);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(108);
objSet = new ObjectSet();
objSet->data.insert(1);
objSet->data.insert(2);
objSet->data.insert(3);
fc.data.push_back(OAPair(objSet, attrSet));
Order(fc);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
} | 12l-edami-okkov | trunk/test/kov/OrderTest.cpp | C++ | gpl3 | 4,531 |
/**
* Test function to check whether Formal Context is sorted properly
*
* author: Marcin Wachulski
*
*/
#include "KOV.h"
bool is_sorted(const FormalContext &fc) {
if (fc.data.size() < 2)
return true;
for (std::vector<OAPair>::const_iterator i = fc.data.begin();
(i+1) != fc.data.end(); i++)
if (i->first->data.size() > (i+1)->first->data.size())
return false;
return true;
} | 12l-edami-okkov | trunk/test/kov/SortCheck.cpp | C++ | gpl3 | 445 |
/**
* KOV test header
*
* author: Marcin Wachulski
*
*/
#include "KOV.h"
#include "gtest\gtest.h"
bool is_sorted(const FormalContext &fc); | 12l-edami-okkov | trunk/test/kov/KOVTest.h | C | gpl3 | 153 |
/**
* Test of Closure function
*
* author: Marcin Wachulski
*
*/
#include "KOVTest.h"
// checks whether all elements in sub set are included within super set
bool subsumes(AttributeSet *sub, AttributeSet *super) {
for (std::set<Attribute>::iterator i = sub->data.begin();
i != sub->data.end(); i++)
if (super->data.find(*i) == super->data.end())
return false;
return true;
}
class ClosureTest : public testing::Test {
protected:
virtual void SetUp() {
AttributeSet *attrSet;
ObjectSet *objSet;
attrSet = new AttributeSet();
attrSet->data.insert(1);
objSet = new ObjectSet();
for (int i = 1; i <= 1; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(2);
objSet = new ObjectSet();
for (int i = 1; i <= 2; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(3);
objSet = new ObjectSet();
for (int i = 1; i <= 3; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(4);
objSet = new ObjectSet();
for (int i = 1; i <= 4; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
fc.processedNo = 4;
attrSet = new AttributeSet();
attrSet->data.insert(5);
objSet = new ObjectSet();
for (int i = 1; i <= 5; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(6);
objSet = new ObjectSet();
for (int i = 1; i <= 6; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(7);
objSet = new ObjectSet();
for (int i = 1; i <= 7; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
attrSet = new AttributeSet();
attrSet->data.insert(6);
attrSet->data.insert(7);
attrSet->data.insert(9);
objSet = new ObjectSet();
for (int i = 1; i <= 8; i++)
objSet->data.insert(i);
fc.data.push_back(OAPair(objSet, attrSet));
for (int i = 1; i <= 15; i++)
all_attributes.data.insert(i);
}
FormalContext fc;
AttributeSet all_attributes;
};
TEST_F(ClosureTest, empty_FC) {
FormalContext empty_fc;
AttributeSet *attrSet = new AttributeSet();
ObjectSet *objSet = new ObjectSet();
ClosureForEmptySet(all_attributes, OAPair(objSet, attrSet), empty_fc);
EXPECT_EQ(15, attrSet->data.size());
subsumes(&all_attributes, attrSet);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
delete attrSet;
delete objSet;
}
TEST_F(ClosureTest, nonequal_support) {
AttributeSet *attrSet = new AttributeSet();
attrSet->data.insert(1);
attrSet->data.insert(2);
attrSet->data.insert(3);
ObjectSet *objSet = new ObjectSet();
ClosureForEmptySet(all_attributes, OAPair(objSet, attrSet), fc);
EXPECT_EQ(7, attrSet->data.size());
AttributeSet diff_attributes;
diff_attributes.data.insert(8);
for (int i = 10; i <= 15; i++)
diff_attributes.data.insert(i);
subsumes(&diff_attributes, attrSet);
EXPECT_EQ(8, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
delete attrSet;
delete objSet;
}
TEST_F(ClosureTest, full_processing) {
AttributeSet *attrSet = new AttributeSet();
attrSet->data.insert(1);
attrSet->data.insert(2);
attrSet->data.insert(3);
attrSet->data.insert(4);
attrSet->data.insert(5);
attrSet->data.insert(1001);
ObjectSet *objSet = new ObjectSet();
objSet->data.insert(3);
objSet->data.insert(4);
objSet->data.insert(5);
objSet->data.insert(6);
objSet->data.insert(7);
objSet->data.insert(8);
objSet->data.insert(9);
objSet->data.insert(10);
AttributeSet last_attrSet_inFC = *(fc.data.back().second);
OAPair oa(objSet, attrSet);
ClosureForEmptySet(all_attributes, oa, fc);
EXPECT_EQ(8, oa.second->data.size());
AttributeSet diff_attributes;
diff_attributes.data.insert(8);
for (int i = 8; i <= 15; i++)
diff_attributes.data.insert(i);
subsumes(&diff_attributes, oa.second);
subsumes(&last_attrSet_inFC, oa.second);
EXPECT_EQ(7, fc.data.size());
EXPECT_EQ(4, fc.processedNo);
EXPECT_TRUE(is_sorted(fc));
delete oa.first;
delete oa.second;
}
| 12l-edami-okkov | trunk/test/kov/ClosureTest.cpp | C++ | gpl3 | 5,028 |
/**
* Test collector and executor
*
* author: Marcin Wachulski
*
*/
#include "gtest\gtest.h"
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 12l-edami-okkov | trunk/ok.test/GTest.cpp | C++ | gpl3 | 223 |
/**
* Test of DataSetLoader class
*
* author: Marcin Wachulski
*
*/
#include "DataStructure.h"
#include "DataSetLoader.h"
#include "gtest\gtest.h"
#include <iostream>
class DataSetLoader : public testing::Test {
public:
};
TEST_F(DataSetLoader, a) {
DataStructure *data = loadDataSet("../datasets/a.dat");
EXPECT_EQ(8, data->getAllAtributes()->data.size());
EXPECT_EQ(6, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, chess) {
DataStructure *data = loadDataSet("../datasets/chess.dat");
EXPECT_EQ(75, data->getAllAtributes()->data.size());
EXPECT_EQ(3196, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, mushroom) {
DataStructure *data = loadDataSet("../datasets/mushroom.dat");
EXPECT_EQ(119, data->getAllAtributes()->data.size());
EXPECT_EQ(8124, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, T10I4D100K) {
DataStructure *data = loadDataSet("../datasets/T10I4D100K.dat");
EXPECT_EQ(870, data->getAllAtributes()->data.size());
EXPECT_EQ(100000, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, connect) {
DataStructure *data = loadDataSet("../datasets/connect.dat");
EXPECT_EQ(129, data->getAllAtributes()->data.size());
EXPECT_EQ(67557, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, pumsb_star) {
DataStructure *data = loadDataSet("../datasets/pumsb_star.dat");
EXPECT_EQ(2088, data->getAllAtributes()->data.size());
EXPECT_EQ(49046, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, T40I10D100K) {
DataStructure *data = loadDataSet("../datasets/T40I10D100K.dat");
EXPECT_EQ(942, data->getAllAtributes()->data.size());
EXPECT_EQ(100000, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
TEST_F(DataSetLoader, pubsb) {
DataStructure *data = loadDataSet("../datasets/pumsb.dat");
EXPECT_EQ(2113, data->getAllAtributes()->data.size());
EXPECT_EQ(49046, data->getAllObjects()->data.size());
data->printSummary(std::cout);
delete data;
}
| 12l-edami-okkov | trunk/dataload.test/DataSetLoaderTest.cpp | C++ | gpl3 | 2,466 |
/**
* Test collector and executor
*
* author: Marcin Wachulski
*
*/
#include "gtest\gtest.h"
int main(int argc, char *argv[])
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 12l-edami-okkov | trunk/dataload.test/GTest.cpp | C++ | gpl3 | 223 |
#ifndef _OBJECT_SET_H_
#define _OBJECT_SET_H_
#include "Object.h"
#include <set>
// set of objects
class ObjectSet {
public:
~ObjectSet() {};
std::set<Object> data;
};
#endif | 12l-edami-okkov | trunk/common/ObjectSet.h | C++ | gpl3 | 197 |
/**
* Implementation of file data loader
*
* author: Marcin Wachulski
*
*/
#include "DataSetLoader.h"
DataStructure* loadDataSet(const char* filepath) {
if (filepath == NULL || filepath == "")
throw std::exception("Unspecified file path");
std::ifstream input;
input.open(filepath, std::ifstream::in);
if (!input.good())
throw std::exception("Input file corrupted");
DataStructure *result = new DataStructure();
char nextChar = input.peek();
int currAttr = 0, currObj = 1;
AttributeSet *currAttrSet = new AttributeSet();
while (input.good()) {
input >> currAttr;
currAttrSet->data.insert(currAttr);
result->updateAttribute(currAttr, currObj);
// new Object (Transaction or Line) recognized
nextChar = input.peek();
while (nextChar == ' ' || nextChar == '\t') {
input.get();
nextChar = input.peek();
}
if (nextChar == '\n' || input.eof()) {
result->addObject(currObj, currAttrSet);
currObj++;
currAttrSet = new AttributeSet();
nextChar = input.peek();
while (input.good() &&
nextChar == ' ' || nextChar == '\t' || nextChar == '\n') {
input.get();
nextChar = input.peek();
}
}
}
delete currAttrSet;
return result;
} | 12l-edami-okkov | trunk/common/DataSetLoader.cpp | C++ | gpl3 | 1,461 |
#ifndef _ATTRIBUTE_H_
#define _ATTRIBUTE_H_
// attribute representation
typedef unsigned int Attribute;
#endif | 12l-edami-okkov | trunk/common/Attribute.h | C | gpl3 | 118 |
#ifndef _OBJECT_H_
#define _OBJECT_H_
// object representation
typedef unsigned int Object;
#endif | 12l-edami-okkov | trunk/common/Object.h | C | gpl3 | 106 |
/**
* Implementation of main data structure
*
* author: Marcin Wachulski
*
*/
#include "DataStructure.h"
DataStructure::DataStructure() {
this->_allAttrs = new AttributeSet();
this->_allObjs = new ObjectSet();
}
DataStructure::~DataStructure() {
// cleaning attributes with object references
for (std::map<Attribute, ObjectSet*>::iterator i = this->_attrs.begin();
i != this->_attrs.end(); i++)
delete i->second;
// cleaning objects with attribute references
for (std::vector<AttributeSet*>::iterator i = this->_objs.begin();
i != this->_objs.end(); i++)
delete *i;
// cleaning the full sets
delete this->_allAttrs;
delete this->_allObjs;
}
void DataStructure::updateAttribute(const Attribute &attr, const Object &obj) {
ObjectSet * &objSet = this->_attrs[attr];
if (objSet == NULL)
objSet = new ObjectSet();
objSet->data.insert(obj);
// update complete AllAttributes set
this->_allAttrs->data.insert(attr);
}
// object is not used since object vector is assumend to be a completed list of
// objects (a sequence of integers) ordered asc - performance optimization
void DataStructure::addObject(const Object &obj, AttributeSet *aSet) {
this->_objs.push_back(aSet);
this->_allObjs->data.insert(obj);
}
// summarize the structure
void DataStructure::printSummary(std::ostream &out) {
// basic properties
out << "Total attributes: " << this->getAllAtributes()->data.size() << std::endl;
out << "Total objects: " << this->getAllObjects()->data.size() << std::endl;
// counting relation elements
int r_elem = 0;
for (std::vector<AttributeSet*>::const_iterator i = this->_objs.begin();
i != this->_objs.end(); i++)
r_elem += (*i)->data.size();
out << "Total relation elements: " << r_elem;
} | 12l-edami-okkov | trunk/common/DataStructure.cpp | C++ | gpl3 | 1,897 |
/**
* Implementation of OAPair universal comparator function
*
* author: Marcin Wachulski
*
*/
#include "OAPair.h"
// universal comparator w.r.t |O| that is the support of an attribute
bool OAPairCompare(const OAPair& e1, const OAPair& e2) {
return e1.first->data.size() < e2.first->data.size(); } | 12l-edami-okkov | trunk/common/OAPair.cpp | C++ | gpl3 | 318 |
#ifndef _DATA_SET_LOADER_H_
#define _DATA_SET_LOADER_H_
#include "DataStructure.h"
#include <istream>
#include <fstream>
// reads an external dataset file, creates and builds up a new data structure
DataStructure* loadDataSet(const char* filepath);
#endif | 12l-edami-okkov | trunk/common/DataSetLoader.h | C++ | gpl3 | 268 |
#ifndef _FORMAL_CONTEXT_H_
#define _FORMAL_CONTEXT_H_
#include "OAPair.h"
#include <vector>
// local formal context
class FormalContext {
public:
FormalContext() : processedNo(0) {}
FormalContext(const FormalContext &);
~FormalContext();
unsigned int processedNo;
std::vector<OAPair> data;
};
#endif | 12l-edami-okkov | trunk/common/FormalContext.h | C++ | gpl3 | 335 |
#ifndef _DATA_STRUCTURE_H_
#define _DATA_STRUCTURE_H_
#include "Attribute.h"
#include "AttributeSet.h"
#include "Object.h"
#include "ObjectSet.h"
#include <vector>
#include <map>
#include <ostream>
// main storage structure
class DataStructure {
public:
DataStructure();
~DataStructure();
// adds an object to set of objects that are the support of attribute attr
void updateAttribute(const Attribute &attr, const Object &obj);
// adds a new object with a complete set of attributes it contains
void addObject(const Object &obj, AttributeSet *aSet);
// returns a set of attributes that are supported by the given object
AttributeSet* getAttributes(const Object &obj) { return _objs[obj-1]; }
// returns a set of objects that support the given attribute
ObjectSet* getObjects(const Attribute &attr) { return _attrs[attr]; }
// returns the set of all attributes
AttributeSet* getAllAtributes() { return this->_allAttrs; }
// returns the set of all objects
ObjectSet* getAllObjects() { return this->_allObjs; }
// prints a brief summary to the out stream
void printSummary(std::ostream &out);
private:
std::map<Attribute, ObjectSet*> _attrs;
std::vector<AttributeSet*> _objs;
AttributeSet* _allAttrs;
ObjectSet* _allObjs;
};
#endif | 12l-edami-okkov | trunk/common/DataStructure.h | C++ | gpl3 | 1,348 |
#ifndef _ATTRIBUTE_SET_H_
#define _ATTRIBUTE_SET_H_
#include "Attribute.h"
#include <set>
// set of attributes
class AttributeSet{
public:
AttributeSet(){
this->processed = false;
this->data.clear();
}
AttributeSet(const AttributeSet &other){
this->processed = other.processed;
for(std::set<Attribute>::const_iterator i = other.data.begin(); i != other.data.end(); i++)
this->data.insert(Attribute(*i));
}
~AttributeSet(){};
std::set<Attribute> data;
bool processed;
bool operator==(const AttributeSet &other) const{
if(this->data.size() != other.data.size())
return false;
for(std::set<Attribute>::const_iterator a = this->data.begin(); a != this->data.end(); a++){
bool attributeFound = false;
for(std::set<Attribute>::const_iterator b = other.data.begin(); b != other.data.end(); b++){
if(*b == *a){
attributeFound = true;
break;
}
}
if(attributeFound == false)
return false;
}
return true;
}
bool operator!=(const AttributeSet &other) const{
return !(*this == other);
}
};
#endif | 12l-edami-okkov | trunk/common/AttributeSet.h | C++ | gpl3 | 1,106 |
#ifndef _OA_PAIR_H_
#define _OA_PAIR_H_
#include "AttributeSet.h"
#include "ObjectSet.h"
// ObjectSet and AttributeSet pair concise representation
typedef std::pair<ObjectSet*, AttributeSet*> OAPair;
// standard comparator
bool OAPairCompare(const OAPair& e1, const OAPair& e2);
#endif | 12l-edami-okkov | trunk/common/OAPair.h | C++ | gpl3 | 301 |
#ifndef _KOV_H_
#define _KOV_H_
// declaration of structures used in KOV algorithm implementation
#include "..\common\Attribute.h"
#include "..\common\AttributeSet.h"
#include "..\common\Object.h"
#include "..\common\ObjectSet.h"
#include "..\common\OAPair.h"
#include "..\common\FormalContext.h"
#include "..\common\DataStructure.h"
#include "..\common\DataSetLoader.h"
#include <time.h>
#include <iostream>
#include <fstream>
typedef std:: vector<AttributeSet> DeltaClosure;
// central data structure maintaining data loaded from external data source and
// reference pointers to speed up search operations
extern DataStructure data;
// special version of Closure for empty sets
void ClosureForEmptySet(const AttributeSet &all_attrs, OAPair &oa_pair, FormalContext &local_fc);
// closure computes a closure of OAPair element in local formal context
// represented by local_fc object
void Closure(const AttributeSet &all_attrs, OAPair &oa_pair, FormalContext &local_fc);
// sort_f is a sort function that compares two OAPair elements and returns true
// iff e1 is less or equal than e2, false conversely
void Order(FormalContext &local_fc, bool (*sort_f)(const OAPair &e1, const OAPair &e2) = NULL);
// determine local context for the first iteration of KOV algorithm, i.e.
// w/o considering the minimal support
FormalContext* LocalContext(const OAPair &oa, const FormalContext * const P);
// determine local context for the next iterations of KOV algorithm (KOV-Extend), i.e.
// considering the minimal support and the delta closure
FormalContext* LocalContextMinSup(const OAPair &oa, DeltaClosure deltaClosure, const FormalContext * const P, unsigned int minSup);
void SaveOA(std::ofstream *fc, OAPair &oa, bool asChar);
void PrintOA(OAPair &oa);
void Kov(DataStructure *ds, std::ofstream *fc, unsigned int minSup, unsigned int* counter, bool asChar, bool (*sort_f)(const OAPair &e1, const OAPair &e2) = NULL);
void KovExtend(AttributeSet *allAttributes, FormalContext &p, unsigned int minSup, std::ofstream *fc, AttributeSet* processedSets, unsigned int* counter, bool asChar, bool (*sort_f)(const OAPair &e1, const OAPair &e2) = NULL);
DeltaClosure ClosureDelta(const OAPair &pair, const FormalContext *p);
#endif | 12l-edami-okkov | trunk/kov/KOV.h | C++ | gpl3 | 2,266 |
/**
* Implementation of Closure function
*
* author: Marcin Wachulski
*
*/
#include "KOV.h"
#include <set>
#include <algorithm>
#include <iterator>
void ClosureForEmptySet(const AttributeSet &all_attrs, OAPair &oa_pair, FormalContext &local_fc) {
if (local_fc.data.size() > 0) {
OAPair &fc_last_p = local_fc.data.back();
if (fc_last_p.first->data.size() == oa_pair.first->data.size()) {
local_fc.data.pop_back();
delete fc_last_p.first;
delete fc_last_p.second;
}
}
Closure(all_attrs, oa_pair, local_fc);
}
void Closure(const AttributeSet &all_attrs, OAPair &oa_pair, FormalContext &local_fc) {
AttributeSet *all_FC_attrs = new AttributeSet();
for (std::vector<OAPair>::const_iterator i = local_fc.data.begin();
i != local_fc.data.end(); i++)
all_FC_attrs->data.insert(i->second->data.begin(), i->second->data.end());
// if oa_pair sets are stored in dynamic memory - the following line should be executed
delete oa_pair.second;
oa_pair.second = new AttributeSet(all_attrs);
for (std::set<Attribute>::const_iterator i = all_FC_attrs->data.begin();
i != all_FC_attrs->data.end(); i++)
oa_pair.second->data.erase(*i);
delete all_FC_attrs;
} | 12l-edami-okkov | trunk/kov/Closure.cpp | C++ | gpl3 | 1,316 |
#include "kov.h"
int main(int argc, char *argv[])
{
_CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT );
try {
DataStructure* data = loadDataSet(argv[1]);
data->printSummary(std::cout);
std::ofstream fc(argv[2]);
clock_t start = clock();
unsigned int* counter = new unsigned int(0);
Kov(data,&fc,atoi(argv[3]), counter, strcmp(argv[4],"c")==0);
clock_t end = clock();
std::cout<<"\nTime:"<<(end-start)/1000;
std::cout<<"\nSets:"<<*counter<<"\n";
fc << "\n" << (end-start)/1000<<"\nSets:"<<*counter;
delete counter;
fc.close();
delete data;
}
catch (std::exception e) {
e.what();
}
_CrtDumpMemoryLeaks();
system("PAUSE");
return 0;
}
void Kov(DataStructure *ds, std::ofstream *fc, unsigned int minSup,unsigned int* counter, bool asChar, bool (*sort_f)(const OAPair &e1, const OAPair &e2)){
if(ds->getAllObjects()->data.size() >= minSup){
OAPair oa = std::make_pair( new ObjectSet(*(ds->getAllObjects())), new AttributeSet());
FormalContext *tmpFC = new FormalContext();
for (std::set<Attribute>::const_iterator i = ds->getAllAtributes()->data.begin(); i != ds->getAllAtributes()->data.end(); i++){
if(ds->getObjects(*i)->data.size() >=minSup){
oa.second->data.insert(Attribute(*i));
OAPair tmpPair = std::make_pair( new ObjectSet(*( ds->getObjects(*i) )) , new AttributeSet());
tmpPair.second->data.insert(Attribute(*i));
tmpFC->data.push_back(tmpPair);
}
}
FormalContext* localP = LocalContext(oa, tmpFC);
for (std::vector<OAPair>::iterator i = tmpFC->data.begin(); i != tmpFC->data.end(); i++) {
delete i->first;
delete i->second;
}
delete tmpFC;
ClosureForEmptySet(*(ds->getAllAtributes()),oa,*localP);
SaveOA(fc,oa, asChar);
++(*counter);
AttributeSet* processedSets = new AttributeSet();
KovExtend(ds->getAllAtributes(), *localP, minSup, fc, processedSets,counter,asChar);
delete processedSets;
for (std::vector<OAPair>::iterator i = localP->data.begin(); i != localP->data.end(); i++) {
delete i->first;
delete i->second;
}
delete localP;
delete oa.first;
delete oa.second;
}
}
void PrintOA(OAPair &oa){
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
std::cout<< "\nO:{ ";
for (std::set<Object>::const_iterator i = O->data.begin(); i != O->data.end(); i++){
std::cout<< *i << " ";
}
std::cout << "}, A:{ ";
for (std::set<Attribute>::const_iterator i = A->data.begin(); i != A->data.end(); i++){
std::cout<< *i << " ";
}
std::cout<< "}";
}
void SaveOA(std::ofstream *fc, OAPair &oa, bool asChar){
//PrintOA(oa);
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
(*fc) << "<{";
for (std::set<Object>::const_iterator i = O->data.begin(); i != O->data.end(); i++)
(*fc) << *i << " ";
(*fc) << "}>, <{";
for (std::set<Attribute>::const_iterator i = A->data.begin(); i != A->data.end(); i++)
if(asChar){
char c = 'a' -1 + (*i);
(*fc) << c;
}
else
(*fc) << *i << " ";
(*fc) << "}>\n";
}
bool AttributeSetProcessed(const AttributeSet& set, const AttributeSet* sets){
for(std::set<Attribute>::const_iterator attr = set.data.begin(); attr != set.data.end(); ++attr)
for(std::set<Attribute>::const_iterator attr2 = sets->data.begin(); attr2 != sets->data.end(); ++attr2)
if(*attr == *attr2)
return true;
return false;
}
void KovExtend(AttributeSet *allAttributes, FormalContext &p, unsigned int minSup, std::ofstream *fc, AttributeSet *processedSets,unsigned int* counter, bool asChar, bool (*sort_f)(const OAPair &e1, const OAPair &e2)){
Order(p);
for (unsigned int i = 0; i < p.data.size(); i++){
OAPair pair = std::make_pair(new ObjectSet(*(p.data.at(i).first)), new AttributeSet(*p.data.at(i).second));
if(!AttributeSetProcessed(*(p.data.at(i).second), processedSets)){
DeltaClosure deltaClosure = ClosureDelta(p.data.at(i), &p);
bool processed = false;
for (DeltaClosure::const_iterator d = deltaClosure.begin(); d != deltaClosure.end(); d++){
if(AttributeSetProcessed((*d), processedSets)){
processed = true;
break;
}
}
if(processed){
for(std::set<Attribute>::const_iterator attr = p.data.at(i).second->data.begin(); attr != p.data.at(i).second->data.end(); ++attr)
processedSets->data.insert(Attribute(*attr));
}else{
FormalContext* localP = LocalContextMinSup(pair, deltaClosure, &p, minSup);
Order(*localP);
Closure(*allAttributes, pair, *localP);
for(std::set<Attribute>::const_iterator attr = p.data.at(i).second->data.begin(); attr != p.data.at(i).second->data.end(); ++attr)
processedSets->data.insert(Attribute(*attr));
SaveOA(fc,pair, asChar);
++(*counter);
AttributeSet* sets = new AttributeSet(*processedSets);
KovExtend(allAttributes, *localP, minSup, fc, sets, counter,asChar);
delete sets;
for (std::vector<OAPair>::iterator i = localP->data.begin(); i != localP->data.end(); i++) {
delete i->first;
delete i->second;
}
delete localP;
}
}
delete pair.first;
delete pair.second;
}
}
DeltaClosure ClosureDelta(const OAPair &oa, const FormalContext *p){
std::vector<OAPair> deltaClosure;
bool copy = false;
for(std::vector<OAPair>::const_iterator i = p->data.begin(); i!=p->data.end(); i++){
if(copy == false && i->first == oa.first && i->second == oa.second)
copy = true;
if(copy == true){
OAPair pair = std::make_pair(i->first, i->second);
deltaClosure.push_back(pair);
}
}
for(std::set<Object>::const_iterator o = oa.first->data.begin(); o != oa.first->data.end(); o++){
for(std::vector<OAPair>::const_iterator i = deltaClosure.begin(); i != deltaClosure.end();){
bool containsObject = false;
for(std::set<Object>::const_iterator oi = i->first->data.begin(); oi != i->first->data.end(); ++oi){
if(*oi == *o){
containsObject = true;
break;
}
}
if(containsObject == false){
i = deltaClosure.erase(i);
}
else
++i;
}
}
DeltaClosure result;
for(std::vector<OAPair>::const_iterator i = deltaClosure.begin(); i != deltaClosure.end();++i){
AttributeSet set = AttributeSet(*(i->second));
result.push_back(set);
}
return result;
}
| 12l-edami-okkov | trunk/kov/KOV.cpp | C++ | gpl3 | 6,433 |
/**
* Functions responsible for determining the local context for the KOV algorithm.
*
* author: Maciej Rubikowski
*/
#include "kov.h"
#include <time.h>
#include <Windows.h>
typedef std::pair<ObjectSet, FormalContext*> ObjectContextPair;
typedef std::vector<ObjectContextPair> LocalContextGrouping;
FormalContext* LocalContext(const OAPair &oa, const FormalContext * const P) {
FormalContext *FC = new FormalContext;
LocalContextGrouping G;
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
ObjectContextPair ocp = std::pair<ObjectSet, FormalContext*>(ObjectSet(), new FormalContext(*P));
G.push_back(ocp);
for (std::set<Object>::const_iterator o = O->data.begin(); o != O->data.end(); ++o) {
LocalContextGrouping set_S;
ObjectSet *Z = NULL;
FormalContext *E = NULL;
for (std::vector<ObjectContextPair>::iterator j = G.begin(); j != G.end();) {
Z = &j->first;
E = j->second;
ObjectSet os = *Z;
os.data.insert(*o);
ObjectContextPair S = std::pair<ObjectSet, FormalContext*>(os, new FormalContext);
for (std::vector<OAPair>::iterator YB = E->data.begin(); YB != E->data.end(); ) {
// remove all y from Y such that y precedes o
// and BTW check if o belongs to Y
ObjectSet *Y = YB->first;
AttributeSet *B = YB->second;
bool oInY = false;
for (std::set<Object>::iterator y = Y->data.begin(); y != Y->data.end(); ) {
if (*y < *o)
y = Y->data.erase(y);
else if (*y == *o) {
oInY = true;
break;
} else {
++y;
}
}
// if object o belongs to Y...
if (oInY) {
Y->data.erase(*o); // remove o from Y
S.second->data.push_back(*YB);
YB = E->data.erase(YB); // remove (Y, B) from E
} else
++YB;
}
// if the second element of S is different from null_set then
if (!S.second->data.empty()) {
set_S.push_back(S);
if (E->data.empty()) {
j = G.erase(j); //delete E
delete E;
} else {
++j;
}
} else {
delete S.second;
++j;
}
}
G.insert(G.end(), set_S.begin(), set_S.end());
}
// prepare P<O, A>
for (LocalContextGrouping::iterator it = G.begin(); it != G.end();) {
if (it->second->data.empty()) {
++it;
continue;
}
ObjectSet *Z = new ObjectSet(it->first);
AttributeSet *D = new AttributeSet;
for (std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2)
D->data.insert(it2->second->data.begin(), it2->second->data.end());
D->processed = false;
FC->data.push_back(OAPair(Z, D));
++it;
}
// clean up
for(LocalContextGrouping::iterator it = G.begin(); it != G.end(); ++it) {
for(std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
delete it2->first;
delete it2->second;
}
delete it->second;
}
return FC;
}
FormalContext* LocalContextMinSup(const OAPair &oa, DeltaClosure deltaClosure, const FormalContext * const P, unsigned int minSup) {
LocalContextGrouping G;
FormalContext *FC = new FormalContext;
ObjectSet *O = oa.first;
AttributeSet *A = oa.second;
FormalContext *FC2 = new FormalContext;
// prepare the initial grouping wrt DeltaClosure
for (std::vector<OAPair>::const_iterator it = P->data.begin(); it != P->data.end(); ++it) {
bool found = false;
for (std::vector<AttributeSet>::iterator it2 = deltaClosure.begin(); it2 != deltaClosure.end(); ++it2) {
if (*it2 == *(it->second)) {
found = true;
break;
}
}
if (found)
continue;
else {
OAPair oap = OAPair(new ObjectSet(*it->first), new AttributeSet(*it->second));
FC2->data.push_back(oap);
}
}
ObjectContextPair ocp = std::pair<ObjectSet, FormalContext*>(ObjectSet(), FC2);
G.push_back(ocp);
for (std::set<Object>::const_iterator o = O->data.begin(); o != O->data.end(); ++o) {
LocalContextGrouping set_S;
ObjectSet *Z = NULL;
FormalContext *E = NULL;
for (std::vector<ObjectContextPair>::iterator j = G.begin(); j != G.end();) {
Z = &j->first;
E = j->second;
ObjectSet os = *Z;
os.data.insert(*o);
ObjectContextPair S = std::make_pair<ObjectSet, FormalContext*>(os, new FormalContext);
for (std::vector<OAPair>::iterator YB = E->data.begin(); YB != E->data.end();) {
// remove all y from Y such that y precedes o
// and BTW check if o belongs to Y
ObjectSet *Y = YB->first;
AttributeSet *B = YB->second;
bool oInY = false;
for (std::set<Object>::iterator y = YB->first->data.begin(); y != YB->first->data.end();) {
if (*y < *o)
y = Y->data.erase(y);
else if (*y == *o) {
oInY = true;
break;
} else {
++y;
}
}
// if object o belongs to Y...
if (oInY) {
Y->data.erase(*o); // remove o from Y
S.second->data.push_back(*YB);
YB = E->data.erase(YB); // remove (Y, B) from E
} else
++YB;
}
// if the second element of S is different from null_set then
if (!S.second->data.empty()) {
set_S.push_back(S);
if (E->data.empty()) {
j = G.erase(j);
delete E;
} else {
++j;
}
} else {
delete S.second;
++j;
}
}
G.insert(G.end(), set_S.begin(), set_S.end());
}
// prepare InfrAttrSet
AttributeSet *ias = new AttributeSet();
for (LocalContextGrouping::iterator it = G.begin(); it != G.end();++it) {
if (it->first.data.size() < minSup)
for (std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
ias->data.insert(it2->second->data.begin(), it2->second->data.end());
}
}
if (!ias->data.empty()) {
ias->processed = true;
FC->data.push_back(OAPair(new ObjectSet, ias));
} else {
delete ias;
}
bool isProcessed = false;
// prepare P<O, A>
for (LocalContextGrouping::iterator it = G.begin(); it != G.end();) {
if (it->second->data.empty() || it->first.data.size() < minSup) {
++it;
continue;
}
ObjectSet *Z = new ObjectSet(it->first);
AttributeSet *D = new AttributeSet;
for (std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2)
D->data.insert(it2->second->data.begin(), it2->second->data.end());
D->processed = false;
FC->data.push_back(OAPair(Z, D));
++it;
}
// clean up
for(LocalContextGrouping::iterator it = G.begin(); it != G.end(); ++it) {
for(std::vector<OAPair>::iterator it2 = it->second->data.begin(); it2 != it->second->data.end(); ++it2) {
delete it2->first;
delete it2->second;
}
delete it->second;
}
return FC;
} | 12l-edami-okkov | trunk/kov/KOVLocalContext.cpp | C++ | gpl3 | 6,721 |
/**
* Implementation of Order function
*
* author: Marcin Wachulski
*
*/
#include "KOV.h"
#include <algorithm>
void Order(FormalContext &local_fc, bool (*sort_f)(const OAPair &e1, const OAPair &e2)) {
if (local_fc.data.size() < 2)
return;
std::sort(local_fc.data.begin(), local_fc.data.end(), OAPairCompare);
} | 12l-edami-okkov | trunk/kov/Order.cpp | C++ | gpl3 | 345 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace _1041448_DH_Utilities
{
public class Files
{
public static string ReadFile(string fName, out bool isReadSuccess){
isReadSuccess = false;
string source = string.Empty;
if (fName == string.Empty){
isReadSuccess = true;
return string.Empty;
}
FileInfo mFile = new FileInfo(fName);
if (!mFile.Exists)
{
isReadSuccess = true;
return string.Empty;
}
FileStream fStream = mFile.Open(FileMode.Open, FileAccess.Read);
StreamReader sStream = new StreamReader(fStream);
while (!sStream.EndOfStream)
{
source += sStream.ReadLine();
}
sStream.Close();
fStream.Close();
return source;
}
public static bool SaveFile(string fName, string source){
bool result = true;
return result;
}
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_DH_Utilities/Files.cs | C# | asf20 | 1,191 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace _1041448_DH_Utilities
{
public class MString
{
public static int GetFrequenceSpaceByCharacter(string source){
// Find one or multi space in source
return Regex.Matches(source, "\\s+").Count;
}
public static string CleanSpaceBySource(string source){
return Regex.Replace(source, "\\s{3,}", " ");
}
public static int CountCharacterByString (string source){
return source.Length;
}
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_DH_Utilities/MString.cs | C# | asf20 | 656 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1041448_DH_Utilities")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("1041448_DH_Utilities")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b2ddcc59-e87e-44cf-a54e-50be4d575b5b")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_DH_Utilities/Properties/AssemblyInfo.cs | C# | asf20 | 1,470 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Resources;
namespace _1041448_DH_Utilities
{
public class MResources
{
#region ReadResourceFile
/// <summary>
/// method for reading a value from a resource file
/// (.resx file)
/// </summary>
/// <param name="file">file to read from</param>
/// <param name="key">key to get the value for</param>
/// <returns>a string value</returns>
public static string ReadResourceValue(string file, string key, out bool error)
{
error = false;
//value for our return value
string resourceValue = string.Empty;
try
{
// specify your resource file name
string resourceFile = file;
// get the path of your file
string filePath = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
// create a resource manager for reading from
//the resx file
ResourceManager resourceManager = ResourceManager.CreateFileBasedResourceManager(resourceFile, filePath, null);
// retrieve the value of the specified key
resourceValue = resourceManager.GetString(key);
}
catch (Exception ex)
{
error = true;
resourceValue = ex.Message;
}
return resourceValue;
}
#endregion
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_DH_Utilities/MResources.cs | C# | asf20 | 1,597 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using _1041448_DH_Utilities;
namespace _1041448_Watermarks
{
public class Spaces : Watermark
{
public static bool PreprocessSource(ref string sources, string watermark, ref int maxbit, out string error){
// Init state variables
error = string.Empty;
int totalSpace = 0;
int maxInputBit = 0;
int numCharacterInWatermark = 0;
bool result = false;
bool isError = false;
string sourceTemp = sources;
string watermarkTemp = watermark;
// Check if sources and watermark params is null
if (sources == null || sources.Equals("") || watermark == null || watermark.Equals("")){
//error = MResources.ReadResourceValue("Global.resx", "Spaces_PreprocessSource_Params_Error", out isError);
error = "Params failed";
return result;
}
sourceTemp = MString.CleanSpaceBySource(sourceTemp);
// Count space in source
totalSpace = MString.GetFrequenceSpaceByCharacter(sourceTemp);
// Check if count lease than 2
if (totalSpace <= Constants.MINBIT){
//error = MResources.ReadResourceValue("Global.resx", "Spaces_PreprocessSource_MinBit_Error", out isError);
error = "Not enough space";
return result;
}
// max input bit = count divide 2
maxInputBit = totalSpace / 2;
// Count nums character in watermark
numCharacterInWatermark = MString.CountCharacterByString(watermarkTemp);
// If nums more max input bit
if (numCharacterInWatermark > maxInputBit)
{
//error = MResources.ReadResourceValue("Global.resx", "Spaces_PreprocessSource_BitOverfloat_Error", out isError);
error = "Bit over float";
return result;
}
// Assign maxbit var = max input bit
maxbit = maxInputBit;
sources = sourceTemp;
result = true;
// End state
sourceTemp = string.Empty;
watermarkTemp = string.Empty;
return result;
}
public static string PreprocessWatermark(string watermark){
return watermark;
}
public static bool InputWatermark(ref string sources, string watermark){
return false;
}
public static string PreprocessOutputSource(string source){
return string.Empty;
}
public static string GetWaterwark(string source, out bool isGetWatermark, out string messages){
isGetWatermark = false;
messages = string.Empty;
return string.Empty;
}
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Watermarks/Spaces.cs | C# | asf20 | 3,006 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1041448_Watermarks
{
public abstract class Watermark
{
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Watermarks/Watermark.cs | C# | asf20 | 183 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1041448_Watermarks
{
static class Constants
{
public const int MINBIT = 2;
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Watermarks/Constants.cs | C# | asf20 | 212 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1041448_Watermarks")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("1041448_Watermarks")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5c3f9e9c-3b1b-49b4-882d-f6b0e1e01a13")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Watermarks/Properties/AssemblyInfo.cs | C# | asf20 | 1,466 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace _1041448_Week01
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Week01/Program.cs | C# | asf20 | 507 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("1041448_Week01")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("1041448_Week01")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9b834ca5-f279-445b-9ae0-84e8b8deec8d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Week01/Properties/AssemblyInfo.cs | C# | asf20 | 1,458 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using _1041448_DH_Utilities;
namespace _1041448_Week01
{
public partial class Form1 : Form
{
private string fName = string.Empty;
private string outName = string.Empty;
public Form1()
{
InitializeComponent();
}
private void InputProccessButton_Click(object sender, EventArgs e)
{
if (fName.Equals("")) { MessagesInputProcessLabel.Text = "Please choose file"; return; }
int maxBit = 0;
string error = string.Empty;
string resouce = string.Empty;
bool isReadSuccess;
// Find any word, that contain spaces
string source = _1041448_DH_Utilities.Files.ReadFile(fName, out isReadSuccess);
if (isReadSuccess) { MessagesInputProcessLabel.Text = "Read file failed"; return; }
string watermark = this.InputWatermarkTextbox.Text;
if (!_1041448_Watermarks.Spaces.PreprocessSource(ref source, watermark, ref maxBit, out error))
{
MessagesInputProcessLabel.Text = error;
return;
}
MaxBitLabel.Text = maxBit.ToString();
watermark = _1041448_Watermarks.Spaces.PreprocessWatermark(watermark);
_1041448_Watermarks.Spaces.InputWatermark(ref source, watermark);
if (!_1041448_DH_Utilities.Files.SaveFile(fName, source)) { MessagesInputProcessLabel.Text = "Save file failed !"; return; }
MessagesInputProcessLabel.Text = "Save file successfully ";
}
private void BrowseInputFileButton_Click(object sender, EventArgs e)
{
DialogResult rs = openFileDialog1.ShowDialog();
if (rs == DialogResult.OK)
{
fName = openFileDialog1.FileName;
MessagesInputProcessLabel.Text = "Process input watermark ...";
}
else if (rs == DialogResult.Cancel)
{
MessagesInputProcessLabel.Text = "Waiting";
}
}
private void BrowseOutputFileButton_Click(object sender, EventArgs e)
{
DialogResult rs = openFileDialog2.ShowDialog();
if (rs == DialogResult.OK)
{
outName = openFileDialog2.FileName;
MessagesInputProcessLabel.Text = "Process get watermark ...";
}
else if (rs == DialogResult.Cancel)
{
MessagesOutputProcessLabel.Text = "Waiting";
}
}
private void OutputProcessButton_Click(object sender, EventArgs e)
{
if (outName.Equals("")) { MessagesOutputProcessLabel.Text = "Please choose file"; return; }
bool isReadSuccess = false;
bool isGetWatermark = false;
string watermark = string.Empty;
string messages = string.Empty;
// Read file
// Find any word, that contain spaces
string source = _1041448_DH_Utilities.Files.ReadFile(outName, out isReadSuccess);
// Preprocess source
source = _1041448_Watermarks.Spaces.PreprocessOutputSource(source);
watermark = _1041448_Watermarks.Spaces.GetWaterwark(source, out isGetWatermark, out messages);
OutputWatermarkTextBox.Text = watermark;
}
}
}
| 1041448-datahiding-daily-practices | trunk/Week01/1041448_Week01/1041448_Week01/Form1.cs | C# | asf20 | 3,708 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.CancelableCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.Toast;
/**
* This shows how to change the camera position for the map.
*/
public class CameraDemoActivity extends android.support.v4.app.FragmentActivity {
/**
* The amount by which to scroll the camera. Note that this amount is in raw pixels, not dp
* (density-independent pixels).
*/
private static final int SCROLL_BY_PX = 100;
static final CameraPosition BONDI =
new CameraPosition.Builder().target(new LatLng(-33.891614, 151.276417))
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
static final CameraPosition SYDNEY =
new CameraPosition.Builder().target(new LatLng(-33.87365, 151.20689))
.zoom(15.5f)
.bearing(0)
.tilt(25)
.build();
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_demo);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// We will provide our own zoom controls.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Show Sydney
mMap.moveCamera(
CameraUpdateFactory.newLatLngZoom(new LatLng(-33.87365, 151.20689), 10));
}
/**
* When the map is not ready the CameraUpdateFactory cannot be used. This should be called on
* all entry points that call methods on the Google Maps API.
*/
private boolean checkReady() {
if (mMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/**
* Called when the Go To Bondi button is clicked.
*/
public void onGoToBondi(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.newCameraPosition(BONDI));
}
/**
* Called when the Animate To Sydney button is clicked.
*/
public void onGoToSydney(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.newCameraPosition(SYDNEY), new CancelableCallback() {
@Override
public void onFinish() {
Toast.makeText(getBaseContext(), "Animation to Sydney complete", Toast.LENGTH_SHORT)
.show();
}
@Override
public void onCancel() {
Toast.makeText(getBaseContext(), "Animation to Sydney canceled", Toast.LENGTH_SHORT)
.show();
}
});
}
/**
* Called when the stop button is clicked.
*/
public void onStopAnimation(View view) {
if (!checkReady()) {
return;
}
mMap.stopAnimation();
}
/**
* Called when the zoom in button (the one with the +) is clicked.
*/
public void onZoomIn(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.zoomIn());
}
/**
* Called when the zoom out button (the one with the -) is clicked.
*/
public void onZoomOut(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.zoomOut());
}
/**
* Called when the left arrow button is clicked. This causes the camera to move to the left
*/
public void onScrollLeft(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.scrollBy(-SCROLL_BY_PX, 0));
}
/**
* Called when the right arrow button is clicked. This causes the camera to move to the right.
*/
public void onScrollRight(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.scrollBy(SCROLL_BY_PX, 0));
}
/**
* Called when the up arrow button is clicked. The causes the camera to move up.
*/
public void onScrollUp(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.scrollBy(0, -SCROLL_BY_PX));
}
/**
* Called when the down arrow button is clicked. This causes the camera to move down.
*/
public void onScrollDown(View view) {
if (!checkReady()) {
return;
}
changeCamera(CameraUpdateFactory.scrollBy(0, SCROLL_BY_PX));
}
private void changeCamera(CameraUpdate update) {
changeCamera(update, null);
}
/**
* Change the camera position by moving or animating the camera depending on the state of the
* animate toggle button.
*/
private void changeCamera(CameraUpdate update, CancelableCallback callback) {
boolean animated = ((CompoundButton) findViewById(R.id.animate)).isChecked();
if (animated) {
mMap.animateCamera(update, callback);
} else {
mMap.moveCamera(update);
}
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/CameraDemoActivity.java | Java | asf20 | 6,650 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.UiSettings;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
/**
* This shows how UI settings can be toggled.
*/
public class UiSettingsDemoActivity extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
private UiSettings mUiSettings;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ui_settings_demo);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMyLocationEnabled(true);
mUiSettings = mMap.getUiSettings();
}
/**
* Checks if the map is ready (which depends on whether the Google Play services APK is
* available. This should be called prior to calling any methods on GoogleMap.
*/
private boolean checkReady() {
if (mMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
public void setZoomButtonsEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables the zoom controls (+/- buttons in the bottom right of the map).
mUiSettings.setZoomControlsEnabled(((CheckBox) v).isChecked());
}
public void setCompassEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables the compass (icon in the top left that indicates the orientation of the
// map).
mUiSettings.setCompassEnabled(((CheckBox) v).isChecked());
}
public void setMyLocationButtonEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables the my location button (this DOES NOT enable/disable the my location
// dot/chevron on the map). The my location button will never appear if the my location
// layer is not enabled.
mUiSettings.setMyLocationButtonEnabled(((CheckBox) v).isChecked());
}
public void setMyLocationLayerEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables the my location layer (i.e., the dot/chevron on the map). If enabled, it
// will also cause the my location button to show (if it is enabled); if disabled, the my
// location button will never show.
mMap.setMyLocationEnabled(((CheckBox) v).isChecked());
}
public void setScrollGesturesEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables scroll gestures (i.e. panning the map).
mUiSettings.setScrollGesturesEnabled(((CheckBox) v).isChecked());
}
public void setZoomGesturesEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables zoom gestures (i.e., double tap, pinch & stretch).
mUiSettings.setZoomGesturesEnabled(((CheckBox) v).isChecked());
}
public void setTiltGesturesEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables tilt gestures.
mUiSettings.setTiltGesturesEnabled(((CheckBox) v).isChecked());
}
public void setRotateGesturesEnabled(View v) {
if (!checkReady()) {
return;
}
// Enables/disables rotate gestures.
mUiSettings.setRotateGesturesEnabled(((CheckBox) v).isChecked());
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/UiSettingsDemoActivity.java | Java | asf20 | 4,862 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import android.os.Bundle;
/**
* This shows how to create a simple activity with multiple maps on screen.
*/
public class MultiMapDemoActivity extends android.support.v4.app.FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multimap_demo);
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/MultiMapDemoActivity.java | Java | asf20 | 1,017 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
/**
* Demonstrates how to instantiate a SupportMapFragment programmatically and add a marker to it.
*/
public class ProgrammaticDemoActivity extends android.support.v4.app.FragmentActivity {
private static final String MAP_FRAGMENT_TAG = "map";
private GoogleMap mMap;
private SupportMapFragment mMapFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// It isn't possible to set a fragment's id programmatically so we set a tag instead and
// search for it using that.
mMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentByTag(MAP_FRAGMENT_TAG);
// We only create a fragment if it doesn't already exist.
if (mMapFragment == null) {
// To programmatically add the map, we first create a SupportMapFragment.
mMapFragment = SupportMapFragment.newInstance();
// Then we add it using a FragmentTransaction.
FragmentTransaction fragmentTransaction = getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.add(android.R.id.content, mMapFragment, MAP_FRAGMENT_TAG);
fragmentTransaction.commit();
}
// We can't be guaranteed that the map is available because Google Play services might
// not be available.
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
// In case Google Play services has since become available.
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = mMapFragment.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/ProgrammaticDemoActivity.java | Java | asf20 | 3,091 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo.view;
import android.content.Context;
import android.view.LayoutInflater;
import android.widget.FrameLayout;
import android.widget.TextView;
import com.example.mapdemo.R;
/**
* A widget that describes an activity that demonstrates a feature.
*/
public final class FeatureView extends FrameLayout {
/**
* Constructs a feature view by inflating layout/feature.xml.
*/
public FeatureView(Context context) {
super(context);
LayoutInflater layoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layoutInflater.inflate(R.layout.feature, this);
}
/**
* Set the resource id of the title of the demo.
*
* @param titleId the resource id of the title of the demo
*/
public synchronized void setTitleId(int titleId) {
((TextView) (findViewById(R.id.title))).setText(titleId);
}
/**
* Set the resource id of the description of the demo.
*
* @param descriptionId the resource id of the description of the demo
*/
public synchronized void setDescriptionId(int descriptionId) {
((TextView) (findViewById(R.id.description))).setText(descriptionId);
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/view/FeatureView.java | Java | asf20 | 1,875 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.UrlTileProvider;
import android.os.Bundle;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Locale;
/**
* This demonstrates how to add a tile overlay to a map.
*/
public class TileOverlayDemoActivity extends android.support.v4.app.FragmentActivity {
/** This returns moon tiles. */
private static final String MOON_MAP_URL_FORMAT =
"http://mw1.google.com/mw-planetary/lunar/lunarmaps_v1/clem_bw/%d/%d/%d.jpg";
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setMapType(GoogleMap.MAP_TYPE_NONE);
TileProvider tileProvider = new UrlTileProvider(256, 256) {
@Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, MOON_MAP_URL_FORMAT, zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMap.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/TileOverlayDemoActivity.java | Java | asf20 | 3,037 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
/**
* This shows how to create a simple activity with a raw MapView and add a marker to it. This
* requires forwarding all the important lifecycle methods onto MapView.
*/
public class RawMapViewDemoActivity extends android.support.v4.app.FragmentActivity {
private MapView mMapView;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.raw_mapview_demo);
mMapView = (MapView) findViewById(R.id.map);
mMapView.onCreate(savedInstanceState);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
mMapView.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((MapView) findViewById(R.id.map)).getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
@Override
protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override
protected void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mMapView.onSaveInstanceState(outState);
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/RawMapViewDemoActivity.java | Java | asf20 | 2,480 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import android.os.Bundle;
/**
* An activity that creates a map with some initial options.
*
* @author hearnden@google.com (David Hearnden)
*/
public final class OptionsDemoActivity extends android.support.v4.app.FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_demo);
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/OptionsDemoActivity.java | Java | asf20 | 1,044 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.InfoWindowAdapter;
import com.google.android.gms.maps.GoogleMap.OnInfoWindowClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
/**
* This shows how to place markers on a map.
*/
public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
implements OnMarkerClickListener, OnInfoWindowClickListener, OnMarkerDragListener {
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
/** Demonstrates customizing the info window and/or its contents. */
class CustomInfoWindowAdapter implements InfoWindowAdapter {
private final RadioGroup mOptions;
// These a both viewgroups containing an ImageView with id "badge" and two TextViews with id
// "title" and "snippet".
private final View mWindow;
private final View mContents;
CustomInfoWindowAdapter() {
mWindow = getLayoutInflater().inflate(R.layout.custom_info_window, null);
mContents = getLayoutInflater().inflate(R.layout.custom_info_contents, null);
mOptions = (RadioGroup) findViewById(R.id.custom_info_window_options);
}
@Override
public View getInfoWindow(Marker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_window) {
// This means that getInfoContents will be called.
return null;
}
render(marker, mWindow);
return mWindow;
}
@Override
public View getInfoContents(Marker marker) {
if (mOptions.getCheckedRadioButtonId() != R.id.custom_info_contents) {
// This means that the default info contents will be used.
return null;
}
render(marker, mContents);
return mContents;
}
private void render(Marker marker, View view) {
int badge;
// Use the equals() method on a Marker to check for equals. Do not use ==.
if (marker.equals(mBrisbane)) {
badge = R.drawable.badge_qld;
} else if (marker.equals(mAdelaide)) {
badge = R.drawable.badge_sa;
} else if (marker.equals(mSydney)) {
badge = R.drawable.badge_nsw;
} else if (marker.equals(mMelbourne)) {
badge = R.drawable.badge_victoria;
} else if (marker.equals(mPerth)) {
badge = R.drawable.badge_wa;
} else {
// Passing 0 to setImageResource will clear the image view.
badge = 0;
}
((ImageView) view.findViewById(R.id.badge)).setImageResource(badge);
String title = marker.getTitle();
TextView titleUi = ((TextView) view.findViewById(R.id.title));
if (title != null) {
// Spannable string allows us to edit the formatting of the text.
SpannableString titleText = new SpannableString(title);
titleText.setSpan(new ForegroundColorSpan(Color.RED), 0, titleText.length(), 0);
titleUi.setText(titleText);
} else {
titleUi.setText("");
}
String snippet = marker.getSnippet();
TextView snippetUi = ((TextView) view.findViewById(R.id.snippet));
if (snippet != null) {
SpannableString snippetText = new SpannableString(snippet);
snippetText.setSpan(new ForegroundColorSpan(Color.MAGENTA), 0, 10, 0);
snippetText.setSpan(new ForegroundColorSpan(Color.BLUE), 12, 21, 0);
snippetUi.setText(snippetText);
} else {
snippetUi.setText("");
}
}
}
private GoogleMap mMap;
private Marker mPerth;
private Marker mSydney;
private Marker mBrisbane;
private Marker mAdelaide;
private Marker mMelbourne;
private TextView mTopText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.marker_demo);
mTopText = (TextView) findViewById(R.id.top_text);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Hide the zoom controls as the button panel will cover it.
mMap.getUiSettings().setZoomControlsEnabled(false);
// Add lots of markers to the map.
addMarkersToMap();
// Setting an info window adapter allows us to change the both the contents and look of the
// info window.
mMap.setInfoWindowAdapter(new CustomInfoWindowAdapter());
// Set listeners for marker events. See the bottom of this class for their behavior.
mMap.setOnMarkerClickListener(this);
mMap.setOnInfoWindowClickListener(this);
mMap.setOnMarkerDragListener(this);
// Pan to see all markers in view.
// Cannot zoom to bounds until the map has a size.
final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
if (mapView.getViewTreeObserver().isAlive()) {
mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressLint("NewApi") // We check which build version we are using.
@Override
public void onGlobalLayout() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(PERTH)
.include(SYDNEY)
.include(ADELAIDE)
.include(BRISBANE)
.include(MELBOURNE)
.build();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
}
});
}
}
private void addMarkersToMap() {
// Uses a colored icon.
mBrisbane = mMap.addMarker(new MarkerOptions()
.position(BRISBANE)
.title("Brisbane")
.snippet("Population: 2,074,200")
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
// Uses a custom icon.
mSydney = mMap.addMarker(new MarkerOptions()
.position(SYDNEY)
.title("Sydney")
.snippet("Population: 4,627,300")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow)));
// Creates a draggable marker. Long press to drag.
mMelbourne = mMap.addMarker(new MarkerOptions()
.position(MELBOURNE)
.title("Melbourne")
.snippet("Population: 4,137,400")
.draggable(true));
// A few more markers for good measure.
mPerth = mMap.addMarker(new MarkerOptions()
.position(PERTH)
.title("Perth")
.snippet("Population: 1,738,800"));
mAdelaide = mMap.addMarker(new MarkerOptions()
.position(ADELAIDE)
.title("Adelaide")
.snippet("Population: 1,213,000"));
// Creates a marker rainbow demonstrating how to create default marker icons of different
// hues (colors).
int numMarkersInRainbow = 12;
for (int i = 0; i < numMarkersInRainbow; i++) {
mMap.addMarker(new MarkerOptions()
.position(new LatLng(
-30 + 10 * Math.sin(i * Math.PI / (numMarkersInRainbow - 1)),
135 - 10 * Math.cos(i * Math.PI / (numMarkersInRainbow - 1))))
.title("Marker " + i)
.icon(BitmapDescriptorFactory.defaultMarker(i * 360 / numMarkersInRainbow)));
}
}
private boolean checkReady() {
if (mMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/** Called when the Clear button is clicked. */
public void onClearMap(View view) {
if (!checkReady()) {
return;
}
mMap.clear();
}
/** Called when the Reset button is clicked. */
public void onResetMap(View view) {
if (!checkReady()) {
return;
}
// Clear the map because we don't want duplicates of the markers.
mMap.clear();
addMarkersToMap();
}
//
// Marker related listeners.
//
@Override
public boolean onMarkerClick(final Marker marker) {
// This causes the marker at Perth to bounce into position when it is clicked.
if (marker.equals(mPerth)) {
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(PERTH);
startPoint.offset(0, -100);
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
final long duration = 1500;
final Interpolator interpolator = new BounceInterpolator();
handler.post(new Runnable() {
@Override
public void run() {
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float) elapsed / duration);
double lng = t * PERTH.longitude + (1 - t) * startLatLng.longitude;
double lat = t * PERTH.latitude + (1 - t) * startLatLng.latitude;
marker.setPosition(new LatLng(lat, lng));
if (t < 1.0) {
// Post again 16ms later.
handler.postDelayed(this, 16);
}
}
});
}
// We return false to indicate that we have not consumed the event and that we wish
// for the default behavior to occur (which is for the camera to move such that the
// marker is centered and for the marker's info window to open, if it has one).
return false;
}
@Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(getBaseContext(), "Click Info Window", Toast.LENGTH_SHORT).show();
}
@Override
public void onMarkerDragStart(Marker marker) {
mTopText.setText("onMarkerDragStart");
}
@Override
public void onMarkerDragEnd(Marker marker) {
mTopText.setText("onMarkerDragEnd");
}
@Override
public void onMarkerDrag(Marker marker) {
mTopText.setText("onMarkerDrag. Current Position: " + marker.getPosition());
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/MarkerDemoActivity.java | Java | asf20 | 13,828 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
/**
* This shows how to retain a map across activity restarts (e.g., from screen rotations), which can
* be faster than relying on state serialization.
*/
public class RetainMapActivity extends android.support.v4.app.FragmentActivity {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
if (savedInstanceState == null) {
// First incarnation of this activity.
mapFragment.setRetainInstance(true);
} else {
// Reincarnated activity. The obtained map is the same map instance in the previous
// activity life cycle. There is no need to reinitialize it.
mMap = mapFragment.getMap();
}
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/RetainMapActivity.java | Java | asf20 | 2,383 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import java.util.Arrays;
import java.util.List;
/**
* This shows how to draw polygons on a map.
*/
public class PolygonDemoActivity extends android.support.v4.app.FragmentActivity
implements OnSeekBarChangeListener {
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final int WIDTH_MAX = 50;
private static final int HUE_MAX = 360;
private static final int ALPHA_MAX = 255;
private GoogleMap mMap;
private Polygon mMutablePolygon;
private SeekBar mColorBar;
private SeekBar mAlphaBar;
private SeekBar mWidthBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.polygon_demo);
mColorBar = (SeekBar) findViewById(R.id.hueSeekBar);
mColorBar.setMax(HUE_MAX);
mColorBar.setProgress(0);
mAlphaBar = (SeekBar) findViewById(R.id.alphaSeekBar);
mAlphaBar.setMax(ALPHA_MAX);
mAlphaBar.setProgress(127);
mWidthBar = (SeekBar) findViewById(R.id.widthSeekBar);
mWidthBar.setMax(WIDTH_MAX);
mWidthBar.setProgress(10);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Create a rectangle with two rectangular holes.
mMap.addPolygon(new PolygonOptions()
.addAll(createRectangle(new LatLng(-20, 130), 5, 5))
.addHole(createRectangle(new LatLng(-22, 128), 1, 1))
.addHole(createRectangle(new LatLng(-18, 133), 0.5, 1.5))
.fillColor(Color.CYAN)
.strokeColor(Color.BLUE)
.strokeWidth(5));
// Create an ellipse centered at Sydney.
PolygonOptions options = new PolygonOptions();
int numPoints = 400;
float semiHorizontalAxis = 10f;
float semiVerticalAxis = 5f;
double phase = 2 * Math.PI / numPoints;
for (int i = 0; i <= numPoints; i++) {
options.add(new LatLng(SYDNEY.latitude + semiVerticalAxis * Math.sin(i * phase),
SYDNEY.longitude + semiHorizontalAxis * Math.cos(i * phase)));
}
int fillColor = Color.HSVToColor(
mAlphaBar.getProgress(), new float[] {mColorBar.getProgress(), 1, 1});
mMutablePolygon = mMap.addPolygon(options
.strokeWidth(mWidthBar.getProgress())
.strokeColor(Color.BLACK)
.fillColor(fillColor));
mColorBar.setOnSeekBarChangeListener(this);
mAlphaBar.setOnSeekBarChangeListener(this);
mWidthBar.setOnSeekBarChangeListener(this);
// Move the map so that it is centered on the mutable polygon.
mMap.moveCamera(CameraUpdateFactory.newLatLng(SYDNEY));
}
/**
* Creates a List of LatLngs that form a rectangle with the given dimensions.
*/
private List<LatLng> createRectangle(LatLng center, double halfWidth, double halfHeight) {
// Note that the ordering of the points is counterclockwise (as long as the halfWidth and
// halfHeight are less than 90).
return Arrays.asList(new LatLng(center.latitude - halfHeight, center.longitude - halfWidth),
new LatLng(center.latitude - halfHeight, center.longitude + halfWidth),
new LatLng(center.latitude + halfHeight, center.longitude + halfWidth),
new LatLng(center.latitude + halfHeight, center.longitude - halfWidth),
new LatLng(center.latitude - halfHeight, center.longitude - halfWidth));
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMutablePolygon == null) {
return;
}
if (seekBar == mColorBar) {
mMutablePolygon.setFillColor(Color.HSVToColor(
Color.alpha(mMutablePolygon.getFillColor()), new float[] {progress, 1, 1}));
} else if (seekBar == mAlphaBar) {
int prevColor = mMutablePolygon.getFillColor();
mMutablePolygon.setFillColor(Color.argb(
progress, Color.red(prevColor), Color.green(prevColor),
Color.blue(prevColor)));
} else if (seekBar == mWidthBar) {
mMutablePolygon.setStrokeWidth(progress);
}
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/PolygonDemoActivity.java | Java | asf20 | 6,257 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import android.os.Bundle;
import android.widget.TextView;
/**
* This shows how to listen to some {@link GoogleMap} events.
*/
public class EventsDemoActivity extends android.support.v4.app.FragmentActivity
implements OnMapClickListener, OnMapLongClickListener, OnCameraChangeListener {
private GoogleMap mMap;
private TextView mTapTextView;
private TextView mCameraTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events_demo);
mTapTextView = (TextView) findViewById(R.id.tap_text);
mCameraTextView = (TextView) findViewById(R.id.camera_text);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setOnMapClickListener(this);
mMap.setOnMapLongClickListener(this);
mMap.setOnCameraChangeListener(this);
}
@Override
public void onMapClick(LatLng point) {
mTapTextView.setText("tapped, point=" + point);
}
@Override
public void onMapLongClick(LatLng point) {
mTapTextView.setText("long pressed, point=" + point);
}
@Override
public void onCameraChange(final CameraPosition position) {
mCameraTextView.setText(position.toString());
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/EventsDemoActivity.java | Java | asf20 | 2,745 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.LocationSource;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
/**
* This shows how to use a custom location source.
*/
public class LocationSourceDemoActivity extends android.support.v4.app.FragmentActivity {
/**
* A {@link LocationSource} which reports a new location whenever a user long presses the map at
* the point at which a user long pressed the map.
*/
private static class LongPressLocationSource implements LocationSource, OnMapLongClickListener {
private OnLocationChangedListener mListener;
/**
* Flag to keep track of the activity's lifecycle. This is not strictly necessary in this
* case because onMapLongPress events don't occur while the activity containing the map is
* paused but is included to demonstrate best practices (e.g., if a background service were
* to be used).
*/
private boolean mPaused;
@Override
public void activate(OnLocationChangedListener listener) {
mListener = listener;
}
@Override
public void deactivate() {
mListener = null;
}
@Override
public void onMapLongClick(LatLng point) {
if (mListener != null && !mPaused) {
Location location = new Location("LongPressLocationProvider");
location.setLatitude(point.latitude);
location.setLongitude(point.longitude);
location.setAccuracy(100);
mListener.onLocationChanged(location);
}
}
public void onPause() {
mPaused = true;
}
public void onResume() {
mPaused = false;
}
}
private LongPressLocationSource mLocationSource;
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
mLocationSource = new LongPressLocationSource();
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
mLocationSource.onResume();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.setLocationSource(mLocationSource);
mMap.setOnMapLongClickListener(mLocationSource);
mMap.setMyLocationEnabled(true);
}
@Override
protected void onPause() {
super.onPause();
mLocationSource.onPause();
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/LocationSourceDemoActivity.java | Java | asf20 | 3,930 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_HYBRID;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_NORMAL;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_SATELLITE;
import static com.google.android.gms.maps.GoogleMap.MAP_TYPE_TERRAIN;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.Toast;
/**
* Demonstrates the different base layers of a map.
*/
public class LayersDemoActivity extends android.support.v4.app.FragmentActivity
implements OnItemSelectedListener {
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layers_demo);
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
Spinner spinner = (Spinner) findViewById(R.id.layers_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.layers_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
}
}
private boolean checkReady() {
if (mMap == null) {
Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
return false;
}
return true;
}
/**
* Called when the Traffic checkbox is clicked.
*/
public void onTrafficToggled(View view) {
if (!checkReady()) {
return;
}
mMap.setTrafficEnabled(((CheckBox) view).isChecked());
}
/**
* Called when the MyLocation checkbox is clicked.
*/
public void onMyLocationToggled(View view) {
if (!checkReady()) {
return;
}
mMap.setMyLocationEnabled(((CheckBox) view).isChecked());
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (!checkReady()) {
return;
}
Log.i("LDA", "item selected at position " + position + " with string "
+ (String) parent.getItemAtPosition(position));
setLayer((String) parent.getItemAtPosition(position));
}
private void setLayer(String layerName) {
if (layerName.equals(getString(R.string.normal))) {
mMap.setMapType(MAP_TYPE_NORMAL);
} else if (layerName.equals(getString(R.string.hybrid))) {
mMap.setMapType(MAP_TYPE_HYBRID);
} else if (layerName.equals(getString(R.string.satellite))) {
mMap.setMapType(MAP_TYPE_SATELLITE);
} else if (layerName.equals(getString(R.string.terrain))) {
mMap.setMapType(MAP_TYPE_TERRAIN);
} else {
Log.i("LDA", "Error setting layer with name " + layerName);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/LayersDemoActivity.java | Java | asf20 | 4,381 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* This shows how to draw polylines on a map.
*/
public class PolylineDemoActivity extends android.support.v4.app.FragmentActivity
implements OnSeekBarChangeListener {
private static final LatLng MELBOURNE = new LatLng(-37.81319, 144.96298);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng ADELAIDE = new LatLng(-34.92873, 138.59995);
private static final LatLng PERTH = new LatLng(-31.95285, 115.85734);
private static final LatLng LHR = new LatLng(51.471547, -0.460052);
private static final LatLng LAX = new LatLng(33.936524, -118.377686);
private static final LatLng JFK = new LatLng(40.641051, -73.777485);
private static final LatLng AKL = new LatLng(-37.006254, 174.783018);
private static final int WIDTH_MAX = 50;
private static final int HUE_MAX = 360;
private static final int ALPHA_MAX = 255;
private GoogleMap mMap;
private Polyline mMutablePolyline;
private SeekBar mColorBar;
private SeekBar mAlphaBar;
private SeekBar mWidthBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.polyline_demo);
mColorBar = (SeekBar) findViewById(R.id.hueSeekBar);
mColorBar.setMax(HUE_MAX);
mColorBar.setProgress(0);
mAlphaBar = (SeekBar) findViewById(R.id.alphaSeekBar);
mAlphaBar.setMax(ALPHA_MAX);
mAlphaBar.setProgress(255);
mWidthBar = (SeekBar) findViewById(R.id.widthSeekBar);
mWidthBar.setMax(WIDTH_MAX);
mWidthBar.setProgress(10);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
// A simple polyline with the default options from Melbourne-Adelaide-Perth.
mMap.addPolyline((new PolylineOptions())
.add(MELBOURNE, ADELAIDE, PERTH));
// A geodesic polyline that goes around the world.
mMap.addPolyline((new PolylineOptions())
.add(LHR, AKL, LAX, JFK, LHR)
.width(5)
.color(Color.BLUE)
.geodesic(true));
// Circle centered at Sydney. This polyline will be mutable.
PolylineOptions options = new PolylineOptions();
int radius = 5;
int numPoints = 100;
double phase = 2 * Math.PI / numPoints;
for (int i = 0; i <= numPoints; i++) {
options.add(new LatLng(SYDNEY.latitude + radius * Math.sin(i * phase),
SYDNEY.longitude + radius * Math.cos(i * phase)));
}
int color = Color.HSVToColor(
mAlphaBar.getProgress(), new float[] {mColorBar.getProgress(), 1, 1});
mMutablePolyline = mMap.addPolyline(options
.color(color)
.width(mWidthBar.getProgress()));
mColorBar.setOnSeekBarChangeListener(this);
mAlphaBar.setOnSeekBarChangeListener(this);
mWidthBar.setOnSeekBarChangeListener(this);
// Move the map so that it is centered on the mutable polyline.
mMap.moveCamera(CameraUpdateFactory.newLatLng(SYDNEY));
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Don't do anything here.
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMutablePolyline == null) {
return;
}
if (seekBar == mColorBar) {
mMutablePolyline.setColor(Color.HSVToColor(
Color.alpha(mMutablePolyline.getColor()), new float[] {progress, 1, 1}));
} else if (seekBar == mAlphaBar) {
float[] prevHSV = new float[3];
Color.colorToHSV(mMutablePolyline.getColor(), prevHSV);
mMutablePolyline.setColor(Color.HSVToColor(progress, prevHSV));
} else if (seekBar == mWidthBar) {
mMutablePolyline.setWidth(progress);
}
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/PolylineDemoActivity.java | Java | asf20 | 5,783 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Bundle;
/**
* This shows how to create a simple activity with a map and a marker on the map.
* <p>
* Notice how we deal with the possibility that the Google Play services APK is not
* installed/enabled/updated on a user's device.
*/
public class BasicMapActivity extends android.support.v4.app.FragmentActivity {
/**
* Note that this may be null if the Google Play services APK is not available.
*/
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_demo);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
* {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/BasicMapActivity.java | Java | asf20 | 3,489 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import com.example.mapdemo.view.FeatureView;
/**
* The main activity of the API library demo gallery.
* <p>
* The main layout lists the demonstrated features, with buttons to launch them.
*/
public final class MainActivity extends ListActivity {
/**
* A simple POJO that holds the details about the demo that are used by the List Adapter.
*/
private static class DemoDetails {
/**
* The resource id of the title of the demo.
*/
private final int titleId;
/**
* The resources id of the description of the demo.
*/
private final int descriptionId;
/**
* The demo activity's class.
*/
private final Class<? extends android.support.v4.app.FragmentActivity> activityClass;
public DemoDetails(int titleId, int descriptionId,
Class<? extends android.support.v4.app.FragmentActivity> activityClass) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.activityClass = activityClass;
}
}
/**
* A custom array adapter that shows a {@link FeatureView} containing details about the demo.
*/
private static class CustomArrayAdapter extends ArrayAdapter<DemoDetails> {
/**
* @param demos An array containing the details of the demos to be displayed.
*/
public CustomArrayAdapter(Context context, DemoDetails[] demos) {
super(context, R.layout.feature, R.id.title, demos);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
FeatureView featureView;
if (convertView instanceof FeatureView) {
featureView = (FeatureView) convertView;
} else {
featureView = new FeatureView(getContext());
}
DemoDetails demo = getItem(position);
featureView.setTitleId(demo.titleId);
featureView.setDescriptionId(demo.descriptionId);
return featureView;
}
}
private static final DemoDetails[] demos = {new DemoDetails(
R.string.basic_map, R.string.basic_description, BasicMapActivity.class),
new DemoDetails(R.string.camera_demo, R.string.camera_description,
CameraDemoActivity.class),
new DemoDetails(R.string.events_demo, R.string.events_description,
EventsDemoActivity.class),
new DemoDetails(R.string.layers_demo, R.string.layers_description,
LayersDemoActivity.class),
new DemoDetails(
R.string.locationsource_demo, R.string.locationsource_description,
LocationSourceDemoActivity.class),
new DemoDetails(R.string.uisettings_demo, R.string.uisettings_description,
UiSettingsDemoActivity.class),
new DemoDetails(R.string.groundoverlay_demo, R.string.groundoverlay_description,
GroundOverlayDemoActivity.class),
new DemoDetails(R.string.marker_demo, R.string.marker_description,
MarkerDemoActivity.class),
new DemoDetails(R.string.polygon_demo, R.string.polygon_description,
PolygonDemoActivity.class),
new DemoDetails(R.string.polyline_demo, R.string.polyline_description,
PolylineDemoActivity.class),
new DemoDetails(R.string.tile_overlay_demo, R.string.tile_overlay_description,
TileOverlayDemoActivity.class),
new DemoDetails(R.string.options_demo, R.string.options_description,
OptionsDemoActivity.class),
new DemoDetails(R.string.multi_map_demo, R.string.multi_map_description,
MultiMapDemoActivity.class),
new DemoDetails(R.string.retain_map, R.string.retain_map_description,
RetainMapActivity.class),
new DemoDetails(R.string.raw_mapview_demo, R.string.raw_mapview_description,
RawMapViewDemoActivity.class),
new DemoDetails(R.string.programmatic_demo, R.string.programmatic_description,
ProgrammaticDemoActivity.class)};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListAdapter adapter = new CustomArrayAdapter(this, demos);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
DemoDetails demo = (DemoDetails) getListAdapter().getItem(position);
startActivity(new Intent(this, demo.activityClass));
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/MainActivity.java | Java | asf20 | 5,755 |
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.mapdemo;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.GroundOverlay;
import com.google.android.gms.maps.model.GroundOverlayOptions;
import com.google.android.gms.maps.model.LatLng;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* This shows how to add a ground overlay to a map.
*/
public class GroundOverlayDemoActivity extends android.support.v4.app.FragmentActivity
implements OnSeekBarChangeListener {
private static final int TRANSPARENCY_MAX = 100;
private static final LatLng NEWARK = new LatLng(40.714086, -74.228697);
private GoogleMap mMap;
private GroundOverlay mGroundOverlay;
private SeekBar mTransparencyBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ground_overlay_demo);
mTransparencyBar = (SeekBar) findViewById(R.id.transparencySeekBar);
mTransparencyBar.setMax(TRANSPARENCY_MAX);
mTransparencyBar.setProgress(0);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
if (mMap == null) {
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(NEWARK, 11));
mGroundOverlay = mMap.addGroundOverlay(new GroundOverlayOptions()
.image(BitmapDescriptorFactory.fromResource(R.drawable.newark_nj_1922)).anchor(0, 1)
.position(NEWARK, 8600f, 6500f));
mTransparencyBar.setOnSeekBarChangeListener(this);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mGroundOverlay != null) {
mGroundOverlay.setTransparency((float) progress / (float) TRANSPARENCY_MAX);
}
}
}
| 12pji-takeaphoto | branches/GoogleSample/src/com/example/mapdemo/GroundOverlayDemoActivity.java | Java | asf20 | 3,147 |
package com.tutos.android.ui;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class AndroidTabLayoutActivity extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.androidtablayout);
TabHost tabHost = getTabHost();
// setting Title and Icon for the Tab
TabSpec photospec = tabHost.newTabSpec("TaheAPhotoForMe");
photospec.setIndicator("TaheAPhotoForMe", getResources().getDrawable(R.drawable.ic_action_search));
Intent photosIntent = new Intent(this, MapActivity.class);
photospec.setContent(photosIntent);
// Tab for Videos
TabSpec videospec = tabHost.newTabSpec("ITakeForYou");
videospec.setIndicator("ITakeForYou", getResources().getDrawable(R.drawable.ic_launcher));
Intent videosIntent = new Intent(this, MapActivity.class);
videospec.setContent(videosIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(photospec); // Adding photos tab
tabHost.addTab(videospec); // Adding photos tab
}
}
| 12pji-takeaphoto | branches/TakeAPhotoForMe/src/com/tutos/android/ui/AndroidTabLayoutActivity.java | Java | asf20 | 1,258 |
package com.tutos.android.ui;
import android.os.Bundle;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
/**
* This shows how to create a simple activity with a map and a marker on the map.
* <p>
* Notice how we deal with the possibility that the Google Play services APK is not
* installed/enabled/updated on a user's device.
*/
public class MapActivity extends android.support.v4.app.FragmentActivity {
/**
* Note that this may be null if the Google Play services APK is not available.
*/
/**
* Note that this may be null if the Google Play services APK is not available.
*/
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
setUpMapIfNeeded();
}
@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}
/**
* Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
* installed) and the map has not already been instantiated.. This will ensure that we only ever
* call {@link #setUpMap()} once when {@link #mMap} is not null.
* <p>
* If it isn't installed {@link SupportMapFragment} (and
* {@link com.google.android.gms.maps.MapView
* MapView}) will show a prompt for the user to install/update the Google Play services APK on
* their device.
* <p>
* A user can return to this Activity after following the prompt and correctly
* installing/updating/enabling the Google Play services. Since the Activity may not have been
* completely destroyed during this process (it is likely that it would only be stopped or
* paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
* {@link #onResume()} to guarantee that it will be called.
*/
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case, we
* just add a marker near Africa.
* <p>
* This should only be called once and when we are sure that {@link #mMap} is not null.
*/
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
}
| 12pji-takeaphoto | branches/TakeAPhotoForMe/src/com/tutos/android/ui/MapActivity.java | Java | asf20 | 2,965 |
/** Automatically generated file. DO NOT MODIFY */
package com.example.uploadimagedemo;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | 12pji-takeaphoto | branches/UploadImageDemo/gen/com/example/uploadimagedemo/BuildConfig.java | Java | asf20 | 169 |
package com.example.uploadimagedemo;
public class c {
}
| 12pji-takeaphoto | branches/UploadImageDemo/src/com/example/uploadimagedemo/c.java | Java | asf20 | 58 |
package com.example.uploadimagedemo;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public String filepath = "/storage/sdcard0";
TextView tv;
Button b;
int serverResponseCode = 0;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = (Button)findViewById(R.id.but);
tv = (TextView)findViewById(R.id.tv);
tv.setText("Uploading file path :- " + filepath + "'/DCIM/Camera/photo.jpg'");
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(MainActivity.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
tv.setText("uploading started.....");
}
});
int response= uploadFile(filepath + "/DCIM/Camera/photo.jpg");
System.out.println("RES : " + response);
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/upload_media_test.php";
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
File f = new File("");
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist : " + sourceFileUri + ", path :" + f.getAbsolutePath());
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
tv.setText("File Upload Completed.");
Toast.makeText(MainActivity.this, "File Upload Complete.", Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Toast.makeText(MainActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
Toast.makeText(MainActivity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
}
}
| 12pji-takeaphoto | branches/UploadImageDemo/src/com/example/uploadimagedemo/MainActivity.java | Java | asf20 | 6,403 |
package com.example.pji_authgoogle;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
| 12pji-takeaphoto | branches/PJI_AuthGoogle/src/com/example/pji_authgoogle/MainActivity.java | Java | asf20 | 527 |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gms;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | 12pji-takeaphoto | branches/google-play-services_lib/gen/com/google/android/gms/BuildConfig.java | Java | asf20 | 164 |
package com.example.tabtest;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
| 12pji-takeaphoto | branches/TabTest/src/com/example/tabtest/MainActivity.java | Java | asf20 | 5,307 |
/** Automatically generated file. DO NOT MODIFY */
package com.example.getpost;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | 12pji-takeaphoto | branches/getpost/gen/com/example/getpost/BuildConfig.java | Java | asf20 | 161 |
package com.example.getpost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class GetAndPost extends Activity {
TextView tv;
String text;
private Context context;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = this.getLayoutInflater().getContext();
tv = (TextView)findViewById(R.id.textview);
text = "";
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/post.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "9999"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
int responseCode = response.getStatusLine().getStatusCode();
switch(responseCode) {
case 200:
HttpEntity entity = response.getEntity();
if(entity != null) {
String responseBody = EntityUtils.toString(entity);
message(responseBody);
}
break;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
public void message(String message) {
Toast toast = Toast.makeText(context, message, 4);
toast.show();
}
}
| 12pji-takeaphoto | branches/getpost/src/com/example/getpost/GetAndPost.java | Java | asf20 | 2,463 |
package com.android.map;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class HelloGoogleMapActivity extends MapActivity {
private MapView mapView;
private MapController mc;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView) this.findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
mc.setZoom(5);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
mapView.setSatellite(true);
return true;
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
mapView.setSatellite(false);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| 12pji-takeaphoto | branches/HelloGoogleMap/src/com/android/map/HelloGoogleMapActivity.java | Java | asf20 | 1,155 |
/** Automatically generated file. DO NOT MODIFY */
package com.takeaphoto.activity;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | 12pji-takeaphoto | trunk/gen/com/takeaphoto/activity/BuildConfig.java | Java | asf20 | 165 |
package com.takeaphoto.activity;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
} | 12pji-takeaphoto | trunk/src/com/takeaphoto/activity/CustomViewPager.java | Java | asf20 | 864 |
package com.takeaphoto.activity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.takeaphoto.model.Demande;
import com.takeaphoto.model.User;
import com.takeaphoto.server.DemandeServeur;
import com.takeaphoto.server.PhotoServeur;
import com.takeaphoto.server.UserServeur;
public class ManagerActivity extends ListFragment {
final String EXTRA_ID_USER = "ID_User";
private ArrayList<Demande> demandes ;
private User currentUser ;
private ArrayList<Bitmap> photos = null ;
private int nbPhotosCurrent, nbPhotos ;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
int id = getActivity().getIntent().getIntExtra(EXTRA_ID_USER, -1) ;
currentUser = new UserServeur().getUser(getActivity(), id) ;
if(demandes == null){
updateDemandes() ;
}
}
private void updateDemandes() {
if(currentUser != null){
new DemandeServeur().updateMyDemandesLocal(getActivity(), currentUser);
actualiserListeDemande() ;
}else
setListAdapter(null) ;
}
public void actualiserListeDemande(){
if(currentUser != null){
demandes = new DemandeServeur().getMyDemandesLocal(getActivity(), currentUser) ;
if(demandes != null){
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
String[] Descriptions = new String[demandes.size()] ;
int[] images = new int[demandes.size()] ;
for(int i = 0 ; i < demandes.size(); i++){
Descriptions[i] = demandes.get(i).getDescription() ;
switch (demandes.get(i).getEtat()) {
case 0:
images[i] = R.drawable.vert ;
break;
case 1:
images[i] = R.drawable.jaune ;
break;
case 2:
images[i] = R.drawable.rouge ;
break;
default:
break;
}
}
for(int i=0;i<demandes.size();i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", Descriptions[i]);
hm.put("image", Integer.toString(images[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "image","txt" };
// Ids of views in listview_layout
int[] to = { R.id.image, R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview, from, to);
setListAdapter(adapter);
}
else
setListAdapter(null) ;
}else
setListAdapter(null) ;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.refresh, menu) ;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh :
updateDemandes() ;
break ;
}
return true ;
}
@Override
public void onListItemClick(ListView l, View v, final int position, long id) {
final int id_demande = demandes.get(position).getId() ;
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
int etat = demandes.get(position).getEtat() ;
if(etat == 0){
alert.setTitle("Demande : " + demandes.get(position).getDescription());
alert.setPositiveButton("Modifier Description", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
renomerDemande(position) ;
}
});
alert.setNeutralButton("Supprimer Demande", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
supprimerDemande(id_demande) ;
}
});
alert.setNegativeButton("Annuler", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
alert.show();
}else if(etat == 1 || etat == 2){
ArrayList<Object> result = new PhotoServeur().getUrls(currentUser, id_demande) ;
if(result != null){
photos = new ArrayList<Bitmap>() ;
nbPhotos = result.size() ;
nbPhotosCurrent = 0 ;
for(Object url : result){
new getPhoto().execute((String)url, id_demande+"") ;
}
}
}
}
public class getPhoto extends AsyncTask<String, Integer, Bitmap> {
volatile int id_demande ;
@Override
protected Bitmap doInBackground(String ... args ) {
id_demande = Integer.parseInt(args[1]) ;
String url = "http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/" + args[0] ;
Bitmap bmp = null ;
try {
URLConnection conn = null;
URL u = new URL(url) ;
conn = u.openConnection() ;
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
InputStream is = null;
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
is = httpConn.getInputStream();
int thisLine;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((thisLine = is.read()) != -1) {
bos.write(thisLine);
}
bos.flush();
byte [] data = bos.toByteArray();
if (bos != null){
bos.close();
}
bmp=BitmapFactory.decodeByteArray(data,0,data.length);
return bmp;
}
httpConn.disconnect() ;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bmp ;
}
protected void onPostExecute(Bitmap bmp)
{
photos.add(bmp) ;
nbPhotosCurrent ++ ;
if(nbPhotos == nbPhotosCurrent){
nbPhotosCurrent = 0 ;
afficherPhotos(id_demande) ;
}
}
}
private void afficherPhotos(final int id_demande){
if(photos != null && nbPhotosCurrent < nbPhotos){
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()) ;
ImageView iv = new ImageView(getActivity()) ;
iv.setImageBitmap(photos.get(nbPhotosCurrent)) ;
alert.setView(iv) ;
alert.setTitle("photo " + (nbPhotosCurrent+1) + "/" + nbPhotos) ;
if(nbPhotosCurrent < nbPhotos -1){
alert.setPositiveButton("Suivant", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
nbPhotosCurrent ++ ;
afficherPhotos(id_demande) ;
}
}) ;
}
alert.setNegativeButton("Ok", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
photos = null ;
nbPhotos = 0 ;
nbPhotosCurrent = 0 ;
afficherPhotos(id_demande) ;
}
}) ;
alert.show() ;
}else
choixEtat(id_demande) ;
}
private void choixEtat(final int id_demande){
Demande demande = new DemandeServeur().getLocalDemandeWithId(getActivity(), id_demande) ;
if(demande.getEtat() == 1){
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity()) ;
ImageView iv = new ImageView(getActivity()) ;
alert.setView(iv) ;
alert.setTitle("Voulez-vous d'autres photos pour cette demande ?") ;
alert.setPositiveButton("Oui", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}) ;
alert.setNegativeButton("Non", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
new DemandeServeur().updateDemande(getActivity(), currentUser, id_demande, "etat", "2") ;
actualiserListeDemande() ;
}
}) ;
alert.show() ;
}
}
private void renomerDemande(final int position){
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setTitle("Description de la photo voulue :");
// Set an EditText view to get user input
final EditText input = new EditText(getActivity());
input.setText(demandes.get(position).getDescription()) ;
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String desc = input.getText().toString() ;
String result = new DemandeServeur().updateDemande(getActivity(), currentUser, demandes.get(position).getId(), "description", desc) ;
if(result != null)
Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivity(), R.string.erreur_connextion, Toast.LENGTH_SHORT).show();
actualiserListeDemande() ;
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
private void supprimerDemande(final int id_demande){
String result = new DemandeServeur().removeDemande(getActivity(), currentUser, id_demande) ;
if(result != null)
Toast.makeText(getActivity(), result, Toast.LENGTH_SHORT).show();
else
Toast.makeText(getActivity(), R.string.erreur_connextion, Toast.LENGTH_SHORT).show();
actualiserListeDemande() ;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/activity/ManagerActivity.java | Java | asf20 | 11,056 |
package com.takeaphoto.activity;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.takeaphoto.database.Demande;
import com.takeaphoto.database.DemandesBDD;
public class MapReponse extends SupportMapFragment {
final String EXTRA_LOGIN = "user_login";
private GoogleMap gMap;
private Activity mainActivity ;
private DemandesBDD demandeBdd ;
private ArrayList<MarkerOptions> markers ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
markers = new ArrayList<MarkerOptions>() ;
}
public void setMainActivity(Activity main) {
mainActivity = main ;
}
public void setDemandeBdd(DemandesBDD demandeBdd){
this.demandeBdd = demandeBdd ;
}
@Override
public void onResume() {
super.onResume();
setUpMapIfNeeded();
updateDemandes() ;
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (gMap == null) {
// Try to obtain the map from the SupportMapFragment.
gMap = getMap();
gMap.setMyLocationEnabled(true);
}
}
private void updateDemandes(){
demandeBdd.open() ;
ArrayList<Demande> demandes = demandeBdd.getDemandeWithoutLogin(mainActivity.getIntent().getStringExtra(EXTRA_LOGIN)) ;
demandeBdd.close() ;
if(demandes != null){
for(Demande d : demandes){
MarkerOptions m = new MarkerOptions() ;
m.title(d.getLogin()) ;
m.position(new LatLng(d.getLat(), d.getLng())) ;
m.snippet(d.getDescription()) ;
markers.add(m) ;
}
}
for(MarkerOptions m : markers){
gMap.addMarker(m);
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = super.onCreateView(inflater, container, savedInstanceState) ;
return myFragmentView;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/activity/MapReponse.java | Java | asf20 | 2,402 |
package com.takeaphoto.activity;
import java.util.Locale;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import com.takeaphoto.utils.CustomViewPager;
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private SectionsPagerAdapter mSectionsPagerAdapter;
private CustomViewPager mViewPager;
private ManagerActivity manager = new ManagerActivity() ;
private MapAddActivity mapAdd = new MapAddActivity() ;
private MapReponseActivity mapRep = new MapReponseActivity() ;
final int NB_ONGLET = 3 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (CustomViewPager) findViewById(R.id.photosViewPager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
mViewPager.setPagingEnabled(false) ;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onResume() {
super.onResume();
}
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {}
@Override
public void onTabReselected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction) {}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment frag = new Fragment() ;
switch (position) {
case 0:
frag = mapAdd ;
break;
case 1:
frag = mapRep ;
break ;
case 2:
frag = manager ;
break;
}
return frag ;
}
@Override
public int getCount() {
// Show 3 total pages.
return NB_ONGLET;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/activity/MainActivity.java | Java | asf20 | 4,140 |
package com.takeaphoto.model;
public class Demande {
private int id ;
private int id_user ;
private Double lat ;
private Double lng ;
private String description ;
private int etat ;
public Demande(){}
public Demande(int id_user, Double lat, Double lng, String description) {
this.id_user = id_user;
this.lat = lat ;
this.lng = lng ;
this.description = description;
this.etat = 0 ;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getId_user() {
return id_user;
}
public void setId_user(int id_user) {
this.id_user = id_user;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getEtat() {
return etat;
}
public void setEtat(int etat) {
this.etat = etat;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
@Override
public String toString() {
return "Demande [id=" + id + ", id_user=" + id_user + ", lat=" + lat
+ ", lng=" + lng + ", description=" + description + ", etat="
+ etat + "]";
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/model/Demande.java | Java | asf20 | 1,264 |
package com.takeaphoto.model;
public class User {
private int id ;
private String login ;
private String pass ;
public User() { }
public User(int id, String login, String pass) {
this.id=id ;
this.login = login;
this.pass = pass;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", pass=" + pass + "]";
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/model/User.java | Java | asf20 | 673 |
package com.takeaphoto.server;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import com.takeaphoto.database.UserBDD;
import com.takeaphoto.model.User;
public class UserServeur extends Serveur{
static UserBDD userbdd = null;
private void userBddIsSet(Context context){
if(userbdd == null)
userbdd = new UserBDD(context) ;
}
public User getUser(Context context, int idUser){
userBddIsSet(context);
User user = null ;
userbdd.open() ;
user = userbdd.getUserWithId(idUser) ;
userbdd.close() ;
return user ;
}
public HashMap<String, Object> authentification(Context context, String login, String pass){
userBddIsSet(context);
//HashMap<String, Object> resultTmp = null ;
ArrayList<String> args = new ArrayList<String>() ;
args.add("authentification.php") ;
args.add("login="+login);
args.add("pass="+pass) ;
/*JSONObject joMap = new JSONObject();
JSONArray jArray = new JSONArray();
JSONObject jo = new JSONObject();
try {
jo.put("url", "authentification.php");
jo.put("login", login);
jo.put("pass", pass);
jArray.put(jo);
joMap.put("POST", jArray);
Log.i("JSONObject ", joMap.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//sendJson(joMap) ;
// resultTmp = Serveur.sendJson("authentification.php", args);
sendJson(args) ;
while(isRunning()){}
if(getResultArray() != null){
if(getResultArray().containsKey("id")){
userbdd.open() ;
userbdd.clear() ;
userbdd.close() ;
int id = Integer.parseInt((String)getResultArray().get("id")) ;
User u = new User(id, login, pass);
userbdd.open() ;
userbdd.insertUser(u);
userbdd.close() ;
}
}
HashMap<String, Object> tmpMap = getResultArray() ;
setResultToFalse() ;
return tmpMap ;
}
public HashMap<String, Object> createUser(Context context, String login, String pass){
userBddIsSet(context);
ArrayList<String> args = new ArrayList<String>() ;
args.add("create_user.php") ;
args.add("login="+login);
args.add("pass="+pass) ;
sendJson(args) ;
while(isRunning()){}
HashMap<String, Object> tmpMap = getResultArray() ;
setResultToFalse() ;
return tmpMap ;
}
public User getOnlyUser(Context context) {
userBddIsSet(context);
User user = null ;
userbdd.open() ;
ArrayList<User> users = userbdd.getALLUser() ;
userbdd.close() ;
if(users != null && users.size() == 1)
user = users.get(0) ;
return user ;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/server/UserServeur.java | Java | asf20 | 2,601 |
package com.takeaphoto.server ;
import java.util.ArrayList;
import java.util.HashMap;
public abstract class Serveur {
private boolean running = true ;
private HashMap<String, Object> resultArray ;
@SuppressWarnings("unchecked")
public void sendJson(ArrayList<String> args){
setResultToFalse() ;
new ServeurAsync(this).execute(args);
}
public HashMap<String, Object> getResultArray() {
return resultArray;
}
public boolean isRunning() {
return running;
}
public void setResult(HashMap<String, Object> resultArray ){
this.resultArray = resultArray ;
}
public void setRunning(boolean b){
running = b ;
}
public void setResultToFalse(){
resultArray = new HashMap<String, Object>() ;
resultArray.put("result", "FALSE") ;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/server/Serveur.java | Java | asf20 | 770 |
package com.takeaphoto.server;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import android.util.Log;
import com.takeaphoto.model.User;
import com.takeaphoto.utils.MCrypt;
public class PhotoServeur extends Serveur {
public int uploadFile(String sourceFilePath, User currentUser, int id_demande) throws Exception {
int serverResponseCode = 0;
String upLoadServerUri = "http://jeremiesamson-portfolio.com/wp-content/uploads/takeaphotoforme/upload_media.php";
String params = "?login="+ currentUser.getLogin() + "&pass=" + MCrypt.bytesToHex( new MCrypt().encrypt(currentUser.getPass())) + "&id_demande=" + id_demande;
upLoadServerUri += params ;
System.out.println(upLoadServerUri);
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFilePath);
File f = new File("");
if (!sourceFile.isFile()) {
Log.e("uploadFile", "Source File Does not exist : " + sourceFilePath + ", path :" + f.getAbsolutePath());
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", sourceFilePath);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ sourceFilePath + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
//Toast.makeText(PhotoActivity.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(PhotoActivity.this, "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);
}
return serverResponseCode;
}
public ArrayList<Object> getUrls(User currentUser, int id_demande){
ArrayList<Object> resultTmp = null ;
ArrayList<String> args = new ArrayList<String>() ;
args.add("get_photos.php") ;
args.add("login="+currentUser.getLogin());
args.add("pass="+currentUser.getPass()) ;
args.add("id_demande="+id_demande);
sendJson(args);
while(isRunning()){}
if(getResultArray() != null){
if(getResultArray() != null){
resultTmp = new ArrayList<Object>() ;
for (String mapKey : getResultArray().keySet()) {
resultTmp.add(getResultArray().get(mapKey)) ;
}
}
}
return resultTmp ;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/server/PhotoServeur.java | Java | asf20 | 5,149 |
package com.takeaphoto.database;
public class Demande {
private int id ;
private String login ;
private Double lat ;
private Double lng ;
private String description ;
private int etat ;
public Demande(){}
public Demande(String login, Double lat, Double lng, String description) {
this.login = login;
this.lat = lat ;
this.lng = lng ;
this.description = description;
this.etat = 0 ;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getEtat() {
return etat;
}
public void setEtat(int etat) {
this.etat = etat;
}
public Double getLat() {
return lat;
}
public void setLat(Double lat) {
this.lat = lat;
}
public Double getLng() {
return lng;
}
public void setLng(Double lng) {
this.lng = lng;
}
@Override
public String toString() {
return "Demande [id=" + id + ", login=" + login + ", lat=" + lat
+ ", lng=" + lng + ", description=" + description + ", etat="
+ etat + "]";
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/database/Demande.java | Java | asf20 | 1,254 |
package com.takeaphoto.utils;
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
} | 12pji-takeaphoto | trunk/src/com/takeaphoto/utils/CustomViewPager.java | Java | asf20 | 861 |
package com.takeaphoto.utils;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MCrypt {
private String iv = "securitykey99999";//Dummy iv (CHANGE IT!)
private IvParameterSpec ivspec;
private SecretKeySpec keyspec;
private Cipher cipher;
private String SecretKey = "99999keysecurity";//Dummy secretKey (CHANGE IT!)
public MCrypt()
{
ivspec = new IvParameterSpec(iv.getBytes());
keyspec = new SecretKeySpec(SecretKey.getBytes(), "AES");
try {
cipher = Cipher.getInstance("AES/CBC/NoPadding");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public byte[] encrypt(String text) throws Exception
{
if(text == null || text.length() == 0)
throw new Exception("Empty string");
byte[] encrypted = null;
try {
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
encrypted = cipher.doFinal(padString(text).getBytes());
} catch (Exception e)
{
throw new Exception("[encrypt] " + e.getMessage());
}
return encrypted;
}
public byte[] decrypt(String code) throws Exception
{
if(code == null || code.length() == 0)
throw new Exception("Empty string");
byte[] decrypted = null;
try {
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
decrypted = cipher.doFinal(hexToBytes(code));
} catch (Exception e)
{
throw new Exception("[decrypt] " + e.getMessage());
}
return decrypted;
}
public static String bytesToHex(byte[] data)
{
if (data==null)
{
return null;
}
int len = data.length;
String str = "";
for (int i=0; i<len; i++) {
if ((data[i]&0xFF)<16)
str = str + "0" + java.lang.Integer.toHexString(data[i]&0xFF);
else
str = str + java.lang.Integer.toHexString(data[i]&0xFF);
}
return str;
}
public static byte[] hexToBytes(String str) {
if (str==null) {
return null;
} else if (str.length() < 2) {
return null;
} else {
int len = str.length() / 2;
byte[] buffer = new byte[len];
for (int i=0; i<len; i++) {
buffer[i] = (byte) Integer.parseInt(str.substring(i*2,i*2+2),16);
}
return buffer;
}
}
private static String padString(String source)
{
char paddingChar = ' ';
int size = 16;
int x = source.length() % size;
int padLength = size - x;
for (int i = 0; i < padLength; i++)
{
source += paddingChar;
}
return source;
}
}
| 12pji-takeaphoto | trunk/src/com/takeaphoto/utils/MCrypt.java | Java | asf20 | 4,089 |
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void read(vector <T> &data) {
int length;
cin >> length;
if (length == 4)
throw 1;
data.resize(length);
for (int i = 0; i < length; ++i) {
cin >> data[i];
}
return;
}
template <typename iterator, typename T>
iterator partition(iterator begin, iterator end, T value) {
if (end - begin == 0)
return begin;
iterator left = begin, right = end - 1;
while (left != right) {
while (left != right && *left < value) {
++left;
}
while (left != right && *right >= value) {
--right;
}
swap(*left, *right);
if (left == right || left == right - 1)
break;
++left, --right;
}
if (*begin >= value)
return begin;
while (*left >= value && left != begin)
--left;
while (left != end && *left < value)
++left;
return left;
}
int main() {
vector <int> data;
read(data);
int value;
cin >> value;
int less = partition(data.begin(), data.end(), value) - data.begin();
cout << less << endl << data.size() - less << endl;
} | 1012-group-trunk | trunk/Anton_Urusov/homework1/homework1-e.cpp | C++ | gpl3 | 1,204 |
#include <fstream>
#include <vector>
using namespace std;
template <typename T>
void read(vector <T> &data) {
int length;
ifstream in("input.txt");
in >> length;
data.resize(length);
for (int i = 0; i < length; ++i) {
in >> data[i];
}
return;
}
template <typename T>
void max_to_end(vector <T> &data, int length) {
int position = 0;
if (length == 0) {
return;
}
for (int i = 0; i < length; ++i) {
if (data[i] > data[position]) {
position = i;
}
}
swap(data[position], data[length - 1]);
return;
}
template <typename T>
void sort(vector <T> &data) {
for (int i = data.size(); i > 0; --i) {
max_to_end(data, i);
}
}
template <typename T>
void print(vector <T> &data) {
ofstream out("output.txt");
for (int i = 0; i < data.size(); ++i) {
out << data[i] << ' ';
}
return;
}
int main() {
ios_base::sync_with_stdio(0);
vector <int> data;
read(data);
sort(data);
print(data);
} | 1012-group-trunk | trunk/Anton_Urusov/homework1/homework1-b.cpp | C++ | gpl3 | 1,035 |
#include <fstream>
#include <vector>
using namespace std;
template <typename T>
void read(vector <T> &data) {
int length;
ifstream in("input.txt");
in >> length;
data.resize(length);
for (int i = 0; i < length; ++i) {
in >> data[i];
}
return;
}
template <typename T>
void max_to_end(vector <T> &data) {
int position = 0;
if (data.empty()) {
return;
}
for (int i = 0; i < data.size(); ++i) {
if (data[i] > data[position]) {
position = i;
}
}
swap(data[position], data.back());
return;
}
template <typename T>
void print(vector <T> &data) {
ofstream out("output.txt");
for (int i = 0; i < data.size(); ++i) {
out << data[i] << ' ';
}
return;
}
int main() {
vector <int> data;
read(data);
max_to_end(data);
print(data);
} | 1012-group-trunk | trunk/Anton_Urusov/homework1/homework1-a.cpp | C++ | gpl3 | 862 |