identifier
stringlengths 42
383
| collection
stringclasses 1
value | open_type
stringclasses 1
value | license
stringlengths 0
1.81k
| date
float64 1.99k
2.02k
⌀ | title
stringlengths 0
100
| creator
stringlengths 1
39
| language
stringclasses 157
values | language_type
stringclasses 2
values | word_count
int64 1
20k
| token_count
int64 4
1.32M
| text
stringlengths 5
1.53M
| __index_level_0__
int64 0
57.5k
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://github.com/TodorGinchev/ThePRECIOUSprojectAPP/blob/master/PRECIOUS/app/src/main/java/ui/precious/comnet/aalto/precious/ui_MainActivity.java
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,015
|
ThePRECIOUSprojectAPP
|
TodorGinchev
|
Java
|
Code
| 2,559
| 11,398
|
//Documentation for android custom views:
// http://android-developers.blogspot.fi/2015/05/android-design-support-library.html
//Documentation for action bar configuration:
// http://blog.rhesoft.com/2015/03/30/tutorial-android-actionbar-with-material-design-and-search-field/
//Documentation for tutorial view
// http://forum.xda-developers.com/showthread.php?t=2419939
package ui.precious.comnet.aalto.precious;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.Target;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import java.util.Calendar;
import java.util.Vector;
import aalto.comnet.thepreciousproject.R;
import confidence_ruler.precious.comnet.aalto.CR_ThirdActivity;
import diet_challenges.precious.comnet.aalto.fi.dc_AddChallenge;
import firstbeatalbum.precious.comnet.aalto.FirstBeatAlbumActivity;
import food_diary.precious.comnet.aalto.fd_MainActivity;
import my_favourites.precious.comnet.aalto.FA_SecondActivity;
import my_favourites.precious.comnet.aalto.my_favourites_activity;
import pa_state_of_change.precious.comnet.aalto.PA_SOC_FirstActivity;
import precious_rule_system.journeyview.assets.Assets;
import precious_rule_system.journeyview.data.DataManager;
import precious_rule_system.journeyview.helpers.SizeCalculator;
import precious_rule_system.journeyview.recycler.RecyclerView;
import precious_rule_system.journeyview.view.JourneyView;
import precious_rule_system.precoiusinterface.PreciousApplicationActions;
import time_machine.precious.comnet.aalto.TM_SecondActivity;
public class ui_MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
// private GoogleApiClient client;
public static final String TAG = "ui_MainActivity";
public static final String UP_PREFS_NAME = "UploaderPreferences";
public static final String UI_PREFS_NAME = "UIPreferences";
public static final int ONBOARDING_RESULT_CODE = 1012;
final private int EXT_STORAGE_PERMISSION = 23;
private SharedPreferences uploader_preferences;
public static Context mContext;
public static String [] boxOrganizer;
private PRECIOUS_APP preciousRuleSystem;
//For the tutorial
public static ShowcaseView showcaseView;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG,"onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preciousRuleSystem = PRECIOUS_APP.getInstance();
// initJurneyView();
// uiUtils.firstStartConfig();
}
@Override
public void onResume(){
uiUtils.CheckIfAlarmAlive();
Log.i(TAG,"onResume");
mContext=this;
uploader_preferences = this.getSharedPreferences(UP_PREFS_NAME, 0);
SB_current_rows=0;
SB_current_half_row=0;
SB_current_half_col=0;
//If Android version >=5.0, set status bar background color
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
getWindow().setStatusBarColor(0x000000);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
// ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
// this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
// //Add this for the jurney view
// {
// public void onDrawerClosed(View view) {
// super.onDrawerClosed(view);
// Log.i(TAG,"Calling store.data.onPause();");
// store.data.onPause();
// }
// public void onDrawerOpened(View drawerView) {
// super.onDrawerOpened(drawerView);
// Log.i(TAG,"Calling store.data.onResume();");
// store.data.onResume();
// }
// };
// drawer.setDrawerListener(toggle);
// toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Set username and location
//View header = navigationView.inflateHeaderView(R.layout.ui_nav_header_main);
//navigationView.addHeaderView(header);
View header = navigationView.getHeaderView(0);
// ImageView iv_profile = (ImageView) header.findViewById(R.id.imageViewProfile);
// iv_profile.setImageResource(R.drawable.profile);
// TextView tv_username = (TextView) header.findViewById(R.id.textViewNavDrawUsername);
// tv_username.setText("");
//// tv_username.setText(uploader_preferences.getString("nickname",""));
// TextView tv_location = (TextView) header.findViewById(R.id.textViewNavDrawLocation);
// tv_location.setText("");
//Change toolbar title
ActionBar actionBar = getSupportActionBar();
//actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
//actionBar.setDisplayShowTitleEnabled(true);
if(uploader_preferences.getString("nickname","?").equals("?")) {
actionBar.setTitle("REGISTER!");
}
else {
try {
String nickname = uploader_preferences.getString("nickname", "");
actionBar.setTitle(getString(R.string.toolbar_name).concat(" ").concat(nickname).concat("!"));
// @christopher
// Set the nickname in the reward system as well
if (!nickname.equals("") && PRECIOUS_APP.getRewardSystem() != null) {
PRECIOUS_APP.getRewardSystem().setUser(nickname);
}
}catch (Exception e){
Log.e(TAG," ",e);
}
}
super.onResume();
askForPermissions();
//Check if user has logged in
if( !(uploader_preferences.getBoolean("isUserLoggedIn",false)) ) {
sql_db.precious.comnet.aalto.DBHelper.getInstance().dropAllTables();
Intent i2 = new Intent(this,onboarding.precious.comnet.aalto.obMainActivity.class);
this.startActivity(i2);
}
//Update AppNotOpenedSince timestamp
SharedPreferences.Editor editor = uploader_preferences.edit();
editor.putLong("AppNotOpenedSince",System.currentTimeMillis());
editor.apply();
gridLayout = (GridLayout) findViewById(R.id.grid_layout);
display = getWindowManager().getDefaultDisplay();
initSandBox();
// if(uploader_preferences.getString("nickname","?").equals("?")) {
// finish();
// }
//Store app usage
try{
sql_db.precious.comnet.aalto.DBHelper.getInstance().insertAppUsage(System.currentTimeMillis(), "ui_MainActivity", "onResume");
}catch (Exception e){
Log.e(TAG," ",e);
}
//Check if user has registered and tutorial is done
SharedPreferences at_preferences = this.getSharedPreferences(UI_PREFS_NAME, 0);
boolean OGisenabled = false;
for (int i = 0; i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("OG"))
OGisenabled=true;
if( uploader_preferences.getBoolean("isUserLoggedIn",false) && !at_preferences.getBoolean("at_tutorial_completed",false) && OGisenabled){
startTutorial();
}
else if (showcaseView!=null)
showcaseView.hide();
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
// @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 boolean onOptionsItemSelected(MenuItem item) {
// // Handle action bar item clicks here. The action bar will
// // automatically handle clicks on the Home/Up button, so long
// // as you specify a parent activity in AndroidManifest.xml.
// int id = item.getItemId();
//
// //noinspection SimplifiableIfStatement
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_about) {
String url = "http://www.thepreciousproject.eu/";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
} else if (id == R.id.nav_feedback) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{"todor.a.ginchev@aalto.fi"});
String version = "";
try{
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pInfo.versionName;
} catch (Exception e) {
Log.e(TAG, " ", e);
}
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.report_problem_template_title).concat(version));
String text = getString(R.string.report_problem_template_content);
SharedPreferences preferences = this.getSharedPreferences(UP_PREFS_NAME, 0);
intent.putExtra(Intent.EXTRA_TEXT,text);
startActivity(Intent.createChooser(intent, "Send Email"));
}
else if (id == R.id.nav_logout) {
SharedPreferences preferences = this.getSharedPreferences(UP_PREFS_NAME, 0);
int groupID = preferences.getInt("group_ID", -1);
//Todo: Comment out to disable logout restriction for uh trials
if(groupID/1000==9) {
Toast.makeText(this,"Users from Helsinki trials are not allowed to log out",Toast.LENGTH_SHORT).show();
return true;
}
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.putBoolean("isUserLoggedIn", false);
editor.putString("email", "?");
editor.putString("password", "?");
editor.putString("weight", "?");
editor.putString("height", "?");
editor.putString("activityClass", "?");
editor.putString("nickname", "");
editor.putString("birthdate", "?");
editor.putString("gender", "?");
editor.apply();
preferences = this.getSharedPreferences(CR_ThirdActivity.CR_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(UI_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(FA_SecondActivity.FA_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(FA_SecondActivity.OG_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(TM_SecondActivity.TM_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(PA_SOC_FirstActivity.PA_SOC_PREFS_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
preferences = this.getSharedPreferences(dc_AddChallenge.DC_PREF_NAME, 0);
editor = preferences.edit();
editor.clear();
editor.apply();
Intent i2 = new Intent(this,onboarding.precious.comnet.aalto.obMainActivity.class);
this.startActivity(i2);
}
// else if (id == R.id.nav_manage) {
//
// }
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public static GridLayout gridLayout;
private static Display display;
private static int LayoutWidth;
private static int BoxMargins;
private static int SB_cols=2;
private static int SB_rows=50;//TODO, very important parameter!!!
private static int SB_current_rows=0;
private static int SB_current_half_row=0;
private static int SB_current_half_col=0;
private Vector<ImageView> SBelements = new Vector<ImageView>();
public static void initSandBox() {
SharedPreferences preferences_up = mContext.getSharedPreferences(UP_PREFS_NAME, 0);
int groupID = preferences_up.getInt("group_ID", -1);
if(!preferences_up.getBoolean("GroupIDsent",false)){
uploader.precious.comnet.aalto.upUtils.sendGroupIDToPreciousServer(groupID);
}
Calendar c_aux = Calendar.getInstance();
Log.i(TAG,"Registration time="+preferences_up.getLong("rd", System.currentTimeMillis()));
long timeNow=System.currentTimeMillis();
long registrationTime = timeNow;
try {
registrationTime = preferences_up.getLong("rd", timeNow);
SharedPreferences.Editor editor = preferences_up.edit();
editor.putLong("rd",(long)registrationTime);
editor.commit();
}catch (Exception e){
Log.e(TAG," ",e);
}
c_aux.setTimeInMillis(registrationTime);
c_aux.set(Calendar.HOUR_OF_DAY, 0);
c_aux.set(Calendar.MINUTE, 0);
c_aux.set(Calendar.SECOND, 0);
c_aux.set(Calendar.MILLISECOND, 0);
boolean seven_days_passed=System.currentTimeMillis() > (c_aux.getTimeInMillis()+8*24*3600*1000);
Log.i(TAG,"GroupID="+groupID);
if(groupID==130 || groupID==517){
//Fruit and Vegetable challenge- Motivation off after 7 days
boxOrganizer = new String[]{"DC"};
}
else if(groupID==678 || groupID==392){
//Fruit and Vegetable challenge- Motivation on after 7 days
if(seven_days_passed){
boxOrganizer = new String[]{"OG", "IR", "DC"};
//TODO
}
else{
boxOrganizer = new String[]{"DC"};
//TODO
}
}
else if(groupID==387 || groupID==599){
boxOrganizer = new String[]{ "MD"};
}
else if(groupID==827 || groupID==135){
//Diary- Motivation on after 7 days
if(seven_days_passed){
boxOrganizer = new String[]{"OG", "IR", "MD"};
//TODO
}
else{
boxOrganizer = new String[]{"MD"};
//TODO
}
}
else if(groupID/1000==9){
// precious_rule_system.precoiusinterface.PreciousApplicationActions.enableDisableSubapp(true, PreciousApplicationActions.SubAppKeys.IMPORTANCE_RULER);
boxOrganizer = PreciousApplicationActions.getBoxOrganizer();
}
else{
// addDivider("TEST");
boxOrganizer = new String[]{"SAD","WR","OG","IR","OAD","MF","TM","PA_SOC","FA","CR","SM","MD","DC","UP"};
// boxOrganizer = new String[]{"SAD","SM"};
// boxOrganizer = new String[]{"OG","IR","MF","TM","PA_SOC","FA","CR","SM","MD","DC","UP"};
}
gridLayout.removeAllViews();
Point size = new Point();
display.getSize(size);
LayoutWidth = size.x;
BoxMargins = LayoutWidth / 50;
LayoutWidth = LayoutWidth - 3 * BoxMargins;
gridLayout.setPadding(0, 0, BoxMargins / 2, BoxMargins);
gridLayout.setColumnCount(SB_cols);
gridLayout.setRowCount(SB_rows + 1);
gridLayout.setVerticalScrollBarEnabled(true);
SharedPreferences ui_preferences = mContext.getSharedPreferences(UI_PREFS_NAME, 0);
if(ui_preferences.getBoolean("OGset",false))
moveSBtoEnd("OG");
if(ui_preferences.getBoolean("IRset",false))
moveSBtoEnd("IR");
if(ui_preferences.getBoolean("PA_SOC_set",false))
moveSBtoEnd("PA_SOC");
if(ui_preferences.getBoolean("TM_set",false))
moveSBtoEnd("TM");
if(ui_preferences.getBoolean("FA_set",false))
moveSBtoEnd("FA");
if(ui_preferences.getBoolean("CR_set",false))
moveSBtoEnd("CR");
// moveSBtoEnd("DB");
SB_current_half_row=0;
SB_current_half_col=0;
for (int i=0; i<boxOrganizer.length;i++)
addView(boxOrganizer[i]);
//TODO for the app tutorial
// if(!ui_preferences.getBoolean("OGset",false) && groupID/1000==9 ) {
// try {
// Target target = new ViewTarget(R.id.OG_id, this);
// ShowcaseView.Builder res = new ShowcaseView.Builder(this, true)
// .setTarget(target)
// .setContentTitle("Hello! I am a Precious sample introduction text! Be like me!")
// .setContentText("");
// res.setStyle(R.style.CustomShowcaseTheme);
// res.build();
// } catch (Exception e) {
// Log.e(TAG, " ", e);
// }
// }
}
// /**
// *
// * @param text
// */
// public static void addDivider(String text){
// TextView tv = new TextView(mContext);
// tv.setText(text);
//
// GridLayout.LayoutParams param = new GridLayout.LayoutParams();
// param.height = LayoutWidth / SB_cols;
// param.width = (2 * LayoutWidth / SB_cols) + BoxMargins;
//
//
// param.setMargins(BoxMargins, BoxMargins, 0, 0);
//
// param.columnSpec = GridLayout.spec(0, 2);
// param.rowSpec = GridLayout.spec(SB_current_rows);
//
// param.setGravity(Gravity.CENTER);
// tv.setLayoutParams(param);
// gridLayout.addView(tv);
// SB_current_rows++;
// }
/**
*
* @param resourceID
* @param relativeWidth
* @param activity
*/
public static void addSBelement (int resourceID, int relativeWidth, final Class activity){
// Log.i(TAG,"Grid layout rows:"+gridLayout.getRowCount());
// Log.i(TAG,"SB_current_half_row:"+SB_current_half_row);
// Log.i(TAG,"SB_current_rows:"+SB_current_rows);
// Log.i(TAG,"addSBelement, "+resourceID+","+relativeWidth+" ");
ImageView im = new ImageView(mContext);
//im.setBackgroundColor(Color);
im.setImageResource(resourceID);
GridLayout.LayoutParams param = new GridLayout.LayoutParams();
if(activity==null)
param.height = LayoutWidth / SB_cols / 4;
else
param.height = LayoutWidth / SB_cols;
if(relativeWidth==2) {
param.width = (relativeWidth * LayoutWidth / SB_cols) + BoxMargins;
}
else {
param.width = (relativeWidth * LayoutWidth / SB_cols);
}
param.setMargins(BoxMargins, BoxMargins, 0, 0);
if(relativeWidth==2) {
param.columnSpec = GridLayout.spec(0, relativeWidth);
param.rowSpec = GridLayout.spec(SB_current_rows);
}
else{
param.columnSpec = GridLayout.spec(SB_current_half_col, relativeWidth);
param.rowSpec = GridLayout.spec(SB_current_half_row);
}
param.setGravity(Gravity.CENTER);
im.setLayoutParams(param);
//SBelements.add(im);
if(resourceID==R.drawable.outcome_goal_tut)
im.setId(R.id.OG_id_tut);
gridLayout.addView(im);
//Define location based on size of the element
if(relativeWidth==2) {
SB_current_rows++;
if(SB_current_half_col==0)
SB_current_half_row++;
}
if(relativeWidth==1){
if(SB_current_half_col==0){
SB_current_rows++;
SB_current_half_col=1;
}
else{
SB_current_half_row=SB_current_rows;
SB_current_half_col=0;
}
}
if(activity!=null){
//Set onClick event
im.setClickable(true);
im.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (activity.equals(FirstBeatAlbumActivity.class)) {
uploader.precious.comnet.aalto.upUtils.getBGimage("/data?key=BG2_REPORT_IMAGE&query=12", mContext);
} else {
Intent i = new Intent(v.getContext(), activity);
mContext.startActivity(i);
}
}
});
}
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
// try {
// client.connect();
// Action viewAction = Action.newAction(
// Action.TYPE_VIEW, // TODO: choose an action type.
// "Main Page", // TODO: Define a title for the content shown.
// // TODO: If you have web page content that matches this app activity's content,
// // make sure this auto-generated web page URL is correct.
// // Otherwise, set the URL to null.
// Uri.parse("http://host/path"),
// // TODO: Make sure this auto-generated app deep link URI is correct.
// Uri.parse("android-app://aalto.comnet.thepreciousproject/http/host/path")
// );
// AppIndex.AppIndexApi.start(client, viewAction);
// }catch (Exception e){
// Log.e(TAG,"",e);
// }
}
@Override
public void onStop() {
super.onStop();
// // ATTENTION: This was auto-generated to implement the App Indexing API.
// // See https://g.co/AppIndexing/AndroidStudio for more information.
// Action viewAction = Action.newAction(
// Action.TYPE_VIEW, // TODO: choose an action type.
// "Main Page", // TODO: Define a title for the content shown.
// // TODO: If you have web page content that matches this app activity's content,
// // make sure this auto-generated web page URL is correct.
// // Otherwise, set the URL to null.
// Uri.parse("http://host/path"),
// // TODO: Make sure this auto-generated app deep link URI is correct.
// Uri.parse("android-app://aalto.comnet.thepreciousproject/http/host/path")
// );
// AppIndex.AppIndexApi.end(client, viewAction);
// client.disconnect();
}
@Override
protected void onPause() {
//Store app usage
try {
SharedPreferences preferences_up = this.getSharedPreferences(UP_PREFS_NAME, 0);
int groupID = preferences_up.getInt("group_ID", -1);
sql_db.precious.comnet.aalto.DBHelper.getInstance().insertAppUsage(System.currentTimeMillis(), "ui_MainActivity, Group"+groupID, "onPause");
} catch (Exception e) {
Log.e(TAG, " ", e);
}
super.onPause();
}
public static void addView(String name){
switch (name){
case "OG": addSBelement (R.drawable.outcome_goal, 1, outcomegoal.precious.comnet.aalto.outcomegoal_activity.class);break;
case "OGtut": addSBelement (R.drawable.outcome_goal_tut, 1, outcomegoal.precious.comnet.aalto.outcomegoal_activity.class);break;
case "IR": addSBelement(R.drawable.importance_ruler, 1, importance_ruler.precious.comnet.aalto.ImportanceRulerActivity.class);break;
case "DC": addSBelement(R.drawable.diet_challenges, 1, diet_challenges.precious.comnet.aalto.fi.dc_MainActivity.class);break;
case "SM": addSBelement(R.drawable.self_monitoring, 2, activity_tracker.precious.comnet.aalto.MountainViewActivity.class);break;
case "MD": addSBelement(R.drawable.my_food_diary, 2, fd_MainActivity.class);break;
case "DB": addSBelement(R.drawable.debug, 1, ui.precious.comnet.aalto.precious.Timeline.class);break;
case "UP": addSBelement(R.drawable.uploader, 1, FirstBeatAlbumActivity.class);break;
case "PA_SOC": addSBelement(R.drawable.pa_soc, 1, pa_state_of_change.precious.comnet.aalto.pa_soc_activity.class);break;
case "TM": addSBelement(R.drawable.time_machine, 2,time_machine.precious.comnet.aalto.time_machine_activity.class);break;
case "FA": addSBelement(R.drawable.my_favourites, 1, my_favourites_activity.class);break;
case "CR": addSBelement(R.drawable.confidence_ruler, 1, confidence_ruler.precious.comnet.aalto.confidence_ruler_activity.class);break;
case "WR": addSBelement(R.drawable.wearable, 1, wearable.precious.comnet.aalto.WearableMainActivity.class);break;
case "SAD": addSBelement(R.drawable.suggested_apps, 2, null);break;
case "OAD": addSBelement(R.drawable.other_apps, 2, null);break;
default: break;
}
}
public static void moveSBtoEnd (String name){
switch (name){
case "OG":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("OG")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="OG";
}
break;
case "DC":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("DC")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="DC";
}
break;
case "IR":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("IR")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="IR";
}
break;
case "SM":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("SM")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="SM";
} break;
case "WR":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("WR")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="WR";
} break;
case "FA":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("FA")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="FA";
}break;
case "MD":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("MD")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="MD";
}break;
case "DB":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("DB")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="DB";
} break;
case "UP":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("UP")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="UP";
} break;
case "PA_SOC":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("PA_SOC")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="PA_SOC";
} break;
case "TM":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("TM")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="TM";
} break;
case "CR":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("CR")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="CR";
} break;
case "SAD":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("SAD")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="SAD";
} break;
case "OAD":
for(int i=0;i<boxOrganizer.length;i++)
if(boxOrganizer[i].equals("OAD")){
for(int j=i;j<boxOrganizer.length-1;j++)
boxOrganizer[j]=boxOrganizer[j+1];
boxOrganizer[boxOrganizer.length-1]="OAD";
} break;
default: break;
}
}
// /**
// *
// */
// public Point getDisplaySize(){
// Display display = getWindowManager().getDefaultDisplay();
// Point size = new Point();
// display.getSize(size);
// return size;
// }
// /**
// *
// */
// @Override protected void onActivityResult (int requestCode,
// int resultCode, Intent data){
// if (requestCode== ONBOARDING_RESULT_CODE && resultCode==RESULT_OK) {
// if(data.getExtras().getBoolean("close_activity")) {
// Log.i(TAG,"finished");
// finish();
// }
// }
// }
public Activity getActivity (){
return this;
}
public void askForPermissions() {
// Here, thisActivity is the current activity
Activity thisActivity = (Activity) this;
boolean hasPermission = (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if(hasPermission){
Log.i(TAG,"WRITE_EXTERNAL_STORAGE permission granted");
}
else{
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},EXT_STORAGE_PERMISSION
);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case EXT_STORAGE_PERMISSION: {
Log.i(TAG,"CHECK IF USER ACCEPTED EXT STORAGE PERMISSION");
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "USER ACCEPTED EXT STORAGE PERMISSION");
// permission was granted, yay! Do the
// contacts-related task you need to do.
} else {
Toast.makeText(this, getString(R.string.storage_permission_warning), Toast.LENGTH_LONG).show();
askForPermissions();
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
/**
*
*/
public static void startTutorial(){
if(showcaseView!=null)
showcaseView.hide();
showcaseView = new ShowcaseView.Builder((Activity)mContext,true)
// .withMaterialShowcase()
.setContentTitle(mContext.getString(R.string.tutorial_ui_part1_title))
.setContentText(mContext.getString(R.string.tutorial_ui_part1_content))
// .blockAllTouches()
// .setTarget(target)
.setStyle(R.style.ShowcaseTheme_very_dark)
.build();
showcaseView.setButtonText(mContext.getString(R.string.tutorial_ui_part1_button));
// new ShowcaseView.Builder(this, true) .setTarget(viewTarget) .build();
// showcaseView.setLayoutPosition(params);
// showcase = showcaseView;
showcaseView.show();
showcaseView.overrideButtonClick(new View.OnClickListener() {
int count1 = 0;
@Override
public void onClick(View v) {
count1++;
switch (count1) {
case 1:
gridLayout.removeAllViews();
addView("OGtut");
showcaseView.setButtonText(mContext.getString(R.string.tutorial_ui_part2_button));
showcaseView.setContentTitle(mContext.getString(R.string.tutorial_ui_part2_title));
showcaseView.setContentText(mContext.getString(R.string.tutorial_ui_part2_content));
showcaseView.setStyle(R.style.ShowcaseTheme_bit_dark);
break;
case 2:
showcaseView.setContentTitle(mContext.getString(R.string.tutorial_ui_part3_title));
showcaseView.setContentText(mContext.getString(R.string.tutorial_ui_part3_content));
Target target3 = new ViewTarget(R.id.OG_id_tut, (Activity)mContext);
showcaseView.setShowcase(target3, false);
showcaseView.hideButton();
showcaseView.setStyle(R.style.ShowcaseTheme_dark);
break;
case 3:
// SharedPreferences at_preferences = mContext.getSharedPreferences(UI_PREFS_NAME, 0);
// SharedPreferences.Editor editor = at_preferences.edit();
// editor.putBoolean("at_tutorial_completed",true);
// editor.apply();
initSandBox();
gridLayout.scrollTo(0,0);
showcaseView.hide();
break;
}
}
});
}
/**
* FOR THE JURNEY VIEW
*/
// convenience class for storing all kinds of instances
public class JourneyStore {
public Assets assets;
public DataManager data;
public SizeCalculator sizes;
public JourneyView journeyView;
public ui_MainActivity activity;
public JourneyStore(ui_MainActivity activity, Assets assets, SizeCalculator sizes) {
this.assets = assets;
this.data = null;
this.sizes = sizes;
this.activity = activity;
}
public void setDataManager(DataManager data) {
this.data = data;
}
public void setJourneyView(JourneyView view) { this.journeyView = view; data.getState().setJourneyView(view); }
public RecyclerView getRecyclerView() { return this.data.getState().getRecyclerView(); }
}
private static String jsonFile = "journey/journeyassets.json";
JourneyStore store;
protected void initJurneyView(){
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
SizeCalculator sizes = new SizeCalculator(this);
Assets assets = new Assets(this, jsonFile, sizes);
this.store = new ui_MainActivity.JourneyStore(this, assets, sizes);
DataManager data = new DataManager(this.store);
store.setDataManager(data);
this.setup();
}
private void setup() {
JourneyView view = new JourneyView(this, this.store);
LinearLayout ll_nv_journey_view = (LinearLayout) findViewById(R.id.ll_nv_journey_view);
ll_nv_journey_view.addView(view);
// setContentView(view);
}
/**
* For the reward system¿?
*/
// public void startPopupActivityForRewardEvent(RewardEvent e) {
//
// FragmentTransaction ft = getFragmentManager().beginTransaction();
// Fragment prev = getFragmentManager().findFragmentByTag("dialog");
// if (prev != null) {
// ft.remove(prev);
// }
// ft.addToBackStack(null);
//
// // Create and show the dialog.
// DialogFragment newFragment = JourneyRewardPopupDialog.newInstance(e);
// newFragment.show(ft, "dialog");
// }
}
| 5,892
|
https://github.com/walidbesrour/bazar-test-app/blob/master/app/build.gradle
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
bazar-test-app
|
walidbesrour
|
Gradle
|
Code
| 175
| 1,250
|
apply plugin: 'com.android.application'
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
defaultConfig {
applicationId "com.example.elbazar"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
android {
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dataBinding {
enabled = true
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:2.0.2'
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
implementation 'com.android.support:appcompat-v7:30.0.3'
//Android image slider
implementation 'com.github.smarteist:autoimageslider:1.4.0'
implementation 'com.github.smarteist:autoimageslider:1.3.9-appcompat'
//////
implementation 'com.github.bumptech.glide:glide:4.11.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0'
androidTestImplementation 'androidx.test:runner:1.1.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation project(':autoimageslider')
/////
implementation 'com.makeramen:roundedimageview:2.3.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//LoginButtons
implementation 'com.shaishavgandhi:login-buttons:1.0.0'
//facebook login
implementation 'com.facebook.android:facebook-login:[5,6)'
//google login
implementation 'com.google.android.gms:play-services-auth:18.1.0'
//noinspection GradleCompatible
implementation 'com.android.support:design:28.0.0'
implementation project(':floatingtextbutton')
//noinspection GradleCompatible
implementation 'com.android.support:support-v13:28.0.0'
// recyclerview dependency
implementation 'com.android.support:recyclerview-v7:30.0.0'
//dependency for circular imageview in android
implementation 'de.hdodenhof:circleimageview:3.1.0'
implementation 'com.squareup.picasso:picasso:2.71828'
//blur view
implementation 'com.eightbitlab:blurview:1.6.3'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
//The CardView
implementation 'com.android.support:cardview-v7:30.0.0'
//chip-navigation-bar
implementation 'com.ismaeldivita.chipnavigation:chip-navigation-bar:1.3.4'
implementation 'com.google.android.material:material:1.3.0-alpha03'
// implementation 'org.jetbrains.kotlin:kotlin-stdlib:$kotlinVersion:1.3.70'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation group: "pl.openrnd.android", name: "multi-level-listview", version: "1.0.1"
implementation 'com.github.dvinfosys:Navigation-ListView:1.0.0'
implementation project(path: ':navigationlistview')
implementation 'org.jetbrains.kotlin:kotlin-stdlib:1.3.72'
implementation 'com.android.support:support-core-utils:30.0.0'
implementation 'hyogeun.github.com.colorratingbar:ColorRatingBar:1.0.1'
implementation 'com.github.travijuu:numberpicker:1.0.7'
implementation 'com.github.dimorinny:floating-text-button:0.0.4'
}
| 2,960
|
https://github.com/garrettheel/aws-sdk-js-v3/blob/master/clients/client-mobile/index.ts
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
aws-sdk-js-v3
|
garrettheel
|
TypeScript
|
Code
| 48
| 129
|
export * from "./MobileClient";
export * from "./Mobile";
export * from "./commands/CreateProjectCommand";
export * from "./commands/DeleteProjectCommand";
export * from "./commands/DescribeBundleCommand";
export * from "./commands/DescribeProjectCommand";
export * from "./commands/ExportBundleCommand";
export * from "./commands/ExportProjectCommand";
export * from "./commands/ListBundlesCommand";
export * from "./commands/ListProjectsCommand";
export * from "./commands/UpdateProjectCommand";
export * from "./models/index";
| 50,944
|
https://github.com/ishanvyas22/asset-mix/blob/master/stubs/inertia-vue/webpack.mix.js
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
asset-mix
|
ishanvyas22
|
JavaScript
|
Code
| 32
| 174
|
const mix = require('laravel-mix');
const path = require('path');
mix.setPublicPath('./webroot')
.js('assets/js/app.js', 'webroot/js').vue()
.sass('assets/sass/app.scss', 'webroot/css')
.webpackConfig({
output: {
chunkFilename: 'js/[name].js?id=[chunkhash]'
},
resolve: {
alias: {
vue$: 'vue/dist/vue.runtime.esm.js',
'@': path.resolve('assets/js'),
},
},
})
.version()
.sourceMaps();
| 7,492
|
https://github.com/aboustayyef/lt/blob/master/app/Console/Commands/GetTweetDetails.php
|
Github Open Source
|
Open Source
|
MIT
| null |
lt
|
aboustayyef
|
PHP
|
Code
| 156
| 479
|
<?php namespace LebaneseTweets\Console\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class GetTweetDetails extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'lebaneseTweets:GetTweetDetails';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Gets the details of a single tweet from its ID';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$client = new \LebaneseTweets\Twitter\TweetsGetter;
$details = $client->getTweetDetails($this->argument('tweetID'));
$option = $this->option('detail');
if ($this->option('detail')) {
var_dump($details[0]->$option);
return;
}
var_dump($details);
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['tweetID', InputArgument::REQUIRED, 'Twitter Status id']
];
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return [
['detail', null, InputOption::VALUE_OPTIONAL, 'details wanted', null],
];
}
}
| 41,301
|
https://github.com/lemms/videofix/blob/master/src/classifiers/include/mlpclassifier.h
|
Github Open Source
|
Open Source
|
MIT
| null |
videofix
|
lemms
|
C
|
Code
| 339
| 942
|
// mlpclassifier.h
// Copyright Laurence Emms 2017
#ifndef MLP_CLASSIFIER
#define MLP_CLASSIFIER
#include <cmath>
#include <string>
#include <iostream>
#include <numeric>
#include <vector>
#include <random>
#include <fstream>
namespace classifiers
{
template <typename T, typename S = size_t>
class WeightLayer
{
public:
WeightLayer(const S rows, const S cols);
void set_value(const S i, const S j, const T value);
T get_value(const S i, const S j) const;
S get_rows() const;
S get_cols() const;
private:
std::vector<T> _weights;
const S _rows;
const S _cols;
};
template <typename T, typename S>
WeightLayer<T, S>::WeightLayer(const S rows, const S cols) : _rows(rows), _cols(cols)
{
_weights.resize(_rows * _cols, static_cast<T>(0));
}
template <typename T, typename S>
void WeightLayer<T, S>::set_value(const S i, const S j, const T value)
{
if (i < 0 || j < 0 || i >= _rows || j >= _cols)
{
std::cerr << "Error: Out of bounds set value " << i << ", " << j << "\n";
return;
}
_weights[j + i * _cols] = value;
}
template <typename T, typename S>
T WeightLayer<T, S>::get_value(const S i, const S j) const
{
if (i < 0 || j < 0 || i >= _rows || j >= _cols)
{
std::cerr << "Error: Out of bounds get value " << i << ", " << j << "\n";
return 0.0f;
}
return _weights[j + i * _cols];
}
template <typename T, typename S>
S WeightLayer<T, S>::get_rows() const
{
return _rows;
}
template <typename T, typename S>
S WeightLayer<T, S>::get_cols() const
{
return _cols;
}
// multi-layer perceptron classifier
class MLPClassifier
{
public:
MLPClassifier(bool verbose = false);
int num_layers() const;
int layer_size(int layer) const;
void init(const std::vector<int>& layer_counts, const float learning_rate = 0.1f, const float beta = 1.0f);
void train(const std::vector<float>& input, const std::vector<float>& target);
void classify(const std::vector<float>& input, std::vector<float>& output);
void feed_forward(const std::vector<float>& input);
void back_propagation(const std::vector<float>& target);
void get_output_layer(std::vector<float>& output);
void write(std::ofstream& stream) const;
void read(std::ifstream& stream);
private:
bool _verbose;
float _learning_rate;
float _beta;
std::vector<int> _layer_counts;
std::vector<WeightLayer<float, int>> _weights;
std::vector<std::vector<float>> _layers;
std::vector<std::vector<float>> _errors;
std::random_device _rd;
std::mt19937 _gen;
std::uniform_real_distribution<> _dist;
};
}
#endif // MLP_CLASSIFIER
| 48,682
|
https://github.com/isaveu/CSharpTcpNetworkDummy/blob/master/NPSBDummyLib/DummyManager.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
CSharpTcpNetworkDummy
|
isaveu
|
C#
|
Code
| 191
| 706
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace NPSBDummyLib
{
public partial class DummyManager
{
List<Dummy> DummyList = new List<Dummy>();
TestConfig Config = new TestConfig();
TestResultManager TestResultMgr = new TestResultManager();
bool InProgress;
public Action<string> LogFunc; //[진행중] [완료] [실패]
static Int64 CurrentConnectingCount = 0;
static public Int64 ConnectedDummyCount()
{
return CurrentConnectingCount;
}
static public void DummyConnected()
{
Interlocked.Increment(ref CurrentConnectingCount);
}
static public void DummyDisConnected()
{
Interlocked.Decrement(ref CurrentConnectingCount);
}
public bool Prepare(TestConfig config)
{
CurrentConnectingCount = 0;
DummyList.Clear();
Config = config;
for(int i = 0; i < Config.DummyCount; ++i)
{
var dummy = new Dummy();
dummy.Init(i);
DummyList.Add(dummy);
}
InProgress = true;
return false;
}
public void EndTest()
{
InProgress = false;
Thread.Sleep(2000);
for (int i = 0; i < Config.DummyCount; ++i)
{
if(DummyList[i] == null)
{
continue;
}
DummyList[i].DisConnect();
}
DummyList.Clear();
Config.ActionCase = TestCase.NONE;
}
public bool IsInProgress()
{
return InProgress;
}
public List<string> GetTestResult(Int64 testIndex )
{
return TestResultMgr.WriteTestResult(testIndex, Config);
}
public TestCase CurrentTestCase()
{
return Config.ActionCase;
}
// Host 프로그램에 메시지를 보낼 큐 혹은 델리게이트. 에러, 로그, 결과를 보냄
// Host 프로그램에서 메시지를 받을 큐 혹은 델리게이트. 중단 메시지를 받음
//System.Threading.Interlocked.Increment(ref ConnectedCount);
//System.Threading.Interlocked.Decrement(ref ConnectedCount);
//System.Threading.Interlocked.Read(ref ConnectedCount);
}
}
| 5,486
|
https://github.com/ahmadaldabouqii/tony_cafe/blob/master/src/wordpress/wp-content/plugins/woocommerce/packages/woocommerce-blocks/assets/js/base/components/cart-checkout/payment-method-icons/utils.ts
|
Github Open Source
|
Open Source
|
MIT
| null |
tony_cafe
|
ahmadaldabouqii
|
TypeScript
|
Code
| 139
| 323
|
/**
* External dependencies
*/
import type { PaymentMethodIcon } from '@woocommerce/type-defs/payment-method-icon';
import { isString } from '@woocommerce/types';
/**
* For an array of icons, normalize into objects and remove duplicates.
*/
export const normalizeIconConfig = (
icons: ( PaymentMethodIcon | string )[]
): PaymentMethodIcon[] => {
const normalizedIcons: Record< string, PaymentMethodIcon > = {};
icons.forEach( ( raw ) => {
let icon: Partial< PaymentMethodIcon > = {};
if ( typeof raw === 'string' ) {
icon = {
id: raw,
alt: raw,
src: null,
};
}
if ( typeof raw === 'object' ) {
icon = {
id: raw.id || '',
alt: raw.alt || '',
src: raw.src || null,
};
}
if ( icon.id && isString( icon.id ) && ! normalizedIcons[ icon.id ] ) {
normalizedIcons[ icon.id ] = <PaymentMethodIcon>icon;
}
} );
return Object.values( normalizedIcons );
};
| 46,412
|
https://github.com/jserot/rfsm-gui/blob/master/src/command.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
rfsm-gui
|
jserot
|
C++
|
Code
| 89
| 184
|
/**********************************************************************/
/* */
/* This file is part of the RFSM package */
/* */
/* Copyright (c) 2018-present, Jocelyn SEROT. All rights reserved. */
/* */
/* This source code is licensed under the license found in the */
/* LICENSE file in the root directory of this source tree. */
/* */
/**********************************************************************/
#include "command.h"
QString CommandLine::toString()
{
#ifdef Q_OS_WIN
QString cmdPath = cmd.contains(' ') ? "\"" + cmd + "\"" : cmd;
#else
QString cmdPath = cmd;
#endif
return cmdPath + " " + args;
}
| 4,008
|
https://github.com/gruntjs-updater/grunt-screencap/blob/master/tasks/screencap.js
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
grunt-screencap
|
gruntjs-updater
|
JavaScript
|
Code
| 118
| 354
|
/*
* grunt-screencap
* https://github.com/jehna/grunt-screencap
*
* Copyright (c) 2015 Jesse Luoto
* Licensed under the MIT license.
*/
'use strict';
module.exports = function(grunt) {
var desktopScreenshot = require('desktop-screenshot');
grunt.registerMultiTask('screencap', 'Take automatic screenshots with grunt (OSX only).', function() {
var options = this.options({
});
if (typeof options.output !== 'string') {
grunt.error('No \'output\' parameter defined. Exiting...');
return;
}
var filenameCorrection = /(.*)\.(png)?|(.*)/.exec(options.output);
filenameCorrection = filenameCorrection[1] ? filenameCorrection[1] : filenameCorrection[3];
var timestamp = new Date().getTime();
var filename = filenameCorrection + timestamp + '.png';
var done = this.async();
grunt.file.write(filename, ''); // Write empty file to make sure folder exists
desktopScreenshot(filename, function(error, complete) {
if (!error) {
console.log('Screenshot captured, filename: ' + filename);
} else {
console.error(error);
}
done();
});
});
};
| 19,282
|
https://github.com/kumasento/deacon/blob/master/src/com/custom_computing_ic/maxdeep/lib/stream/BaseStream.java
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
deacon
|
kumasento
|
Java
|
Code
| 206
| 734
|
package com.custom_computing_ic.maxdeep.lib.stream;
import com.maxeler.maxcompiler.v2.kernelcompiler.Kernel;
import com.maxeler.maxcompiler.v2.kernelcompiler.KernelBase;
import com.maxeler.maxcompiler.v2.kernelcompiler.types.base.DFEType;
import com.maxeler.maxcompiler.v2.kernelcompiler.types.base.DFEVar;
import com.maxeler.maxcompiler.v2.kernelcompiler.types.composite.DFEVector;
import com.maxeler.maxcompiler.v2.kernelcompiler.types.composite.DFEVectorType;
/**
* The base class for Stream
*
* @author Ruizhe Zhao
*
*/
public class BaseStream {
private final String name;
private final int vecSize;
private final DFEVar enable;
private final DFEType T;
private final DFEVectorType<DFEVar> vecT;
private DFEVector<DFEVar> placeholder;
private final boolean isInput;
public BaseStream(String name, int vecSize, DFEType T, DFEVar enable) {
this(name, vecSize, T, enable, true);
}
public BaseStream(String name, int vecSize, DFEType T, DFEVar enable,
boolean isInput) {
if (vecSize <= 0)
throw new IllegalArgumentException("vecSize should be larger than 0.");
this.name = name;
this.vecSize = vecSize;
this.T = T;
this.enable = enable;
this.vecT = new DFEVectorType<DFEVar>(T, vecSize);
this.isInput = isInput;
}
public String getName() {
return name;
}
public int getVecSize() {
return vecSize;
}
public DFEVar getEnable() {
return enable;
}
public DFEType getT() {
return T;
}
public DFEVectorType<DFEVar> getVecT() {
return vecT;
}
public DFEVector<DFEVar> getPlaceholder(KernelBase<?> owner) {
if (this.placeholder != null)
return this.placeholder;
this.placeholder = vecT.newInstance(owner);
return this.placeholder;
}
public void setIO(Kernel owner) throws RuntimeException {
owner.getManager().logMsg(String.format("setting IO for %s", name));
if (placeholder == null)
throw new RuntimeException("please initialise placeholder at first");
if (isInput)
placeholder.connect(owner.io.input(name, vecT, enable));
else
owner.io.output(name, vecT, enable).connect(placeholder);
}
}
| 50,198
|
https://github.com/plusxp/alibabacloud-sdk/blob/master/ecs-20140526/java/src/main/java/com/aliyun/ecs20140526/models/DescribeNetworkInterfacesRequest.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
alibabacloud-sdk
|
plusxp
|
Java
|
Code
| 153
| 616
|
// This file is auto-generated, don't edit it. Thanks.
package com.aliyun.ecs20140526.models;
import com.aliyun.tea.*;
public class DescribeNetworkInterfacesRequest extends TeaModel {
@NameInMap("RegionId")
@Validation(required = true)
public String regionId;
@NameInMap("Tag")
public java.util.List<DescribeNetworkInterfacesRequestTag> tag;
@NameInMap("ResourceGroupId")
public String resourceGroupId;
@NameInMap("VSwitchId")
public String vSwitchId;
@NameInMap("VpcId")
public String vpcId;
@NameInMap("PrimaryIpAddress")
public String primaryIpAddress;
@NameInMap("PrivateIpAddress")
public java.util.List<String> privateIpAddress;
@NameInMap("SecurityGroupId")
public String securityGroupId;
@NameInMap("NetworkInterfaceName")
public String networkInterfaceName;
@NameInMap("Type")
public String type;
@NameInMap("InstanceId")
public String instanceId;
@NameInMap("NetworkInterfaceId")
public java.util.List<String> networkInterfaceId;
@NameInMap("ServiceManaged")
public Boolean serviceManaged;
@NameInMap("Status")
public String status;
@NameInMap("PageNumber")
public Integer pageNumber;
@NameInMap("PageSize")
public Integer pageSize;
@NameInMap("NextToken")
public String nextToken;
@NameInMap("MaxResults")
public Integer maxResults;
public static DescribeNetworkInterfacesRequest build(java.util.Map<String, ?> map) throws Exception {
DescribeNetworkInterfacesRequest self = new DescribeNetworkInterfacesRequest();
return TeaModel.build(map, self);
}
public static class DescribeNetworkInterfacesRequestTag extends TeaModel {
@NameInMap("Key")
@Validation(required = true)
public String key;
@NameInMap("Value")
@Validation(required = true)
public String value;
public static DescribeNetworkInterfacesRequestTag build(java.util.Map<String, ?> map) throws Exception {
DescribeNetworkInterfacesRequestTag self = new DescribeNetworkInterfacesRequestTag();
return TeaModel.build(map, self);
}
}
}
| 43,975
|
https://github.com/sangramch/deepvideo/blob/master/modules/liteflownet/flow_loss.py
|
Github Open Source
|
Open Source
|
CC0-1.0
| 2,020
|
deepvideo
|
sangramch
|
Python
|
Code
| 246
| 915
|
# imports
import torch
import torch.nn as nn
from .network import LiteFlowNet
from modules.functional import epe_loss, cosine_loss
# Pre-trained LiteFlowNet Models
SIN = "./modules/liteflownet/saved_models/network-sintel.pytorch"
KIT = "./modules/liteflownet/saved_models/network-kitti.pytorch"
DEF = "./modules/liteflownet/saved_models/network-default.pytorch"
"""
LiteFlowNetLoss
Calculate MSE between estimated optical flow of hallucinated and input video frames
Args:
Refs:
https://arxiv.org/pdf/1805.07036.pdf
https://github.com/sniklaus/pytorch-liteflownet.git
https://github.com/twhui/LiteFlowNet
"""
class LiteFlowNetLoss(nn.Module):
def __init__(self, flow_model=SIN, flow_loss="EPE"):
super(LiteFlowNetLoss, self).__init__()
if not torch.cuda.is_available():
raise NotImplementedError("LiteFlowNet only implemented for CUDA")
# LiteFlowNet
self.flow_net = LiteFlowNet()
self.flow_net.load_model(save_loc=flow_model)
self.eval().cuda()
# Fix pre-trained weights
for param in self.parameters():
param.requires_grad = False
if flow_loss not in ["EPE", "COSINE"]:
raise KeyError("Specified flow loss; {}, is not currently supported!".format(flow_loss))
else:
self.flow_loss = flow_loss
def forward(self, inpt, target):
losses = []
if inpt.size() != target.size():
raise ValueError("Input and target sizes are not equal!")
# extract width and height
_, _, _, h, w = inpt.size()
# only implemented for CUDA
inpt = inpt.cuda()
targ = target.cuda()
inpt_flows = []
targ_flows = []
for i in range(inpt.size(2)-1):
# input & target flow
inpt_flow = self.flow_net(inpt[:, :, i], inpt[:, :, i+1])
targ_flow = self.flow_net(targ[:, :, i], targ[:, :, i+1])
inpt_flows.append(inpt_flow)
targ_flows.append(targ_flow)
inpt_flow = torch.stack(inpt_flows, dim=2)
targ_flow = torch.stack(targ_flows, dim=2)
# normalize flow in x and y directions
inpt_flow[:, 0] = inpt_flow[:, 0].clone() / h
inpt_flow[:, 1] = inpt_flow[:, 1].clone() / w
targ_flow[:, 0] = targ_flow[:, 0].clone() / h
targ_flow[:, 1] = targ_flow[:, 1].clone() / w
# calculate loss
if self.flow_loss == "EPE":
loss = epe_loss(inpt_flow, target=targ_flow, reduction="element_wise_mean")
elif self.flow_loss == "COSINE":
loss = cosine_loss(inpt_flow, target=targ_flow, reduction="element_wise_mean")
return loss
| 23,637
|
https://github.com/jsdelivrbot/Dependency-Graph/blob/master/server-side/java-callgraph/src/main/java/com/bighi/se/cg/bronkerbosch/Friend.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Dependency-Graph
|
jsdelivrbot
|
Java
|
Code
| 124
| 285
|
package com.bighi.se.cg.bronkerbosch;
import java.io.Serializable;
import java.util.HashMap;
public class Friend implements Comparable, Serializable {
// Basic Elements
public String name;
public String id;
// The value in each k-v pair here is the weight of the edge between
// this user and that friend.
// Weight is defined as Math.floor(1000 / (number of mutual friends + 1))
// where mutual friends = number of friends two users have in common in
// the graph.
public HashMap<Friend, Integer> friends;
public Friend() {
friends = new HashMap<Friend, Integer>();
}
@Override
public String toString() {
return null;
}
// Suitable as facebook IDs are unique
@Override
public int hashCode() {
return (Long.decode(id).hashCode());
}
@Override
public int compareTo(Object o) {
Friend friend = (Friend) o;
return this.id.compareTo(friend.id);
}
}
| 44,407
|
https://github.com/BuildingBridge/biznet/blob/master/bitrix/modules/intranet/lang/en/public_bitrix24/telephony/phones.php
|
Github Open Source
|
Open Source
|
Unlicense
| 2,020
|
biznet
|
BuildingBridge
|
PHP
|
Code
| 5
| 24
|
<?
$MESS["VI_PAGE_PHONES_TITLE"] = "Phones";
?>
| 47,252
|
https://github.com/JuKu/mmo-game-client/blob/master/game/src/main/java/com/jukusoft/mmo/client/game/MessageReceiver.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
mmo-game-client
|
JuKu
|
Java
|
Code
| 12
| 45
|
package com.jukusoft.mmo.client.game;
@FunctionalInterface
public interface MessageReceiver<T> {
public void receive(T buffer);
}
| 21,854
|
https://github.com/Pepperi-Addons/ngx-lib/blob/master/projects/ngx-lib/dialog/public-api.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
ngx-lib
|
Pepperi-Addons
|
TypeScript
|
Code
| 24
| 53
|
/*
* Public API Surface of ngx-lib/dialog
*/
export * from './dialog.module';
export * from './dialog.model';
export * from './dialog.component';
export * from './dialog.service';
| 7,257
|
https://github.com/tladesignz/DNATools/blob/master/tools/src/main/java/com/netzarchitekten/tools/Log.java
|
Github Open Source
|
Open Source
|
MIT
| null |
DNATools
|
tladesignz
|
Java
|
Code
| 1,687
| 3,956
|
/*
DNA Android Tools.
The MIT License (MIT)
Copyright (c) 2015 - 2017 Die Netzarchitekten e.U., Benjamin Erhart
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.netzarchitekten.tools;
import java.util.Locale;
import android.text.TextUtils;
/**
* <p>
* Logging helper which wraps {@link android.util.Log}.
* </p>
* <ul>
* <li>Allows consuming apps to control, which log levels are actually printed.
* </li>
* <li>Doesn't print anything in {@link #VERBOSE} and {@link #DEBUG} if
* {@code BuildConfig#DEBUG} is not true, meaning app is not in development
* mode.</li>
* <li>Log tag is automatically generated like this
* "com.example.CallingClass#callingMethod#123".</li>
* <li>Log message is wrapped in
* {@link String#format(Locale, String, Object...)}, where {@link Locale} is
* {@link Locale#US} per default, but can be changed.
* </ul>
*
* @author Benjamin Erhart {@literal <berhart@netzarchitekten.com>}
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public class Log {
/**
* Proxy for {@link android.util.Log#VERBOSE}.
*/
public static final int VERBOSE = android.util.Log.VERBOSE;
/**
* Proxy for {@link android.util.Log#DEBUG}.
*/
public static final int DEBUG = android.util.Log.DEBUG;
/**
* Proxy for {@link android.util.Log#INFO}.
*/
public static final int INFO = android.util.Log.INFO;
/**
* Proxy for {@link android.util.Log#WARN}.
*/
public static final int WARN = android.util.Log.WARN;
/**
* Proxy for {@link android.util.Log#ERROR}.
*/
public static final int ERROR = android.util.Log.ERROR;
/**
* Proxy for {@link android.util.Log#ASSERT}.
*/
public static final int ASSERT = android.util.Log.ASSERT;
/**
* Current log level.
*/
private static int sLogLevel = VERBOSE;
/**
* Current {@link Locale} to use in
* {@link String#format(Locale, String, Object...)}.
*/
private static Locale sLocale = Locale.US;
/**
* Set current log level. Every subsequent call with a lower log level will
* be ignored.
*
* @param level
* the new log level
*/
public static void setLogLevel(int level) {
sLogLevel = level;
}
/**
* <p>
* Returns the <em>real</em> log level: If we're not in debug mode, the log
* level cannot be lower than {@link #INFO}.
* </p>
* <p>
* All calls with a lower log level will be ignored.
* </p>
*
* @return the real current log level.
*/
@SuppressWarnings("unused")
public static int getLogLevel() {
if (!BuildConfig.DEBUG && sLogLevel < INFO) return INFO;
return sLogLevel;
}
/**
* <p>
* Set the {@link Locale}, which is used in
* {@link String#format(Locale, String, Object...)} calls to a given
* {@link Locale}.
* </p>
* <p>
* Default is {@link Locale#US}.
* </p>
* <p>
* You most probably should log in english, so as many IT people as possible
* can read this. But if you really really want to output your log messages
* in your native language or something - here's your chance to format the
* strings accordingly...
* </p>
*
* @param locale
* the new {@link Locale}
*/
public static void setLocale(Locale locale) {
sLocale = locale;
}
/**
* @return the current {@link Locale}, which is used in
* {@link String#format(Locale, String, Object...)} calls. Defaults
* to {@link Locale#US}.
*/
public static Locale getLocale() {
return sLocale;
}
/**
* Log a message with a given level. Use caller as log tag, format message
* with {@link String#format(Locale, String, Object...)}.
*
* @param level
* the log level
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#println(int, String, String)
*/
public static int println(int level, String msg, Object... args) {
if ((level > DEBUG || BuildConfig.DEBUG) && sLogLevel <= level)
return android.util.Log.println(level, getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log a message with level {@link #VERBOSE}, but only if we're running in
* development. Use caller as log tag, format message with
* {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#v(String, String)
*/
public static int v(String msg, Object... args) {
if (BuildConfig.DEBUG && sLogLevel <= VERBOSE)
return android.util.Log.v(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #VERBOSE}, but only if we're running
* in development.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#v(String, String, Throwable)
*/
public static int v(Throwable tr) {
if (BuildConfig.DEBUG && sLogLevel <= VERBOSE)
return android.util.Log.v(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Log a message with level {@link #DEBUG}, but only if we're running in
* development. Use caller as log tag, format message with
* {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#d(String, String)
*/
public static int d(String msg, Object... args) {
if (BuildConfig.DEBUG && sLogLevel <= DEBUG)
return android.util.Log.d(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #DEBUG}, but only if we're running in
* development.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#d(String, String, Throwable)
*/
public static int d(Throwable tr) {
if (BuildConfig.DEBUG && sLogLevel <= DEBUG)
return android.util.Log.d(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Log a message with level {@link #INFO}. Use caller as log tag, format
* message with {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#i(String, String)
*/
public static int i(String msg, Object... args) {
if (sLogLevel <= INFO)
return android.util.Log.i(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #INFO}.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#i(String, String, Throwable)
*/
public static int i(Throwable tr) {
if (sLogLevel <= INFO) return android.util.Log.i(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Log a message with level {@link #WARN}. Use caller as log tag, format
* message with {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#w(String, String)
*/
public static int w(String msg, Object... args) {
if (sLogLevel <= WARN)
return android.util.Log.w(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #WARN}.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#w(String, String, Throwable)
*/
public static int w(Throwable tr) {
if (sLogLevel <= WARN) return android.util.Log.w(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Log a message with level {@link #ERROR}. Use caller as log tag, format
* message with {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#e(String, String)
*/
public static int e(String msg, Object... args) {
if (sLogLevel <= ERROR)
return android.util.Log.e(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #ERROR}.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#e(String, String, Throwable)
*/
public static int e(Throwable tr) {
if (sLogLevel <= ERROR) return android.util.Log.e(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Log a message with level {@link #ASSERT}. Use caller as log tag, format
* message with {@link String#format(Locale, String, Object...)}.
*
* @param msg
* first argument of {@link String#format(String, Object...)}
* @param args
* additional arguments for
* {@link String#format(String, Object...)}
* @return the number of bytes written.
* @see android.util.Log#wtf(String, String)
*/
public static int wtf(String msg, Object... args) {
if (sLogLevel <= ASSERT)
return android.util.Log.wtf(getTag(), String.format(sLocale, msg, args));
return 0;
}
/**
* Log an exception with level {@link #ASSERT}.
*
* @param tr
* an exception to log
* @return the number of bytes written.
* @see android.util.Log#wtf(String, Throwable)
*/
public static int wtf(Throwable tr) {
if (sLogLevel <= ASSERT) return android.util.Log.wtf(getTag(), getMsg(tr), tr);
return 0;
}
/**
* Proxy to {@link android.util.Log#getStackTraceString(Throwable)}.
*
* @param tr
* an exception to log
* @return the number of bytes written.
*/
public static String getStackTrace(Throwable tr) {
return android.util.Log.getStackTraceString(tr);
}
/**
* Proxy to {@link android.util.Log#isLoggable(String, int)}. Use caller as
* log tag.
*
* @param level
* the level to check
* @return whether or not this is allowed to be logged.
*/
public static boolean isLoggable(int level) {
String tag = getTag();
// Avoid IllegalArgumentException in #isLoggable.
if (tag.length() > 23) tag = tag.substring(0, 23);
return android.util.Log.isLoggable(tag, level);
}
/**
* @return a String like "com.example.CallingClass#callingMethod#123".
*/
private static String getTag() {
StackTraceElement trace[] = Thread.currentThread().getStackTrace();
return trace[4].getClassName() + "#" + trace[4].getMethodName() + "#"
+ trace[4].getLineNumber();
}
/**
* @param tr
* an exception to log
* @return a proper error message from a {@link Throwable}.
*/
private static String getMsg(Throwable tr) {
return tr.getClass().getSimpleName()
+ (TextUtils.isEmpty(tr.getMessage()) ? "" : ": \"" + tr.getMessage() + "\"");
}
}
| 34,099
|
https://github.com/pm5/rocks/blob/master/lib/Rocks/Models/Event.pm
|
Github Open Source
|
Open Source
|
MIT-0
| null |
rocks
|
pm5
|
Perl
|
Code
| 87
| 238
|
package Rocks::Models::Event;
use Moo;
use Rocks::Base;
use Types::Standard qw[Str ArrayRef InstanceOf];
use Type::Params qw[compile];
use DateTime;
use namespace::autoclean;
has happened_at => ( is => "ro", isa => InstanceOf["DateTime"] );
has name => ( is => "ro", isa => Str );
has presentations => ( is => "ro", isa => ArrayRef[InstanceOf["Rocks::Models::Presentation"]] );
sub from_record ($class, $record)
{
$class->new(%$record);
}
sub add_presentation
{
state $check = compile(InstanceOf["Rocks::Models::Presentation"]);
my $self = shift;
my ($pres) = $check->(@_);
die "did not pass constraints" unless $pres->event == $self;
push @{$self->{presentations}}, $pres;
}
1;
| 41,176
|
https://github.com/Patbox/Creeperfall/blob/master/src/main/java/io/github/redstoneparadox/creeperfall/entity/CreeperfallCreeperEntity.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Creeperfall
|
Patbox
|
Java
|
Code
| 244
| 1,139
|
package io.github.redstoneparadox.creeperfall.entity;
import io.github.redstoneparadox.creeperfall.entity.ai.goal.CreeperfallFollowTargetGoal;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.ai.goal.CreeperIgniteGoal;
import net.minecraft.entity.ai.goal.FleeEntityGoal;
import net.minecraft.entity.ai.goal.LookAtEntityGoal;
import net.minecraft.entity.ai.goal.SwimGoal;
import net.minecraft.entity.damage.DamageSource;
import net.minecraft.entity.mob.CreeperEntity;
import net.minecraft.entity.mob.SkeletonEntity;
import net.minecraft.entity.passive.CatEntity;
import net.minecraft.entity.passive.OcelotEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
public class CreeperfallCreeperEntity extends CreeperEntity {
private final double multX;
private final double multZ;
private double fallSpeedMultiplier;
private int ticksUntilAutoIgnite = 3 * 20;
public CreeperfallCreeperEntity(World world, double fallSpeedMultiplier, double multX, double multZ) {
super(EntityType.CREEPER, world);
this.fallSpeedMultiplier = fallSpeedMultiplier;
this.experiencePoints = 0;
this.multX = multX;
this.multZ = multZ;
}
@Override
protected void initGoals() {
super.initGoals();
this.goalSelector.add(1, new SwimGoal(this));
this.goalSelector.add(2, new CreeperIgniteGoal(this));
this.goalSelector.add(3, new FleeEntityGoal<>(this, OcelotEntity.class, 6.0F, 1.0D, 1.2D));
this.goalSelector.add(3, new FleeEntityGoal<>(this, CatEntity.class, 6.0F, 1.0D, 1.2D));
this.goalSelector.add(6, new LookAtEntityGoal(this, PlayerEntity.class, 128.0F, 1.0f));
this.goalSelector.add(6, new LookAtEntityGoal(this, SkeletonEntity.class, 128.0f, 1.0f));
this.targetSelector.add(1, new CreeperfallFollowTargetGoal<>(
this,
PlayerEntity.class,
1,
true,
true,
livingEntity -> true
)
);
this.targetSelector.add(2, new CreeperfallFollowTargetGoal<>(
this,
SkeletonEntity.class,
1,
true,
true,
livingEntity -> true
)
);
}
@Override
public void setMovementSpeed(float movementSpeed) {
super.setMovementSpeed(movementSpeed * 1.15f);
}
@Override
public void tick() {
if (isOnGround()) {
setInvulnerable(true);
if (ticksUntilAutoIgnite > 0 && !this.isIgnited()) {
ticksUntilAutoIgnite -= 1;
}
else {
ignite();
}
}
else {
Vec3d velocity = getVelocity();
double value = ((double) this.age) / 10 + this.getId();
velocity = new Vec3d(velocity.x + Math.sin(value) * this.multX, velocity.y, velocity.z + Math.cos(value) * this.multZ);
setVelocity(velocity);
}
if (!isInvulnerable()) {
Vec3d velocity = getVelocity();
setVelocity(velocity.multiply(1.0, fallSpeedMultiplier, 1.0));
}
if (getY() <= 0) {
kill();
}
super.tick();
}
@Override
public boolean handleFallDamage(float fallDistance, float damageMultiplier, DamageSource damageSource) {
return false;
}
}
| 38,227
|
https://github.com/ceos-seo/Data_Cube_v2/blob/master/agdc-v2/datacube/ui/click.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
Data_Cube_v2
|
ceos-seo
|
Python
|
Code
| 595
| 2,118
|
# coding=utf-8
"""
Common functions for click-based cli scripts.
"""
from __future__ import absolute_import
import functools
import logging
import os
import re
import copy
import click
from datacube import config, __version__
from datacube.executor import get_executor
from datacube.index import index_connect
from pathlib import Path
from sqlalchemy.exc import OperationalError, ProgrammingError
_LOG_FORMAT_STRING = '%(asctime)s %(levelname)s %(message)s'
CLICK_SETTINGS = dict(help_option_names=['-h', '--help'])
def _print_version(ctx, param, value):
if not value or ctx.resilient_parsing:
return
click.echo(
'{prog}, version {version}'.format(
prog='Data Cube',
version=__version__
)
)
ctx.exit()
def compose(*functions):
"""
>>> compose(
... lambda x: x+1,
... lambda y: y+2
... )(1)
4
"""
def compose2(f, g):
return lambda x: f(g(x))
return functools.reduce(compose2, functions, lambda x: x)
class ColorFormatter(logging.Formatter):
colors = {
'info': dict(fg='white'),
'error': dict(fg='red'),
'exception': dict(fg='red'),
'critical': dict(fg='red'),
'debug': dict(fg='blue'),
'warning': dict(fg='yellow')
}
def format(self, record):
if not record.exc_info:
record = copy.copy(record)
record.levelname = click.style(record.levelname, **self.colors.get(record.levelname.lower(), {}))
return logging.Formatter.format(self, record)
class ClickHandler(logging.Handler):
def emit(self, record):
try:
msg = self.format(record)
click.echo(msg, err=True)
except (KeyboardInterrupt, SystemExit):
raise
except: # pylint: disable=bare-except
self.handleError(record)
def _init_logging(ctx, param, value):
handler = ClickHandler()
handler.formatter = ColorFormatter(_LOG_FORMAT_STRING)
logging.root.addHandler(handler)
logging_level = logging.WARN - 10 * value
logging.root.setLevel(logging_level)
logging.getLogger('datacube').setLevel(logging_level)
if not ctx.obj:
ctx.obj = {}
ctx.obj['verbosity'] = value
def _add_logfile(ctx, param, value):
formatter = logging.Formatter(_LOG_FORMAT_STRING)
for logfile in value:
handler = logging.FileHandler(logfile)
handler.formatter = formatter
logging.root.addHandler(handler)
def _log_queries(ctx, param, value):
if value:
logging.getLogger('sqlalchemy.engine').setLevel('INFO')
def _set_config(ctx, param, value):
if value:
if not any(os.path.exists(p) for p in value):
raise ValueError('No specified config paths exist: {}' % value)
paths = value
else:
paths = config.DEFAULT_CONF_PATHS
parsed_config = config.LocalConfig.find(paths=paths)
if not ctx.obj:
ctx.obj = {}
ctx.obj['config_file'] = parsed_config
#: pylint: disable=invalid-name
version_option = click.option('--version', is_flag=True, callback=_print_version,
expose_value=False, is_eager=True)
#: pylint: disable=invalid-name
verbose_option = click.option('--verbose', '-v', count=True, callback=_init_logging,
is_eager=True, expose_value=False, help="Use multiple times for more verbosity")
#: pylint: disable=invalid-name
logfile_option = click.option('--log-file', multiple=True, callback=_add_logfile,
is_eager=True, expose_value=False, help="Specify log file")
#: pylint: disable=invalid-name
config_option = click.option('--config_file', '-C', multiple=True, default='', callback=_set_config,
expose_value=False)
#: pylint: disable=invalid-name
log_queries_option = click.option('--log-queries', is_flag=True, callback=_log_queries,
expose_value=False, help="Print database queries.")
# This is a function, so it's valid to be lowercase.
#: pylint: disable=invalid-name
global_cli_options = compose(
version_option,
verbose_option,
logfile_option,
config_option,
log_queries_option
)
@click.group(help="Data Cube command-line interface", context_settings=CLICK_SETTINGS)
@global_cli_options
def cli():
pass
def pass_config(f):
"""Get a datacube config as the first argument. """
def new_func(*args, **kwargs):
config_ = click.get_current_context().obj['config_file']
return f(config_, *args, **kwargs)
return functools.update_wrapper(new_func, f)
def pass_index(app_name=None, expect_initialised=True):
"""Get a connection to the index as the first argument.
A short name name of the application can be specified for logging purposes.
"""
def decorate(f):
def with_index(*args, **kwargs):
ctx = click.get_current_context()
try:
index = index_connect(ctx.obj['config_file'],
application_name=app_name or ctx.command_path,
validate_connection=expect_initialised)
return f(index, *args, **kwargs)
except (OperationalError, ProgrammingError) as e:
handle_exception('Error Connecting to database: %s', e)
return functools.update_wrapper(with_index, f)
return decorate
def parse_endpoint(value):
ip, port = tuple(value.split(':'))
return ip, int(port)
EXECUTOR_TYPES = {
'serial': lambda _: get_executor(None, None),
'multiproc': lambda workers: get_executor(None, int(workers)),
'distributed': lambda addr: get_executor(parse_endpoint(addr), True)
}
def _setup_executor(ctx, param, value):
try:
return EXECUTOR_TYPES[value[0]](value[1])
except ValueError:
ctx.fail("Failed to create '%s' executor with '%s'" % value)
executor_cli_options = click.option('--executor',
type=(click.Choice(EXECUTOR_TYPES.keys()), str),
default=('serial', None),
help="Run parallelized, either locally or distrbuted. eg:\n"
"--executor multiproc 4 (OR)\n"
"--executor distributed 10.0.0.8:8888",
callback=_setup_executor)
def handle_exception(msg, e):
"""
Exit following an exception in a CLI app
If verbosity (-v flag) specified, dump out a stack trace. Otherwise,
simply print the given error message.
Include a '%s' in the message to print the single line message from the
exception.
:param e: caught Exception
:param msg: Message to User with optional %s
"""
ctx = click.get_current_context()
if ctx.obj['verbosity'] >= 1:
raise e
else:
if '%s' in msg:
click.echo(msg % e)
else:
click.echo(msg)
ctx.exit(1)
def to_pathlib(ctx, param, value):
if value:
return Path(value)
else:
return None
| 745
|
https://github.com/HJBowers/quick-bat/blob/master/command-line/1.1.1.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
quick-bat
|
HJBowers
|
Shell
|
Code
| 41
| 121
|
#identify the prompt, command, options, arguments, and cursor
[Projects]$ rm -f foo.txt
[Projects]$ rm -f foo.txt
//Prompt Command Option Argument Cursor
[~]$ cd ruby
[~]$ cd ruby
//Prompt Command Argument Cursor
[ruby]$ ls -a
[ruby]$ ls -a
//Prompt Command Option Cursor
| 4,680
|
https://github.com/KeyMaker13/portfolio/blob/master/documents/cFiles/advancedProgramming/Practice/fall2010MidtermOne.c
|
Github Open Source
|
Open Source
|
Zlib, Apache-2.0
| null |
portfolio
|
KeyMaker13
|
C
|
Code
| 306
| 888
|
#include <stdio.h>
#include "genlib.h"
#include "simpio.h"
//question1
double *MinMax(double minMax[], int numOfElements);
//question3
int IsVowel(char ch);
//int removeVowelArray(char s[]);
int removeVowelPointer(char *s);
main(int argc, char *argv[]){
//question1
double test[] = {6.5,2.0,4.4,8.1,3.3};
double *values;
values = MinMax(test, 5);
printf("The min is %lf the max is %lf",values[0],values[1]);
printf("\n");
int v = 14 % 5 / 3;
printf("%d",v);
//question3
//char s[] = {"xyabbAaaecccDEf"};
//int six = removeVowelArray(s);
//printf("removed %d vowels and the remaining string is %s",six,s);
//char testCh[] = {"test"};
//char *testingCh;
//char testingCh[] = {"testing"};
//testingCh = testCh;
//printf("new array is now %s ", testingCh);
//question 4
/*
while (--argc > 0 ){
printf("%s\n", *(argv+argc));
}
printf("%c\n", argv[0][5]);
printf("%c\n", *(argv[2]+3));
*/
}
//question 1
double *MinMax(double minMax[], int numOfElements){
double min = minMax[0], max = 0, temp;
static double r[2];
int i;
for (i = 1; i < numOfElements; i++){
if (max < minMax[i]){
max = minMax[i];
}
if (min > max){
temp = max;
max = min;
min = temp;
}
}
r[0] = min;
r[1] = max;
return r;
}
//question3
int IsVowel(char ch){
switch(ch){
case 'A': case 'E': case 'I': case 'O': case 'U':
case 'a': case 'e': case 'i': case 'o': case 'u':
return 1;
default:
return 0;
}
}
/*
int removeVowelArray(char s[])
{
int sizeOfS = 0;
int sizeOfV = 0;
int i =0;
while (s[i] != '\0'){
if (IsVowel(s[i]) == 1){
sizeOfV++;
}
i++;
}
sizeOfS= i;
char temp[sizeOfS - sizeOfV];
i = 0;
int tempc = 0;
while (s[i] != '\0'){
if (IsVowel(s[i]) == 0){
temp[tempc] = s[i];
tempc++;
}
i++;
}
i = 0;
while (temp[i] != '\0'){
s[i] = temp[i];
i++;
}
s[++i] = '\0';
return sizeOfV;
}
*/
int removeVowelPointer(char *s)
{
int r = 0, i = 0;
while (*(s+i) != '\0'){
if (IsVowel(*(s+i)) == 1){
*(s+i) = 'T';
r++;
}
i++;
}
return r;
}
| 9,365
|
https://github.com/leo365zhou/Akso/blob/master/AksoParenet/AksoDemo/src/main/java/com/akso/java8/defaultmethod/DefaultMethodTest.java
|
Github Open Source
|
Open Source
|
MIT
| null |
Akso
|
leo365zhou
|
Java
|
Code
| 20
| 64
|
package com.akso.java8.defaultmethod;
public class DefaultMethodTest {
public static void main(String[] args) {
MyClass test = new MyClass();
System.out.println(MyInterface1.getString());
}
}
| 31,218
|
https://github.com/EnsekiTT/atcoder/blob/master/ABC/abc069/a.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
atcoder
|
EnsekiTT
|
C++
|
Code
| 28
| 72
|
#include<iostream>
#include<string>
#include <algorithm>
using namespace std;
int main()
{
int n, m;
cin >> n >> m;
cout << (n-1) * (m-1) << endl;
return 0;
}
| 36,708
|
https://github.com/Irushinie/Krish-LP-Training/blob/master/petsclinic-service/src/pets/pets.controller.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Krish-LP-Training
|
Irushinie
|
TypeScript
|
Code
| 118
| 442
|
import { Body, Controller, Delete, Get, HttpCode, NotFoundException, Param, Post, Put, Query, UsePipes, ValidationPipe } from '@nestjs/common';
import { PetCreateDto } from './PetCreate.dto';
import { PetsService } from './pets.service';
import { PetSearchDto } from './PetSearch.dto';
import { PetUpdateDto } from './PetUpdate.dto';
@Controller('pets')
export class PetsController {
constructor(private petService: PetsService) {
}
@Get()
getAllPets(@Query() param: PetSearchDto) {
if (Object.keys(param).length) {
return this.petService.petSearch(param)
} else {
return this.petService.getAllPets()
}
}
@Post()
@UsePipes(ValidationPipe)
createPets(@Body() petCreateDto: PetCreateDto) {
return this.petService.createPet(petCreateDto)
}
@Get('/:pid')
getEmployeeById(@Param('pid') pid: number) {
return this.petService.getPetById(pid);
}
@Put('/:pid/petage')
updatePet(@Param('pid') pid: number, @Body() petUpdateDto: PetUpdateDto) {
petUpdateDto.pid = pid;
return this.petService.updatePet(petUpdateDto)
}
@Delete('/:pid')
@HttpCode(204)
deletePet(@Param('pid') pid: number) {
if (this.petService.deletePet(pid)) {
throw new NotFoundException('Pet Does not exist ')
}
}
}
| 40,167
|
https://github.com/dzakwanzaky/kursusOnline/blob/master/resources/views/murid/header1.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
kursusOnline
|
dzakwanzaky
|
PHP
|
Code
| 273
| 1,138
|
<!-- Navbar -->
<link rel="stylesheet" href="{{asset('/ya')}}/bootstrap/css/bootstrap.min.css">
<style type="text/css">
.h6 {
text-align: center;
margin-top: 15px;
font-color: #6c757d;
}
.modall-title {
margin-left: 8em;
}
@media screen and (width: 375px) {
.modall-title {
margin-left: 5em;
}
}
@media screen and (width: 360px) {
.modall-title {
margin-left: 4em;
}
}
@media screen and (width: 320px) {
.modall-title {
margin-left: 3em;
}
}
@media screen and (width: 414px) {
.modall-title {
margin-left: 6em;
}
}
@media screen and (width: 411px) {
.modall-title {
margin-left: 6em;
}
}
@media screen and (width: 568px) {
.modall-title {
margin-left: 9em;
}
}
</style>
<nav class="main-header navbar navbar-expand navbar-white navbar-light border-bottom">
<!-- Left navbar links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" data-widget="pushmenu" href="#"><i class="fas fa-bars"></i></a>
</li>
</ul>
<!-- Right navbar links -->
<ul class="navbar-nav ml-auto">
<!-- Messages Dropdown Menu -->
<!-- Notifications Dropdown Menu -->
<li class="nav-item dropdown">
<a class="nav-link" data-toggle="dropdown" href="#">
<i class="far fa-user"></i>
<span>Halo, {{DB::table('users')->where('id','=', Auth::user()->id)->value('name')}}</span>
</a>
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-right">
<a href="/profileMurid" class="dropdown-item">
<i class="fas fa-user"></i> Profil
</a>
<a href="/changePasswordMurid" class="dropdown-item">
<i class="fas fa-edit"></i> Ubah Kata Sandi
</a>
<a href="/pilihMetode" class="dropdown-item">
<i class="fas fa-shopping-cart"></i> Beli Kelas Baru
</a>
<a href="/" class="nav-link btn-login; dropdown-item" data-toggle="modal" data-target="#exampleModal">
<i class="fas fa-sign-out-alt"></i> Keluar
</a>
<form id="logout-form" action="{{ url('/logout') }}" method="POST" style="display: none;">
{{ csrf_field() }}
</form>
</li>
</ul>
</nav>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modall-title" id="exampleModalLabel">Konfirmasi Aksi</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6 class="h6" style="color: #2c3034">Anda yakin <br>ingin keluar dari akun Anda ?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Batal</button>
<button type="button" class="btn btn-primary" onclick="event.preventDefault();
document.getElementById('logout-form').submit();">Yakin</button>
</div>
</div>
</div>
</div>
<script src="{{asset('/ya')}}/bootstrap/js/bootstrap.min.js"></script>
<!-- /.navbar -->
| 43,465
|
https://github.com/Arslan-Soomro/merakiui/blob/master/components/ui/FAQ/Centered.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
merakiui
|
Arslan-Soomro
|
Vue
|
Code
| 630
| 2,688
|
<template>
<view-component :name="name" :code="code">
<div class="py-6" slot="component">
<section class="bg-white dark:bg-gray-900">
<div class="container max-w-4xl px-6 py-10 mx-auto">
<h1 class="text-4xl font-semibold text-center text-gray-800 dark:text-white">Frequently asked questions</h1>
<div class="mt-12 space-y-8">
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">How i can play for my appoinment ?</h1>
<span class="text-gray-400 bg-gray-200 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 12H6" />
</svg>
</span>
</button>
<hr class="border-gray-200 dark:border-gray-700">
<p class="p-8 text-sm text-gray-500 dark:text-gray-300">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Voluptas eaque nobis, fugit odit omnis fugiat deleniti animi ab maxime cum laboriosam recusandae facere dolorum veniam quia pariatur obcaecati illo ducimus?
</p>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">Is the cost of the appoinment covered by private health insurance?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">Do i need a referral?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">What are your opening house?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">What can i expect at my first consultation?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
</div>
</div>
</section>
</div>
</view-component>
</template>
<script>
export default {
data() {
return {
name: 'Centered',
code: `
<section class="bg-white dark:bg-gray-900">
<div class="container max-w-4xl px-6 py-10 mx-auto">
<h1 class="text-4xl font-semibold text-center text-gray-800 dark:text-white">Frequently asked questions</h1>
<div class="mt-12 space-y-8">
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">How i can play for my appoinment ?</h1>
<span class="text-gray-400 bg-gray-200 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18 12H6" />
</svg>
</span>
</button>
<hr class="border-gray-200 dark:border-gray-700">
<p class="p-8 text-sm text-gray-500 dark:text-gray-300">
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Voluptas eaque nobis, fugit odit omnis fugiat deleniti animi ab maxime cum laboriosam recusandae facere dolorum veniam quia pariatur obcaecati illo ducimus?
</p>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">Is the cost of the appoinment covered by private health insurance?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">Do i need a referral?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">What are your opening house?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
<div class="border-2 border-gray-100 rounded-lg dark:border-gray-700">
<button class="flex items-center justify-between w-full p-8">
<h1 class="font-semibold text-gray-700 dark:text-white">What can i expect at my first consultation?</h1>
<span class="text-white bg-blue-500 rounded-full">
<svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
</svg>
</span>
</button>
</div>
</div>
</div>
</section>`
}
}
}
</script>
| 20,009
|
https://github.com/Jbjbot/Equanim/blob/master/web/app/themes/equanim/templates/404.twig
|
Github Open Source
|
Open Source
|
MIT
| null |
Equanim
|
Jbjbot
|
Twig
|
Code
| 57
| 247
|
{% extends "base.twig" %}
{% block content %}
<article class="page-404" itemscope itemtype="https://schema.org/WebPage">
<section class="section__container">
<div class="section__wrapper">
<div class="section__content">
<h1 class="section__h1" itemprop="headline">{{__('404 erreur', 'jb-starter-theme')}}</h1>
<div class="section__body">
<div class="alert alert-danger" role="alert">
{{__('Désolé, nous ne pouvons trouver ce que vous cherchez.', 'jb-starter-theme')}}
</div>
<a href="/">{{__('Retour à l\'accueil', 'jb-starter-theme')}}</a>
</div>
</div>
</div>
</section><!-- /section -->
</article><!-- /article -->
{% endblock %}
| 756
|
https://github.com/wj008t/php-beacon/blob/master/widget/Button.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
php-beacon
|
wj008t
|
PHP
|
Code
| 102
| 298
|
<?php
namespace beacon\widget;
use beacon\core\Field;
#[\Attribute]
class Button extends Field
{
protected array $_attrs = [
'class' => 'form-btn'
];
public bool $offJoin = true;
/**
* @param array $args
* @return void
*/
public function setting(array $args): void
{
parent::setting($args);
$this->offJoin = true;
}
protected function code(array $attrs = []): string
{
if (empty($attrs['href'])) {
$attrs['href'] = 'javascript:;';
}
unset($attrs['name']);
return static::makeTag('a', ['attrs' => $attrs, 'text' => $this->label]);
}
public function fromParam(array $param = []): mixed
{
return $this->getValue();
}
public function fromData(array $data = []): mixed
{
return $this->getValue();
}
public function joinData(array &$data = []): void
{
}
}
| 6,471
|
https://github.com/zoli-fischer/o3-cms/blob/master/theme/templates/controllers/o3_cms_template_update_payment.php
|
Github Open Source
|
Open Source
|
MIT
| null |
o3-cms
|
zoli-fischer
|
PHP
|
Code
| 89
| 356
|
<?php
//Require theme controller class
require_once(O3_CMS_THEME_DIR.'/classes/snapfer_template_controller.php');
class o3_cms_template_update_payment extends snapfer_template_controller {
public function init() {
//parent init
parent::init( func_get_args() );
}
//update payment
public function ajax_update_method() {
//check if user logged and he/she is the sender
if ( $this->logged_user()->validate_ajax( $this->ajax_result ) ) {
//check where to send the user after payment added
$redirect_url = !$this->logged_user()->has_payment() ? $this->o3_cms()->page_url( HOME_PAGE_ID ) : $this->o3_cms()->page_url( SUBSCRIPTION_PAGE_ID );
//if payment method updated send success
if ( $this->logged_user()->update_payment( $this->ajax_result->value('type'), $this->ajax_result->value('cardnumber') ) ) {
//redirect
$this->ajax_result->redirect( $redirect_url );
//set success
$this->ajax_result->success();
}
}
}
}
?>
| 49,603
|
https://github.com/michaelmuenzer/skybookmarks/blob/master/src/website-scraper/lib/filename-generator/by-type.js
|
Github Open Source
|
Open Source
|
MIT
| null |
skybookmarks
|
michaelmuenzer
|
JavaScript
|
Code
| 177
| 550
|
import _, { map, includes } from 'lodash';
import { join, basename as _basename } from 'path';
import sanitizeFilename from 'sanitize-filename';
import { shortenFilename, getFilenameExtension, getFilenameFromUrl } from '../utils';
import typeExtensions from '../config/resource-ext-by-type';
export default function generateFilename (resource, {subdirectories, defaultFilename}, occupiedFileNames) {
const occupiedNames = getSubDirectoryNames({subdirectories}).concat(occupiedFileNames);
let filename = getFilenameForResource(resource, {subdirectories, defaultFilename});
filename = shortenFilename(sanitizeFilename(filename, {replacement: '_'}));
const extension = getFilenameExtension(filename);
const directory = getDirectoryByExtension(extension, {subdirectories, defaultFilename});
let currentFilename = join(directory, filename);
const basename = _basename(filename, extension);
let index = 1;
while (occupiedNames.includes(currentFilename)) {
currentFilename = join(directory, `${basename}_${index}${extension}`);
index++;
}
return currentFilename;
};
function getFilenameForResource (resource, {defaultFilename}) {
const preferredFilename = resource.getFilename();
const urlFilename = getFilenameFromUrl(resource.getUrl());
let filename = preferredFilename || urlFilename || defaultFilename;
const resourceType = resource.getType();
let extension = getFilenameExtension(filename);
if (!extension && typeExtensions[resourceType]) {
extension = typeExtensions[resourceType][0];
filename += extension;
}
return filename;
}
function getSubDirectoryNames ({subdirectories}) {
return map(subdirectories, function getDirectory (directory) { return directory.directory; });
}
function getDirectoryByExtension (extension, {subdirectories}) {
return _(subdirectories)
.filter(function matchesExtension (directory) { return includes(directory.extensions, extension); })
.map(function getDirectory (directory) { return directory.directory; })
.first() || '';
}
| 8,975
|
https://github.com/Karthik-Ragunath/DDU/blob/master/data/fast_mnist.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
DDU
|
Karthik-Ragunath
|
Python
|
Code
| 107
| 375
|
"""
FastMNIST taken from: https://gist.github.com/y0ast/f69966e308e549f013a92dc66debeeb4
"""
import torch
from torchvision.datasets import MNIST
device = torch.device("cuda" if torch.cuda.is_available else "cpu")
class FastMNIST(MNIST):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Scale data to [0,1]
self.data = self.data.unsqueeze(1).float().div(255)
# Normalize it with the usual MNIST mean and std
self.data = self.data.sub_(0.1307).div_(0.3081)
# Put both data and targets on GPU in advance
self.data, self.targets = self.data.to(device), self.targets.to(device)
def __getitem__(self, index):
"""
Args:
index (int): Index
Returns:
tuple: (image, target) where target is index of the target class.
"""
img, target = self.data[index], self.targets[index]
return img, target
def create_MNIST_dataset():
train_dataset = FastMNIST("data", train=True, download=True)
test_dataset = FastMNIST("data", train=False, download=True)
return train_dataset, test_dataset
| 17,000
|
https://github.com/jonatanlaksamana/simplecrudLaravel/blob/master/resources/views/welcome.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
simplecrudLaravel
|
jonatanlaksamana
|
PHP
|
Code
| 147
| 741
|
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<title>UjiCoba</title>
</head>
<body>
<div class="container">
<h3 class="text-center my-5"> Simple CRUD (Create Read Update Delete)</h3>
<form method="post" action="{{route('add.book')}}">
@csrf
<div class="container">
<div class="form-group">
<div class="row">
<div class="col-1">
<p class="lead">Name:</p>
</div>
<div class="col-4">
<input name="title" type="text" name="title" class="form-control" >
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-1">
<p class="lead">Rating:</p>
</div>
<div class="col-4">
<input name="rating" type="number" name="rating" class="form-control">
</div>
</div>
</div>
<div class="form-group">
<input name="submit" type="submit" class="btn btn-success" value="Submit!!!">
</div>
</div>
</form>
<table class="table">
<thead>
<tr>
<th scope="col">id</th>
<th scope="col">title</th>
<th scope="col">Rating</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
@foreach($books as $book)
<tr>
<th scope="row">{{$book->id}}</th>
<td>{{$book->name}}</td>
<td>{{$book->rating}}</td>
<td>
<form method="post" action="{{url('/delete/' . $book->id)}}">
@csrf
<input type="submit" class="btn btn-danger btn-sm" value="remove">
</form>
<a href="{{url('/edit/' . $book->id)}}" type="submit" class="btn btn-primary btn-sm" >Edit </a>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</body>
</html>
| 5,819
|
https://github.com/rimalim2009/Odaka_DNN_inverse_2011_tsunami/blob/master/6GS_Odaka_DNN_Tsunami_inverse_Sampling_window 1000-1900_rw2200_gsroundrev.py
|
Github Open Source
|
Open Source
|
MIT
| null |
Odaka_DNN_inverse_2011_tsunami
|
rimalim2009
|
Python
|
Code
| 20,000
| 94,014
|
#!/usr/bin/env python # coding: utf-8 # # SW 1100 # In[1]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1100_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1100) # In[2]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1100_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1100_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[3]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1100_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1100_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1100_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1100_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] y2= test_result_normal[:, i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1100_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1100_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1100_2_TC_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.show() # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1100_2_TC_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1000_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1000_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1000_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1000_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1000_2.csv',estimated_dep_5000,delimiter=',') estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1100_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1100_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1100_2.pdf") plt.show() # In[4]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1100_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1100_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1100_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1100_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1100_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1200 # In[1]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1200_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1200) # In[2]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # # # # Display Result # In[3]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # # Determining standard devieation from residual value # In[4]: from scipy.stats import variation import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) resi = test_result - icond titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation:', np.std(resi[:,i])) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('CV:', np.std(resi[:,i],ddof=1)/np.mean(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2000,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2000,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y2= test_result_normal[:, i] y=test_result_normal[:,i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1200_2_TC_5000_odaka_cubic_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.show() # # Thickness # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1200_2_TC_5000_odaka_cubic_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1200_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1200_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1200_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1200_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1200_2.csv',estimated_dep_5000,delimiter=',') #data_estim=pd.DataFrame(estimated_dep_5000,columns=['distance','1.5phi','2.5phi','3.5phi','4.5phi']) #Formatting the loaded data #estimated_dep_df = pd.DataFrame(estimated_dep,columns=['distance','1.5phi','2.5phi','3.5phi','4.5phi']) #estimated_dep = pd.DataFrame(np.array([x_bed - dist_offset,H1[-1,:],H2[-1,:],H3[-1,:]]).T,columns=['distance','500micron','125micron','63micron']) estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #outcrop = pd.read_csv('../DeepLearningTurbidite_Fukuda/GA_naruse_v2.csv') #outcrop = outcrop.append(pd.DataFrame([[0,'Loc0',0,0,0],[dist_max,'LocE',0,0,0]], columns=outcrop.columns)) #outcrop = outcrop.sort_values('distance') #outcrop['distance'] = outcrop['distance'] - 1000 #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1200_2_5000.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1200_2_5000.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1200_2_5000_2.pdf") plt.show() # In[1]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1200_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1200_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1200_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1200_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1200_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1300 # In[9]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1300_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1300) # In[10]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[11]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # # Determining standard devieation from residual value # In[12]: from scipy.stats import variation import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) resi = test_result - icond titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation:', np.std(resi[:,i])) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('CV:', np.std(resi[:,i],ddof=1)/np.mean(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[5]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] y2= test_result_normal[:, i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[6]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1300_2_TC_cubic_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.show() # # Thickness # In[7]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1300_2_TC_cubic_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1300_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1300_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1300_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1300_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1300_2.csv',estimated_dep_5000,delimiter=',') estimated_dep_5000= estimated_dep_5000.query('distance > 0') #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1300_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1300_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1300_2.pdf") plt.show() # In[1]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1300_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1300_2_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1300_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1300_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1300_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1400 # In[17]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1400_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1400) # In[18]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # # # # Display Result # In[19]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # # Determining standard devieation from residual value # In[20]: from scipy.stats import variation import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) resi = test_result - icond titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation:', np.std(resi[:,i])) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('CV:', np.std(resi[:,i],ddof=1)/np.mean(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #ipdb.set_trace() #Kriging Interpolation by #vparams = np.array([[0.035, 10000., 0.001],[0.006, 10000., 0.002],[0.005, 10000., 0.002],[0.035, 10000., 0.001]]) #for j in range(gclass): #okip = OK(outcrop['distance'],np.zeros(outcrop['distance'].shape),outcrop.iloc[:,j+1],variogram_model='linear',) #okip.display_variogram_model() #ipdata, ipstd = okip.execute('grid',x,np.array([0.])) #ipdata = np.squeeze(ipdata) #thick_interp[0,coord_num*j:coord_num*(j+1)] = ipdata #Assign complemented d #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] y2= test_result_normal[:, i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1400_2_TC_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) plt.legend() plt.show() # # Thickness # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_rw2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1400_2_TC_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1400_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1400_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1400_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1400_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1400_2.csv',estimated_dep_5000,delimiter=',') estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1400_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1400_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1400_2.pdf") plt.show() # # Jackknife and Jackknife Standard error # In[4]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1400_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1400_2_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ['841','595','420','297','210','149'] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1400_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1400_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1400_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1600 # In[4]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1600_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1600) # In[5]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1600_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1600_2_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # # # # Display Result # In[6]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1600_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1600_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # # Determining standard devieation from residual value # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1600_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1600_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #ipdb.set_trace() #Kriging Interpolation by #vparams = np.array([[0.035, 10000., 0.001],[0.006, 10000., 0.002],[0.005, 10000., 0.002],[0.035, 10000., 0.001]]) #for j in range(gclass): #okip = OK(outcrop['distance'],np.zeros(outcrop['distance'].shape),outcrop.iloc[:,j+1],variogram_model='linear',) #okip.display_variogram_model() #ipdata, ipstd = okip.execute('grid',x,np.array([0.])) #ipdata = np.squeeze(ipdata) #thick_interp[0,coord_num*j:coord_num*(j+1)] = ipdata #Assign complemented d #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] y2= test_result_normal[:, i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1600_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1600_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1600_2_TC_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.show() # # Thickness # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1600_2_TC_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1600_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1600_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1600_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1600_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1600_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1600_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1600_2.pdf") plt.show() # In[4]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1600_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1600_2_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1600_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1600_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1600_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1700 # In[12]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1700_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1700) # In[13]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1700_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1700_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[14]: from scipy.stats import variation import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1700_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1700_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) resi = test_result - icond titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation:', np.std(resi[:,i])) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('CV:', np.std(resi[:,i],ddof=1)/np.mean(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1700_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1700_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #ipdb.set_trace() #Kriging Interpolation by #vparams = np.array([[0.035, 10000., 0.001],[0.006, 10000., 0.002],[0.005, 10000., 0.002],[0.035, 10000., 0.001]]) #for j in range(gclass): #okip = OK(outcrop['distance'],np.zeros(outcrop['distance'].shape),outcrop.iloc[:,j+1],variogram_model='linear',) #okip.display_variogram_model() #ipdata, ipstd = okip.execute('grid',x,np.array([0.])) #ipdata = np.squeeze(ipdata) #thick_interp[0,coord_num*j:coord_num*(j+1)] = ipdata #Assign complemented d #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2000,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2000,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1700_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1700_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) #add=np.array(3000) #test_result_outcrop_add=np.concatenate((add,test_result_outcrop), axis=None) #Output results #print(test_result_outcrop_add) np.savetxt('outcrop_result_g6_g300_j2_roi1700_2_TC_cubic_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.legend() plt.show() # # Thickness # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1700_2_TC_cubic_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1700.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1700.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1700.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1700.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1700.csv',estimated_dep_5000,delimiter=',') estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1700.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1700.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1700.pdf") plt.show() # In[1]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1700_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1700_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 #gclass_label = ["406 ${\mu}m$", "268 ${\mu}m$", #"177 ${\mu}m$", "117 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1700_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1700_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5jk','$C_6$jk'] jk_er=[] with open('jk_e_1700_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1800 (TN) # In[23]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1800_2_TC_odaka_2_TN" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1800) # In[24]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1800_2_TC_odaka_2_TN/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1800_2_TC_odaka_2_TN/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [500,1000,2000,3000,4000,5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # # SW 1000 # In[26]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1000_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1000) # In[27]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1000_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1000_2_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[28]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1000_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1000_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1000_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1000_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label =["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[20250,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] y2= test_result_normal[:, i] max_value = np.max([x, y, y2]) min_value = np.min([x, y, y2]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[ ]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1000_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1000_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gname_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) #add=np.array(3000) #test_result_outcrop_add=np.concatenate((add,test_result_outcrop), axis=None) #Output results #print(test_result_outcrop_add) np.savetxt('outcrop_result_g6_g300_j2_roi1000_2_TC_cubic_odaka_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') for i in range(gclass): plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.legend() plt.show() # # Thickness # In[2]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi1000_2_TC_cubic_odaka_2rev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1000_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1000_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1800_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1800_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi1000_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1000_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi1000_2.pdf") plt.show() # In[3]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1000_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1000_2_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1000_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1000_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5$jk','$C_6$jk'] jk_er=[] with open('jk_e_1000_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 1900 # In[3]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi1900_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=1900) # In[4]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1900_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1900_2_TC_odaka_2/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[5]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1900_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1900_2_TC_odaka_2/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[4]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats import ipdb #ipdb.set_trace() datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1900_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1900_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) #gclass = 3 #gclass_label = ["500 $\mu$m","125 $\mu$m","63 $\mu$m"] gclass = 6 gclass_name=['841','595','420','297','210','149'] gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 print(thick_interp) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)], label='estimated') for j in range(gclass): plt.plot(x,X_test_norm[0,j * coord_num : (j+1) * coord_num],'o',label='test') #plt.plot(outcrop['distance'], thick_interp_at_outcrop[0,outcrop_num*j:outcrop_num*(j+1)],'o',label='test') plt.plot() plt.legend() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # # DNN Inverse model final result # In[5]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1900_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1900_2_TC_odaka_2/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') #Read outcrop data #dist_max = 22000. #Distance of distal end of learning data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi1900_2_TC_cubic_2rev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) plt.legend() plt.show() # In[1]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi1900_2_TC_odaka_2/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi1900_2_TC_odaka_2/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi1900_TC_6_2rev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi1900_TC_6_2rev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5jk','$C_6$jk'] jk_er=[] with open('jk_e_1900_j2_6_2rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 2000 # In[14]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi2000_TC_odaka" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=2000) # In[15]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') # plt.show() def test_model(model, x_test): #Test the results x_test_norm = get_normalized_data(x_test, min_x, max_x) test_result_norm = model.predict(x_test_norm) test_result = get_raw_data(test_result_norm, min_y, max_y) return test_result def save_result(savedir, model, history, test_result): np.savetxt(savedir + 'test_result.txt',test_result,delimiter=',') np.savetxt(savedir+'loss.txt',history.history.get('loss'),delimiter=',') np.savetxt(savedir+'val_loss.txt',history.history.get('val_loss'),delimiter=',') #Serialize model and save print('save the model') model.save(savedir + 'model3.hdf5') def load_data(datadir): """ This function load training and test data sets, and returns variables """ global min_x, max_x, min_y, max_y x_train = np.loadtxt(datadir + 'x_train.txt',delimiter=',') x_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_train = np.loadtxt(datadir + 'icond_train.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') min_y = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') max_y = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') [min_x, max_x] = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') return x_train, y_train, x_test, y_test def set_minmax_data(_min_x, _max_x, _min_y, _max_y): global min_x, max_x, min_y, max_y min_x, max_x, min_y, max_y = _min_x, _max_x, _min_y, _max_y return def get_normalized_data(x, min_val, max_val): """ Normalizing the training and test dataset """ x_norm = (x - min_val) / (max_val - min_val) return x_norm def get_raw_data(x_norm, min_val, max_val): """ Get raw data from the normalized dataset """ x = x_norm * (max_val - min_val) + min_val return x if __name__ == "__main__": #Reading data datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi2000_TC_odaka/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi2000_TC_odaka/' if not os.path.exists(resdir): os.mkdir(resdir) x_train, y_train, x_test, y_test = load_data(datadir) #Execution of learning testcases = [5000] for i in range(len(testcases)): resdir_case = resdir + '{}/'.format(testcases[i]) if not os.path.exists(resdir_case): os.mkdir(resdir_case) x_train_sub = x_train[0:testcases[i],:] y_train_sub = y_train[0:testcases[i],:] model, history = deep_learning_tsunami(resdir_case, x_train_sub, y_train_sub, x_test, y_test, num_layers=5) #Verify and save results result = test_model(model, x_test) save_result(resdir_case,model,history,result) # In[1]: import numpy as np import matplotlib.pyplot as plt import ipdb get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi2000_TC_odaka/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi2000_TC_odaka/5000/' test_result = np.loadtxt(resdir + 'test_result.txt',delimiter=',') icond = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') print(icond.shape) loss = np.loadtxt(resdir+'loss.txt',delimiter=',') epoch = range(0,2000) vloss = np.loadtxt(resdir+'val_loss.txt',delimiter=',') resi = test_result - icond fig = plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(epoch, loss, 'bo',label='Loss') plt.plot(epoch, vloss, 'yo',label='Validation') plt.xlabel('Epoch') plt.ylabel('Mean Squared Error') plt.legend(loc="upper right") plt.savefig(resdir+ 'mse.pdf') plt.show() fig2 = plt.figure() hfont = {'fontname':'Century Gothic'} textcol = 'k' titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', '$C_1$', '$C_2$', '$C_3$', '$C_4$','$C_5$','$C_6$'] xymin=[2200,2.0,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(icond[:,i],test_result[:,i],"o",markersize = 2.5) x=icond[:,i] y=test_result[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') #plt.plot([xymin[i],xymax[i]],[xymin[i],xymax[i]],"-",color = 'k') plt.axes().set_aspect('equal') #plt.ylim(xymin[i],xymax[i]) #plt.xlim(xymin[i],xymax[i]) plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.xlabel('Original Value',color=textcol,size=14,**hfont) plt.ylabel('Estimated Value',color=textcol,size=14,**hfont) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + '.eps') plt.savefig(resdir+titlelabel[i] + '.pdf') #plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist' + '.pdf') plt.show() # In[1]: import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb from scipy import stats datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi2000_TC_odaka/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi2000_TC_odaka/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') # Load test datasets X_test = np.loadtxt(datadir + 'x_test.txt',delimiter=',') y_test = np.loadtxt(datadir + 'icond_test.txt',delimiter=',') # Normalize the test datasets min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') X_test_norm = (X_test - min_x) / (max_x - min_x) gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # Load outcrop data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 outcrop_num = len(outcrop['distance']) print(outcrop) #Preparation under interpolation thick_interp_at_outcrop = np.zeros([X_test.shape[0],outcrop_num*gclass]) thick_interp = np.zeros([X_test.shape[0],coord_num*gclass])#Interpolated sample thickness data outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #Index number of sampling point in inverse analysis system x = np.arange(0,coord_num*topodx,topodx) # Interpolation of test datasets at the outcrop locations for i in range(X_test.shape[0]): for j in range(gclass): f = interp1d(x,X_test_norm[i,j * coord_num : (j+1) * coord_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp_at_outcrop[i,outcrop_num*j:outcrop_num*(j+1)] = f(outcrop['distance']) #Supplemented data # Interpolation of test datasets at the grids of the forward model for j in range(gclass): f = interp1d(outcrop['distance'],thick_interp_at_outcrop[i,j * outcrop_num : (j+1) * outcrop_num], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[i,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 #Perform inverse analysis test_result_outcrop = model.predict(thick_interp) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_location_interp.txt',test_result_outcrop, delimiter=',') test_result=np.loadtxt('outcrop_location_interp.txt', delimiter=',') test_result_normal = np.loadtxt(resdir + 'test_result.txt',delimiter=',') resi=test_result-y_test titlelabel = ['Max Inundation Length','Flow Velocity', 'Max. Flow Depth', 'C_1', 'C_2', 'C_3', 'C_4','C_5','C_6'] hfont = {'fontname':'Century Gothic'} textcol = 'k' xymin=[2200,1.5,1.5,0.0001,0.0001,0.0001,0.0001,0.0001,0.0001] xymax=[4500,10.0,12.0,0.02,0.02,0.02,0.02,0.02,0.02] xstep=[500,1.5,1.5,0.005,0.005,0.005,0.005,0.005,0.005] stepmin=[2200,1.0,2.0,0.000,0.0000,0.0000,0.0000,0.0000,0.0000] stepmax=[4550,10.5,13.0,0.025,0.025,0.025,0.025,0.025,0.025] for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.plot(y_test[:,i],test_result[:,i],"o", markersize=4.5) plt.plot(y_test[:,i],test_result_normal[:,i],"*",label='estimate',markersize=3.5) x=y_test[:,i] y=test_result_normal[:,i] max_value = np.max([x, y]) min_value = np.min([x, y]) y_lim = plt.ylim([min_value * 0.8, max_value * 1.1]) x_lim = plt.xlim([min_value * 0.8, max_value * 1.1]) plt.plot(x_lim, y_lim, 'k-', color = 'k') plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('True values',color=textcol,size=14,**hfont) plt.ylabel('Estimated values',color=textcol,size=14,**hfont) plt.legend() plt.axes().set_aspect('equal') plt.xticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) plt.yticks(np.arange(stepmin[i],stepmax[i], step=xstep[i])) #plt.plot(x_lim, y_lim, color = 'k') plt.tick_params(labelsize=14,colors='k') plt.savefig(resdir+titlelabel[i] + 'outcrop_location' + '.pdf') plt.show() for i in range(len(titlelabel)): plt.figure(num=None,dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:,i],bins=20) print('Standard Deviation sample:', np.std(resi[:,i],ddof=1)) print('Mean:', np.mean(resi[:,i])) print('mode',stats.mode(resi[:,i])) print('m',np.median(resi[:,i])) plt.title(titlelabel[i],color=textcol,size=14,**hfont) plt.xlabel('Deviation from true value',color=textcol,size=14,**hfont) plt.ylabel('Frequency',color=textcol,size=14,**hfont) plt.tick_params(labelsize=14,colors=textcol) plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.eps') plt.savefig(resdir+titlelabel[i] + 'hist_outcrop_location' + '.pdf') plt.show() # In[2]: import numpy as np import matplotlib.pyplot as plt from tensorflow.keras.models import load_model from scipy import stats from scipy.interpolate import interp1d import pandas as pd from pykrige import OrdinaryKriging as OK import ipdb datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi2000_TC_odaka/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi2000_TC_odaka/5000/' #Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 gclass_label = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) #Acquires a value for normalizing input data to [0, 1] min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt',delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt',delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt',delimiter=',') # outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop = outcrop.sort_values('distance') outcrop['distance'] = outcrop['distance'] - 0 print(outcrop) #Preparation under interpolation thick_interp = np.zeros([1,coord_num*gclass])#補間されたサンプル厚さデータ outcrop_x_id = np.round(outcrop['distance']/topodx).astype(np.int32) #逆解析システムでのサンプリング地点のindex番号 x = np.arange(0,coord_num*topodx,topodx) #Complement data for j in range(gclass): f = interp1d(outcrop['distance'],outcrop.iloc[:,j+1], kind="cubic",bounds_error=False,fill_value='extrapolate') thick_interp[0,coord_num*j:coord_num*(j+1)] = f(x) #Supplemented data #Normalize data thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) #Perform inverse analysis test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop) np.savetxt('outcrop_result_g6_g300_j2_roi2000_2_TCrev.txt',test_result_outcrop, delimiter=',') for i in range(len(gclass_label)): plt.plot(x,thick_interp[0,coord_num * i:coord_num * (i+1)],label=gclass_label[i]) plt.legend() plt.show() # In[3]: import numpy as np import matplotlib.pyplot as plt import pandas as pd import Forward_model_for_DNN_J2_odaka_GS_round2200 as fmodel import time import ipdb get_ipython().run_line_magic('matplotlib', 'inline') #Basic setting #dist_max = 3000. gclass = 6 topodx=15.0 gname_tex = ["841 ${\mu}m$","595 ${\mu}m$","420 ${\mu}m$","297 ${\mu}m$", "210 ${\mu}m$","149 ${\mu}m$"] gclass_name=['841','595','420','297','210','149'] estimated_icond=np.loadtxt('outcrop_result_g6_g300_j2_roi2000_2_TCrev.txt', delimiter=',') start = time.time() fmodel.read_setfile("config_g6_300grid_j2_gs_round.ini") (x,C,x_dep,deposit) = fmodel.forward(estimated_icond) np.savetxt('eta_estimated_thickness_5K_g6_j2_roi1000_2.csv', deposit, delimiter=',') np.savetxt('eta_estimated_Distance_5K_g6_j2_roi1000_2.csv', x_dep,delimiter=',') estimated_dep_thickness_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_thickness_5K_g6_j2_roi1000_2.csv', delimiter=',')) estimated_dep_thickness_5000=pd.DataFrame(estimated_dep_thickness_5000,columns=['841','595','420','297','210','149']) estimated_dep_distance_5000=np.transpose(np.loadtxt('/home/rimali2009/Journal_2/'+'eta_estimated_Distance_5K_g6_j2_roi1000_2.csv', delimiter=',')) estimated_dep_distance_5000=pd.DataFrame(estimated_dep_distance_5000,columns=['distance']) estimated_dep_5000=pd.concat([estimated_dep_distance_5000,estimated_dep_thickness_5000],axis=1) np.savetxt('estimated_dep_5K_g6_j2_roi1000_2.csv',estimated_dep_5000,delimiter=',') estimated_dep_5000= estimated_dep_5000.query('distance > 0') #estimated_dep_5000 = estimated_dep_5000.query('distance < {}'.format(dist_max)) #Read original data outcrop = pd.read_csv('../Journal_2/odaka_increased_class_edit3.csv') outcrop= pd.DataFrame(outcrop,columns=['distance','841','595','420','297','210','149']) #Plot plt.figure(num=None, figsize=(17, 4), dpi=250, facecolor='w', edgecolor='g') hfont = {'fontname':'Sans'} plt.subplots_adjust(bottom=0.15, wspace=0.8) for i in range(gclass): plt.subplot(1,gclass,i+1) plt.plot(estimated_dep_5000['distance'],estimated_dep_5000[gclass_name[i]],'-', label='Estimated') plt.plot(outcrop['distance'], outcrop[gclass_name[i]],'o', label='Measured') plt.yscale('log') #plt.ylim([0.000001,1]) plt.title(gname_tex[i], size=21,**hfont) plt.xlabel('Distance (m)', size = 14, **hfont) plt.ylabel('Volume per unit area (m)', size = 14, **hfont) plt.legend(fontsize=10) plt.savefig("thickness_distance_curve_5000_g6_j2_roi2000_2.png") plt.savefig("thickness_distance_curve_5000_g6_j2_roi2000_2.eps") plt.savefig("thickness_distance_curve_5000_g6_j2_roi2000_2.pdf") plt.show() # In[1]: # Jackknife Method import csv import numpy as np import pandas as pd import math from keras.models import load_model from scipy.interpolate import interp1d import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') datadir = '/home/rimali2009/Journal_2/data_g6_j2_roi2000_TC_odaka/' resdir = '/home/rimali2009/Journal_2/result_g6_j2_roi2000_TC_odaka/5000/' # Initial setting if not "model" in locals(): model = load_model(resdir+'model3.hdf5') gclass = 6 topodx = 15.0 coord_num = int(model.layers[0].input_shape[1]/gclass) min_x, max_x = np.loadtxt(datadir + 'x_minmax.txt', delimiter=',') y_min = np.loadtxt(datadir + 'icond_min.txt', delimiter=',') y_max = np.loadtxt(datadir + 'icond_max.txt', delimiter=',') a = pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', delimiter=',') print(a) y = pd.DataFrame() output = [] with open('output_final_j2_roi2000_TCrev.csv', 'w') as outfile: # x=[] for index in range(len(a)): df = y.append(pd.read_csv( '../Journal_2/odaka_increased_class_edit3.csv', skiprows=[index+1])) print(df) df = df.sort_values('distance') thick_interp = np.zeros([1, coord_num*gclass]) x = np.arange(0, coord_num*topodx, topodx) for j in range(gclass): # Interpolation function of jth granularity level f = interp1d(df['distance'], df.iloc[:, j+1], kind="cubic", bounds_error=False,fill_value='extrapolate') thick_interp[0, coord_num*j:coord_num*(j+1)] = f(x) thick_interp[thick_interp < 0] = 0 thick_interp_norm = (thick_interp - min_x) / (max_x - min_x) test_result_outcrop = model.predict(thick_interp_norm) test_result_outcrop = test_result_outcrop * (y_max - y_min) + y_min print(test_result_outcrop.shape) print(test_result_outcrop) # output.append(test_result_outcrop) np.savetxt(outfile,test_result_outcrop, delimiter=',') # outfile.write('# New iteration\n') hfont = {'fontname': 'Century Gothic'} textcol = 'k' resi = np.loadtxt('output_final_j2_roi2000_TCrev.csv', delimiter=',') titlelabel = ['Max. Inundation Lengthjk','Flow Velocityjk', 'Max Flow depthjk', '$C_1$jk', '$C_2$jk', '$C_3$jk', '$C_4$jk','$C_5jk','$C_6$jk'] jk_er=[] with open('jk_e_2000_j2_6rev.txt','wb') as ftext: for i in range(len(titlelabel)): plt.figure(num=None, dpi=250, facecolor='w', edgecolor='k') plt.hist(resi[:, i], bins=35) mean = sum(resi[:,i]) / len(resi[:,i]) print("mean:",mean) var_jk = sum(pow(x-mean,2) for x in resi[:,i]) / ((len(resi[:,i])-1)*(len(resi[:,i]))) jk_e= math.sqrt(var_jk) #ci_u=mean+(1.96*jk_e) #ci_l=mean-(1.96*jk_e) CI=(1.96*jk_e) print("jk_e:",jk_e) #print("CI_u", ci_u) #print("CI_l",ci_l) print("CI",CI) e=np.append(jk_e,jk_er) np.savetxt(ftext,e,delimiter=',') plt.title(titlelabel[i], color=textcol, size=14, **hfont) plt.xlabel('Data from jackknife', color=textcol, size=14, **hfont) plt.ylabel('Frequency', color=textcol, size=14, **hfont) plt.tick_params(labelsize=14, colors=textcol) plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.eps') plt.savefig(resdir+titlelabel[i] + 'jkhist' + '.pdf') plt.show() # # SW 2100 # In[46]: import numpy as np import os #import ipdb def connect_dataset(file_list, icond_file_list, outputdir, topodx=15, roi=2500, offset=5000,gclass_num=6,test_data_num=500): """ 複数のデータセットを連結する """ #ipdb.set_trace() #Reading and combining files Decide start and end points of the learning area and convert them to grid numbers H = np.loadtxt(file_list[0], delimiter = ',') icond = np.loadtxt(icond_file_list[0], delimiter = ',') #Reading and combining files if len(file_list) > 1: for i in range(1, len(file_list)): H_temp = np.loadtxt(file_list[i], delimiter = ',') icond_temp = np.loadtxt(icond_file_list[i], delimiter = ',') H = np.concatenate((H,H_temp),axis=0) icond = np.concatenate((icond,icond_temp),axis = 0) roi_grids = int(roi / topodx) num_grids = int(H.shape[1] / gclass_num) H_subset = np.zeros([H.shape[0], roi_grids * gclass_num]) for i in range(gclass_num): H_subset[:, i*roi_grids:(i+1)*roi_grids] = H[:, i*num_grids:(i*num_grids+roi_grids)] #Obtain the maximum and minimum values of data max_x = np.max(H_subset) min_x = np.min(H_subset) icond_max = np.max(icond, axis=0) icond_min = np.min(icond, axis=0) #Split the data into tests and training H_train = H_subset[0:-test_data_num,:] H_test = H_subset[H_subset.shape[0] - test_data_num:,:] icond_train = icond[0:-test_data_num,:] icond_test = icond[H.shape[0] - test_data_num:,:] #Save the data if not os.path.exists(outputdir): os.mkdir(outputdir) np.savetxt(outputdir + '/x_train.txt',H_train,delimiter = ',') np.savetxt(outputdir + '/x_test.txt',H_test,delimiter = ',') np.savetxt(outputdir + '/icond_train.txt',icond_train,delimiter = ',') np.savetxt(outputdir + '/icond_test.txt',icond_test,delimiter = ',') np.savetxt(outputdir + '/icond_min.txt',icond_min,delimiter = ',') np.savetxt(outputdir + '/icond_max.txt',icond_max,delimiter = ',') np.savetxt(outputdir + '/x_minmax.txt',[min_x, max_x],delimiter = ',') if __name__=="__main__": original_data_dir = "/home/rimali2009/Journal_2" parent_dir = "/home/rimali2009/Journal_2" if not os.path.exists(parent_dir): os.mkdir(parent_dir) outputdir = parent_dir + "/data_g6_j2_roi2100_2_TC_odaka_2" file_list = ['/home/rimali2009/Journal_2/eta_5000_g6_300grid_j2_odaka_round_2200.csv'] initial_conditions = ['/home/rimali2009/Journal_2/start_param_random_5000_j2_odaka_round_2200.csv'] connect_dataset(file_list, initial_conditions, outputdir, test_data_num=500, gclass_num=6, topodx=15., roi=2100) # In[47]: # -*- coding: utf-8 -*- """ Created on Tue Mar 7 15:43:18 2017 @author: hanar """ import time import numpy as np import os from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense, Activation, Dropout from keras.optimizers import SGD from keras.optimizers import RMSprop from keras.optimizers import Adagrad from keras.optimizers import Adadelta from keras.optimizers import Adam from keras.optimizers import Adamax from keras.optimizers import Nadam from keras.callbacks import ModelCheckpoint from keras.callbacks import EarlyStopping from keras.callbacks import TensorBoard from keras.models import load_model #from keras.utils.visualize_util import plot import matplotlib.pyplot as plt import keras.callbacks import keras.backend.tensorflow_backend as KTF import tensorflow as tf #Global variables for normalizing parameters max_x = 1.0 min_x = 0.0 max_y = 1.0 min_y = 0.0 def deep_learning_tsunami(resdir, X_train_raw, y_train_raw, X_test_raw, y_test_raw, _lr=0.02, _decay=0, _validation_split=0.2, _batch_size=32, _momentum=0.9, _nesterov=True, num_layers=4, dropout=0.5, node_num = 2500, _epochs=2000): """ Creating the inversion model of turbidity currents by deep learning """ #Normalizing dataset X_train = get_normalized_data(X_train_raw, min_x, max_x) X_test = get_normalized_data(X_test_raw, min_x, max_x) y_train = get_normalized_data(y_train_raw, min_y, max_y) y_test = get_normalized_data(y_test_raw, min_y, max_y) #Generation of neural network model model = Sequential() model.add(Dense(node_num, input_dim=X_train.shape[1], activation='relu', kernel_initializer ='glorot_uniform'))#1st layer model.add(Dropout(dropout)) for i in range(num_layers - 2): model.add(Dense(node_num, activation='relu', kernel_initializer ='glorot_uniform'))#2nd layer model.add(Dropout(dropout)) model.add(Dense(y_train.shape[1], activation = 'relu', kernel_initializer ='glorot_uniform')) #last layer #Compiling the model model.compile(loss="mean_squared_error", optimizer=SGD(lr=_lr, decay=_decay, momentum=_momentum, nesterov=_nesterov), #optimizer=Adadelta(), metrics=["mean_squared_error"]) #Perform learning t = time.time() check = ModelCheckpoint("model3.hdf5") #es_cb = EarlyStopping(monitor='val_loss', patience=5, verbose=0, mode='auto') #tb_cb = TensorBoard(log_dir=resdir, histogram_freq=2, write_graph=True, write_images=True) history = model.fit(X_train, y_train, epochs=_epochs, validation_split=_validation_split, batch_size=_batch_size, callbacks=[check]) #Evaluate learning result loss_and_metrics = model.evaluate(X_test,y_test) print("\nloss:{} mse:{}".format(loss_and_metrics[0],loss_and_metrics[1])) print("Elapsed time: {:.1f} sec.".format(time.time()-t)) #Visualize learning result #plot(model, to_file="model.png", show_shapes=True, show_layer_names=True) # model The state of change when letting you learnplot plot_history(history) return model, history def apply_model(model, X, min_x, max_x, min_y, max_y): """ Apply model Maximum and minimum values of X and Y are required to normalize """ X_norm = (X - min_x) / (max_x - min_x) Y_norm = model.predict(X_norm) Y = Y_norm*(max_y - min_y)+min_y return Y def plot_history(history): # Plot accuracy history plt.plot(history.history['mean_squared_error'],"o-",label="mse") plt.plot(history.history['val_mean_squared_error'],"o-",label="val mse") plt.title('model mse') plt.xlabel('epoch') plt.ylabel('mse') plt.legend(loc="upper right") plt.show() # # 損失の履歴をプロット # plt.plot(history.history['loss'],"o-",label="loss",) # plt.plot(history.history['val_loss'],"o-",label="val_loss") # plt.title('model loss') # plt.xlabel('epoch') # plt.ylabel('loss') # plt.legend(loc='upper right') #
| 13,709
|
https://github.com/andrewdouglas/PipeBandGames/blob/master/PipeBandGames.ConsoleUI/MainMenu.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,017
|
PipeBandGames
|
andrewdouglas
|
C#
|
Code
| 81
| 204
|
using PipeBandGames.ConsoleUI.Commands;
namespace PipeBandGames.ConsoleUI
{
public sealed class MainMenu : Menu
{
public MainMenu()
{
this.Description = "Main menu";
this.MenuItems.Add(new MenuItem { Command = 'd', Text = "Data entry", Action = NoopCommand.Noop });
this.MenuItems.Add(new MenuItem { Command = 's', Text = "Create schedule", Action = NoopCommand.Noop });
this.MenuItems.Add(new MenuItem { Command = 'p', Text = "Print solo event schedule", Action = NoopCommand.Noop });
this.MenuItems.Add(new MenuItem { Command = 'q', Text = "Quit this application", Action = QuitCommand.Quit });
}
}
}
| 42,065
|
https://github.com/TopSkySir/LTCustomProtocol/blob/master/Sources/RequestStatus/LTRequestPagingStatusProtocol.swift
|
Github Open Source
|
Open Source
|
MIT
| null |
LTCustomProtocol
|
TopSkySir
|
Swift
|
Code
| 766
| 2,885
|
//
// LTRequestPagingStatusProtocol.swift
// LTTableViewDemo
//
// Created by TopSky on 2018/3/19.
// Copyright © 2018年 TopSky. All rights reserved.
//
import Foundation
fileprivate struct LTRequestPagingStatusKey {
/**
当前页码Key
*/
static var currentPage = "currentPage"
static var isRefreshHidden = "isRefreshHidden"
static var isLoadMoreHidden = "isLoadMoreHidden"
static var isPagingOver = "isPagingOver"
}
// MARK: - 分页协议
public protocol LTRequestPagingStatusProtocol: LTRequestStatusProtocol where DataSourceType: ExpressibleByArrayLiteral&RangeReplaceableCollection{
/**
分页
*/
func pageSize() -> Int
/**
请求
*/
func startRefreshRequest()
func startLoadMoreRequest()
/**
结束刷新
*/
func endRefresh()
func endLoadMore()
/**
状态
*/
//头部刷新隐藏状态
func shouldCheckRefreshHidden() -> Bool
func checkRefreshHidden() -> Bool
func startRefreshHidden()
func endRefreshHidden()
//尾部加载隐藏状态
func shouldCheckLoadMoreHidden() -> Bool
func checkLoadMoreHidden() -> Bool
func startLoadMoreHidden()
func endLoadMoreHidden()
//分页结束状态
func shouldCheckPagingOver() -> Bool
func checkPagingOver(_ totolCount: Int, _ addCount: Int) -> Bool
func startPagingOver()
func endPagingOver()
}
// MARK: - 请求
public extension LTRequestPagingStatusProtocol{
/**
开启 刷新请求
*/
func startRefreshRequest() {
cleanRequestStatus()
setInitStatus()
setCurrentPage(1)
request()
}
/**
开启 加载更多
*/
func startLoadMoreRequest() {
cleanRequestStatus()
setCurrentPage(currentPage + 1)
request()
}
}
// MARK: - 数据绑定
public extension LTRequestPagingStatusProtocol {
/**
获取数据
*/
func fetchDataSource(_ source: DataSourceType?) {
cleanRequestStatus()
if currentPage == 1 {
refreshDataSource(source)
} else {
appendDataSource(source)
}
setResponseEmptyStatus()
setRefreshHiddenStatus()
setLoadMoreHiddenStatus()
setPagingOverStatus(source)
reloadData()
}
/**
获取Error
*/
func fetchError(_ err: DataErrorType?) {
cleanRequestStatus()
setResponseErrorStatus(err)
setRefreshHiddenStatus()
setLoadMoreHiddenStatus()
}
/**
刷新数据源
*/
fileprivate func refreshDataSource(_ source: DataSourceType?) {
dataSource = source
}
/**
拼接数据源
*/
fileprivate func appendDataSource(_ source: DataSourceType?) {
guard let appendSource = source else {
return
}
guard let originSource = dataSource else {
dataSource = appendSource
return
}
dataSource = originSource + appendSource
}
}
// MARK: - 页码
public extension LTRequestPagingStatusProtocol {
/**
页码大小
*/
func pageSize() -> Int {
return 10
}
/**
当前页码
*/
var currentPage: Int {
return getAssociateIntValue(<RequestPagingStatusKey.currentPage, defaultValue: 1)
}
/**
是否 是头部刷新
*/
fileprivate var isRefreshing: Bool {
return currentPage == 1
}
/**
设置当前页码
*/
fileprivate func setCurrentPage(_ newValue: Int) {
setAssociateIntValue(<RequestPagingStatusKey.currentPage, newValue)
}
}
// MARK: - 状态管理
public extension LTRequestPagingStatusProtocol {
/**
清除其他状态
*/
fileprivate func cleanRequestStatus() {
cleanInitStatus()
cleanResponseEmptyStatus()
cleanResponseErrorStatus()
cleanRefreshHiddenStatus()
cleanLoadMoreHiddenStatus()
cleanPagingOverStatus()
cleanRefreshingOrLoading()
}
/**
清除刷新或加载状态
*/
fileprivate func cleanRefreshingOrLoading() {
if isRefreshing {
endRefresh()
} else {
endLoadMore()
}
}
}
// MARK: - 头部刷新隐藏状态
public extension LTRequestPagingStatusProtocol {
/**
是否检测 头部刷新隐藏状态
*/
func shouldCheckRefreshHidden() -> Bool {
return true
}
/**
检测 头部刷新隐藏状态
*/
func checkRefreshHidden() -> Bool {
return isResponseEmpty || isResponseError
}
/**
开启 头部刷新隐藏状态
*/
func startRefreshHidden() {
}
/**
关闭 头部刷新隐藏状态
*/
func endRefreshHidden() {
}
/**
设置 头部刷新隐藏状态
*/
fileprivate func setRefreshHiddenStatus() {
if shouldCheckRefreshHidden() && checkRefreshHidden() {
setIsRefreshHidden(true)
startRefreshHidden()
}
}
/**
清除 头部刷新隐藏状态
*/
fileprivate func cleanRefreshHiddenStatus() {
if isRefreshHidden {
endRefreshHidden()
setIsRefreshHidden(false)
}
}
/**
存储
*/
var isRefreshHidden: Bool {
guard shouldCheckRefreshHidden() else {
return false
}
return getAssociateBoolValue(<RequestPagingStatusKey.isRefreshHidden)
}
fileprivate func setIsRefreshHidden(_ newValue: Bool) {
setAssociateBoolValue(<RequestPagingStatusKey.isRefreshHidden, newValue)
}
}
// MARK: - 尾部加载隐藏状态
public extension LTRequestPagingStatusProtocol {
/**
是否检测 尾部加载隐藏状态
*/
func shouldCheckLoadMoreHidden() -> Bool {
return true
}
/**
检测 尾部加载隐藏状态
*/
func checkLoadMoreHidden() -> Bool {
return isResponseEmpty || isResponseError
}
/**
开启 尾部加载隐藏状态
*/
func startLoadMoreHidden() {
}
/**
关闭 尾部加载隐藏状态
*/
func endLoadMoreHidden() {
}
/**
设置 尾部加载隐藏状态
*/
fileprivate func setLoadMoreHiddenStatus() {
if shouldCheckLoadMoreHidden() && checkLoadMoreHidden() {
setIsLoadMoreHidden(true)
startLoadMoreHidden()
}
}
/**
清除 尾部加载隐藏状态
*/
fileprivate func cleanLoadMoreHiddenStatus() {
if isLoadMoreHidden {
endLoadMoreHidden()
setIsLoadMoreHidden(false)
}
}
/**
存储
*/
var isLoadMoreHidden: Bool {
guard shouldCheckLoadMoreHidden() else {
return false
}
return getAssociateBoolValue(<RequestPagingStatusKey.isLoadMoreHidden)
}
fileprivate func setIsLoadMoreHidden(_ newValue: Bool) {
setAssociateBoolValue(<RequestPagingStatusKey.isLoadMoreHidden, newValue)
}
}
// MARK: - 页尾状态
public extension LTRequestPagingStatusProtocol {
/**
是否检测 页尾状态
*/
func shouldCheckPagingOver() -> Bool {
return true
}
/**
检测 页尾状态
*/
func checkPagingOver(_ totolCount: Int, _ addCount: Int) -> Bool {
return addCount < pageSize()
}
/**
开启 页尾状态
*/
func startPagingOver() {
}
/**
关闭 页尾状态
*/
func endPagingOver() {
}
/**
设置 页尾状态
*/
fileprivate func setPagingOverStatus(_ source: DataSourceType?) {
guard shouldCheckPagingOver() else {
return
}
let totalCount = dataSource?.count ?? 0
let addCount = source?.count ?? 0
guard checkPagingOver(Int(totalCount), Int(addCount)) else {
return
}
setIsPagingOverKey(true)
startPagingOver()
}
/**
清除 页尾状态
*/
fileprivate func cleanPagingOverStatus() {
if isPagingOver {
endPagingOver()
setIsPagingOverKey(false)
}
}
/**
存储
*/
var isPagingOver: Bool {
guard shouldCheckPagingOver() else {
return false
}
return getAssociateBoolValue(<RequestPagingStatusKey.isPagingOver)
}
fileprivate func setIsPagingOverKey(_ newValue: Bool) {
setAssociateBoolValue(<RequestPagingStatusKey.isPagingOver, newValue)
}
}
// MARK: - 关联属性
public extension LTRequestPagingStatusProtocol {
/**
set Int 关联属性
*/
fileprivate func setAssociateIntValue(_ key: UnsafeRawPointer, _ newValue: Int) {
objc_setAssociatedObject(self, key, newValue, .OBJC_ASSOCIATION_ASSIGN)
}
/**
get Int 关联属性
*/
fileprivate func getAssociateIntValue(_ key: UnsafeRawPointer, defaultValue: Int = 0) -> Int {
return objc_getAssociatedObject(self, key) as? Int ?? defaultValue
}
}
| 18,142
|
https://github.com/JackWangCUMT/JdSdk/blob/master/Source/JdSdk/Request/JingdongUnionPromotiongoodUpdateRequest.cs
|
Github Open Source
|
Open Source
|
MS-PL
| 2,021
|
JdSdk
|
JackWangCUMT
|
C#
|
Code
| 114
| 559
|
#region head comment
/*
Code generate by JdSdkTool.
Copyright © starpeng@vip.qq.com
2013-07-29 22:39:05.01420 +08:00
*/
#endregion
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using JdSdk.Response;
using Newtonsoft.Json;
namespace JdSdk.Request
{
/// <summary>
/// 获得指定SKU ID的商品的推广数据 Request
/// </summary>
public class JingdongUnionPromotiongoodUpdateRequest : JdRequestBase<JingdongUnionPromotiongoodUpdateResponse>
{
public JingdongUnionPromotiongoodUpdateRequest()
{
throw new Exception("此接口已下线!");
}
/// <summary>
/// 商品的SKU ID,如果skuId不填或者没有相匹配的店铺信息则返回默认的推广数据
/// </summary>
[XmlElement("skuId")]
[JsonProperty("skuId")]
public Int64 SkuId
{
get;
set;
}
/// <summary>
/// 要求返回的商品推广的内容字段
/// </summary>
/// <example>good_pk,good_skuId,good_shopName,good_name,good_price,good_praiseDegree,good_targetUrl,good_shopUrl,good_materialUrl,good_commRatio,good_commision,good_promQuantity,good_startDate,good_endDate,totalCount</example>
[XmlElement("fields")]
[JsonProperty("fields")]
public String Fields
{
get;
set;
}
public override String ApiName
{
get { return "jingdong.union.promotiongood.update"; }
}
protected override void PrepareParam(IDictionary<String, Object> paramters)
{
paramters.Add("skuid", this.SkuId);
paramters.Add("fields", this.Fields);
}
public override void Validate()
{
}
}
}
| 20,119
|
https://github.com/Vloods/TransTTE_demo/blob/master/backend/app/utils.py
|
Github Open Source
|
Open Source
|
MIT
| null |
TransTTE_demo
|
Vloods
|
Python
|
Code
| 192
| 439
|
import numpy as np
def haversine_np(lon1, lat1, lon2, lat2):
"""
Calculate the great circle distance between two points
on the earth (specified in decimal degrees)
All args must be of equal length.
"""
lon1, lat1, lon2, lat2 = map(np.radians, [lon1, lat1, lon2, lat2])
dlon = lon2 - lon1
dlat = lat2 - lat1
a = np.sin(dlat/2.0)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2.0)**2
c = 2 * np.arcsin(np.sqrt(a))
m = 6367 * c * 1000
return m
def get_perp( X1, Y1, X2, Y2, X3, Y3):
"""************************************************************************************************
Purpose - X1,Y1,X2,Y2 = Two points representing the ends of the line segment
X3,Y3 = The offset point
'Returns - X4,Y4 = Returns the Point on the line perpendicular to the offset or None if no such
point exists
'************************************************************************************************ """
XX = X2 - X1
YY = Y2 - Y1
ShortestLength = ((XX * (X3 - X1)) + (YY * (Y3 - Y1))) / ((XX * XX) + (YY * YY))
print(ShortestLength)
X4 = X1 + XX * ShortestLength
Y4 = Y1 + YY * ShortestLength
if X4 < X2 and X4 > X1 and Y4 < Y2 and Y4 > Y1:
return X4,Y4
return None
| 26,296
|
https://github.com/luk036/ckpttncpp/blob/master/lib/include/ckpttncpp/FMBiGainCalc.hpp
|
Github Open Source
|
Open Source
|
MIT
| null |
ckpttncpp
|
luk036
|
C++
|
Code
| 548
| 1,773
|
#pragma once
#include "FMPmrConfig.hpp"
#include "dllist.hpp" // import dllink
#include "netlist.hpp" // import Netlist
#include <gsl/span>
// struct FMBiGainMgr;
/*!
* @brief FMBiGainCalc
*
*/
class FMBiGainCalc
{
friend class FMBiGainMgr;
public:
using node_t = typename SimpleNetlist::node_t;
using Item = dllink<std::pair<node_t, uint32_t>>;
private:
const SimpleNetlist& H;
std::vector<Item> vertex_list;
int totalcost {0};
std::byte StackBuf[8192]; // ???
FMPmr::monotonic_buffer_resource rsrc;
public:
int deltaGainW {};
FMPmr::vector<node_t> IdVec;
bool special_handle_2pin_nets {true};
/*!
* @brief Construct a new FMBiGainCalc object
*
* @param[in] H
* @param[in] K
*/
explicit FMBiGainCalc(const SimpleNetlist& H, std::uint8_t /*K*/)
: H {H}
, vertex_list(H.number_of_modules())
, rsrc(StackBuf, sizeof StackBuf)
, IdVec(&rsrc)
{
for (const auto& v : this->H)
{
this->vertex_list[v].data = std::pair {v, int32_t(0)};
}
}
/*!
* @brief
*
* @param[in] part
*/
auto init(gsl::span<const std::uint8_t> part) -> int
{
this->totalcost = 0;
for (auto& vlink : this->vertex_list)
{
vlink.data.second = 0;
}
for (const auto& net : this->H.nets)
{
this->_init_gain(net, part);
}
return this->totalcost;
}
/*!
* @brief update move init
*
*/
auto update_move_init() -> void
{
// nothing to do in 2-way partitioning
}
void init_IdVec(const node_t& v, const node_t& net);
/*!
* @brief update move 2-pin net
*
* @param[in] part
* @param[in] move_info
* @param[out] w
* @return int
*/
auto update_move_2pin_net(gsl::span<const std::uint8_t> part,
const MoveInfo<node_t>& move_info) -> node_t;
/*!
* @brief update move 3-pin net
*
* @param[in] part
* @param[in] move_info
* @return ret_info
*/
auto update_move_3pin_net(gsl::span<const std::uint8_t> part,
const MoveInfo<node_t>& move_info) -> std::vector<int>;
/*!
* @brief update move general net
*
* @param[in] part
* @param[in] move_info
* @return ret_info
*/
auto update_move_general_net(gsl::span<const std::uint8_t> part,
const MoveInfo<node_t>& move_info) -> std::vector<int>;
private:
/*!
* @brief
*
* @param[in] w
* @param[in] weight
*/
auto _modify_gain(const node_t& w, unsigned int weight) -> void
{
this->vertex_list[w].data.second += weight;
}
/**
* @brief
*
* @tparam Ts
* @param weight
* @param w
*/
template <typename... Ts>
auto _modify_gain_va(unsigned int weight, Ts... w) -> void
{
((this->vertex_list[w].data.second += weight), ...);
}
// /**
// * @brief
// *
// * @tparam Ts
// * @param weight
// * @param w
// */
// auto _modify_gain_va(unsigned int weight, const node_t& w1) -> void
// {
// this->vertex_list[w1].data.second += weight;
// }
// /**
// * @brief
// *
// * @tparam Ts
// * @param weight
// * @param w
// */
// auto _modify_gain_va(unsigned int weight, const node_t& w1, const node_t& w2) ->
// void
// {
// this->vertex_list[w1].data.second += weight;
// this->vertex_list[w2].data.second += weight;
// }
// /**
// * @brief
// *
// * @tparam Ts
// * @param weight
// * @param w
// */
// auto _modify_gain_va(unsigned int weight, const node_t& w1, const node_t& w2,
// const node_t& w3) -> void
// {
// this->vertex_list[w1].data.second += weight;
// this->vertex_list[w2].data.second += weight;
// this->vertex_list[w3].data.second += weight;
// }
/*!
* @brief
*
* @param[in] net
* @param[in] part
*/
auto _init_gain(const node_t& net, gsl::span<const std::uint8_t> part)
-> void;
/*!
* @brief
*
* @param[in] net
* @param[in] part
*/
auto _init_gain_2pin_net(
const node_t& net, gsl::span<const std::uint8_t> part) -> void;
/*!
* @brief
*
* @param[in] net
* @param[in] part
*/
auto _init_gain_3pin_net(
const node_t& net, gsl::span<const std::uint8_t> part) -> void;
/*!
* @brief
*
* @param[in] net
* @param[in] part
*/
auto _init_gain_general_net(
const node_t& net, gsl::span<const std::uint8_t> part) -> void;
};
| 27,606
|
https://github.com/SaurabhSM/ews/blob/master/lib/ComplexProperties/ExtendedPropertyCollection.dart
|
Github Open Source
|
Open Source
|
MIT
| null |
ews
|
SaurabhSM
|
Dart
|
Code
| 917
| 2,694
|
/*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
import 'package:ews/ComplexProperties/ComplexPropertyCollection.dart';
import 'package:ews/ComplexProperties/ExtendedProperty.dart';
import 'package:ews/Core/EwsServiceXmlReader.dart';
import 'package:ews/Core/EwsServiceXmlWriter.dart';
import 'package:ews/Core/EwsUtilities.dart';
import 'package:ews/Core/ServiceObjects/ServiceObject.dart';
import 'package:ews/Core/XmlElementNames.dart';
import 'package:ews/Enumerations/XmlNamespace.dart';
import 'package:ews/Interfaces/ICustomUpdateSerializer.dart';
import 'package:ews/PropertyDefinitions/ExtendedPropertyDefinition.dart';
import 'package:ews/PropertyDefinitions/PropertyDefinition.dart';
import 'package:ews/misc/OutParam.dart';
/// <summary>
/// Represents a collection of extended properties.
/// </summary>
class ExtendedPropertyCollection
extends ComplexPropertyCollection<ExtendedProperty>
implements ICustomUpdateSerializer {
/// <summary>
/// Creates the complex property.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Complex property instance.</returns>
@override
ExtendedProperty CreateComplexProperty(String xmlElementName) {
return new ExtendedProperty();
}
/// <summary>
/// Gets the name of the collection item XML element.
/// </summary>
/// <param name="complexProperty">The complex property.</param>
/// <returns>XML element name.</returns>
@override
String GetCollectionItemXmlElementName(ExtendedProperty complexProperty) {
// This method is unused in this class, so just return null.
return null;
}
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="localElementName">Name of the local element.</param>
@override
void LoadFromXml(EwsServiceXmlReader reader, String localElementName) {
ExtendedProperty extendedProperty = new ExtendedProperty();
extendedProperty.LoadFromXml(reader, reader.LocalName);
this.InternalAdd(extendedProperty);
}
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
@override
void WriteToXml(EwsServiceXmlWriter writer, String xmlElementName) {
for (ExtendedProperty extendedProperty in this) {
extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty);
}
}
/// <summary>
/// Gets existing or adds new extended property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <returns>ExtendedProperty.</returns>
ExtendedProperty _GetOrAddExtendedProperty(
ExtendedPropertyDefinition propertyDefinition) {
ExtendedProperty extendedProperty = null;
OutParam<ExtendedProperty> extendedPropertyOut =
new OutParam<ExtendedProperty>();
if (!this._TryGetProperty(propertyDefinition, extendedPropertyOut)) {
extendedProperty =
new ExtendedProperty.withDefinition(propertyDefinition);
this.InternalAdd(extendedProperty);
} else {
extendedProperty = extendedPropertyOut.param;
}
return extendedProperty;
}
/// <summary>
/// Sets an extended property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="value">The value.</param>
void SetExtendedProperty(
ExtendedPropertyDefinition propertyDefinition, Object value) {
ExtendedProperty extendedProperty =
this._GetOrAddExtendedProperty(propertyDefinition);
extendedProperty.Value = value;
}
/// <summary>
/// Removes a specific extended property definition from the collection.
/// </summary>
/// <param name="propertyDefinition">The definition of the extended property to remove.</param>
/// <returns>True if the property matching the extended property definition was successfully removed from the collection, false otherwise.</returns>
bool RemoveExtendedProperty(ExtendedPropertyDefinition propertyDefinition) {
EwsUtilities.ValidateParam(propertyDefinition, "propertyDefinition");
ExtendedProperty extendedProperty = null;
OutParam<ExtendedProperty> extendedPropertyOut =
new OutParam<ExtendedProperty>();
if (this._TryGetProperty(propertyDefinition, extendedPropertyOut)) {
extendedProperty = extendedPropertyOut.param;
return this.InternalRemove(extendedProperty);
} else {
return false;
}
}
/// <summary>
/// Tries to get property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="extendedProperty">The extended property.</param>
/// <returns>True of property exists in collection.</returns>
bool _TryGetProperty(ExtendedPropertyDefinition propertyDefinition,
OutParam<ExtendedProperty> extendedPropertyOut) {
bool found = false;
extendedPropertyOut.param = null;
for (ExtendedProperty prop in this.Items) {
if (prop.PropertyDefinition == propertyDefinition) {
found = true;
extendedPropertyOut.param = prop;
break;
}
}
return found;
}
/// <summary>
/// Tries to get property value.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="propertyValue">The property value.</param>
/// <typeparam name="T">Type of expected property value.</typeparam>
/// <returns>True if property exists in collection.</returns>
bool TryGetValue<T>(ExtendedPropertyDefinition propertyDefinition,
OutParam<T> propertyValueOut) {
ExtendedProperty extendedProperty = null;
OutParam<ExtendedProperty> extendedPropertyOut =
new OutParam<ExtendedProperty>();
if (this._TryGetProperty(propertyDefinition, extendedPropertyOut)) {
extendedProperty = extendedPropertyOut.param;
// todo ("implement runtimeType check")
// if (T.runtimeType is propertyDefinition.Type) {
// String errorMessage = String.format(
// "Property definition type '%s' and type parameter '%s' aren't compatible.",
// propertyDefinition.getType().getSimpleName(),
// cls.getSimpleName());
// throw new ArgumentError(errorMessage, "propertyDefinition");
// }
propertyValueOut.param = extendedProperty.Value;
return true;
} else {
propertyValueOut.param = null;
return false;
}
// ExtendedProperty extendedProperty;
// if (this.TryGetProperty(propertyDefinition, out extendedProperty))
// {
// // Verify that the type parameter and property definition's type are compatible.
// if (!typeof(T).IsAssignableFrom(propertyDefinition.Type))
// {
// String errorMessage = string.Format(
// Strings.PropertyDefinitionTypeMismatch,
// EwsUtilities.GetPrintableTypeName(propertyDefinition.Type),
// EwsUtilities.GetPrintableTypeName(typeof(T)));
// throw new ArgumentError(errorMessage, "propertyDefinition");
// }
//
// propertyValue = (T)extendedProperty.Value;
// return true;
// }
// else
// {
// propertyValue = default(T);
// return false;
// }
}
/// <summary>
/// Writes the update to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="ewsObject">The ews object.</param>
/// <param name="propertyDefinition">Property definition.</param>
/// <returns>
/// True if property generated serialization.
/// </returns>
bool WriteSetUpdateToXml(EwsServiceXmlWriter writer, ServiceObject ewsObject,
PropertyDefinition propertyDefinition) {
List<ExtendedProperty> propertiesToSet = new List<ExtendedProperty>();
propertiesToSet.addAll(this.AddedItems);
propertiesToSet.addAll(this.ModifiedItems);
for (ExtendedProperty extendedProperty in propertiesToSet) {
writer.WriteStartElement(
XmlNamespace.Types, ewsObject.GetSetFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteStartElement(
XmlNamespace.Types, ewsObject.GetXmlElementName());
extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty);
writer.WriteEndElement();
writer.WriteEndElement();
}
for (ExtendedProperty extendedProperty in this.RemovedItems) {
writer.WriteStartElement(
XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteEndElement();
}
return true;
}
/// <summary>
/// Writes the deletion update to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="ewsObject">The ews object.</param>
/// <returns>
/// True if property generated serialization.
/// </returns>
bool WriteDeleteUpdateToXml(
EwsServiceXmlWriter writer, ServiceObject ewsObject) {
for (ExtendedProperty extendedProperty in this.Items) {
writer.WriteStartElement(
XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteEndElement();
}
return true;
}
}
| 16,501
|
https://github.com/chierrie/Tia-contract/blob/master/src/Dollar.sol
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
Tia-contract
|
chierrie
|
Gerber Image
|
Code
| 226
| 669
|
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/GSN/Context.sol";
import "./ERC20/ERC20Custom.sol";
import "./Share.sol";
import "./interfaces/ITreasury.sol";
import "./interfaces/IDollar.sol";
import "./Operator.sol";
contract Dollar is ERC20Custom, IDollar, Operator {
using SafeMath for uint256;
// ERC20
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public constant genesis_supply = 5000 ether; // 5000 will be mited at genesis for liq pool seeding
// CONTRACTS
address public treasury;
// FLAGS
bool public initialized;
/* ========== MODIFIERS ========== */
modifier onlyPools() {
require(ITreasury(treasury).hasPool(msg.sender), "!pools");
_;
}
/* ========== CONSTRUCTOR ========== */
constructor(
string memory _name,
string memory _symbol,
address _treasury
) public {
name = _name;
symbol = _symbol;
treasury = _treasury;
}
function initialize() external onlyOperator {
require(!initialized, "alreadyInitialized");
initialized = true;
_mint(_msgSender(), genesis_supply);
}
/* ========== RESTRICTED FUNCTIONS ========== */
// Burn DOLLAR. Can be used by Pool only
function poolBurnFrom(address _address, uint256 _amount) external override onlyPools {
super._burnFrom(_address, _amount);
emit DollarBurned(_address, msg.sender, _amount);
}
// Mint DOLLAR. Can be used by Pool only
function poolMint(address _address, uint256 _amount) external override onlyPools {
super._mint(_address, _amount);
emit DollarMinted(msg.sender, _address, _amount);
}
function setTreasuryAddress(address _treasury) public onlyOperator {
treasury = _treasury;
}
/* ========== EVENTS ========== */
// Track DOLLAR burned
event DollarBurned(address indexed from, address indexed to, uint256 amount);
// Track DOLLAR minted
event DollarMinted(address indexed from, address indexed to, uint256 amount);
}
| 1,134
|
https://github.com/papeldeorigami/dotvim/blob/master/ftplugin/ruby_pry.vim
|
Github Open Source
|
Open Source
|
Beerware
| 2,018
|
dotvim
|
papeldeorigami
|
Vim Script
|
Code
| 3
| 30
|
nnoremap <Leader><Leader>b orequire'pry';binding.pry<esc>:w<cr>
| 39,002
|
https://github.com/mrnustik/AwsConfiguration/blob/master/AwsConfiguration.ParameterStore/Program.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
AwsConfiguration
|
mrnustik
|
C#
|
Code
| 22
| 113
|
using Microsoft.Extensions.Options;
var builder = WebApplication.CreateBuilder(args);
var environmentName = builder.Environment.EnvironmentName;
builder.Configuration.AddSystemsManager($"/{environmentName}/");
builder.Services.Configure<MyOptions>(builder.Configuration.GetRequiredSection("MyKey"));
var app = builder.Build();
app.MapGet("/configuration", (IOptions<MyOptions> options) => options.Value);
app.Run();
| 42,343
|
https://github.com/6923403/C/blob/master/cpp11/class/workers/Commpany.h
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
C
|
6923403
|
C
|
Code
| 30
| 124
|
#ifndef _WORKERS_COMMPANY_H
#define _WORKERS_COMMPANY_H
#include <string>
using std::string;
class Commpany
{
public:
Commpany();
virtual ~Commpany();
void showMenu();
void CenterControl();
void ExitProgam();
private:
int Ctmp;
//CpManger * setCp;
};
#endif //_WORKERS_COMMPANY_H
| 49,486
|
https://github.com/p1b234/jlplib/blob/master/jlp_gseg_gnome/jlp_gseg_gnome.cpp
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
jlplib
|
p1b234
|
C++
|
Code
| 281
| 1,345
|
/**
* \file jlp_gseg_gnome.cpp
* \class JLP_Gseg_Gnome (Gnu Graphic Device)
* \author JLP
* \date 13/12/2016
* \brief Definition of the gnome graphic drivers for JLP_Gseg
*
* Class JLP_Gseg_Gnome ("Gnu Graphic Device")
* Definition of the graphic drivers
* used in the JLP/GNU plotting package
*
* JLP
* Version 14/12/2016
**************************************************************************/
#include <math.h>
#include <time.h>
#include "jlp_gseg_gnome.h" // JLP_Gseg_Gnome class
/************************************************************************
* Constructor
************************************************************************/
JLP_Gseg_Gnome::JLP_Gseg_Gnome(window_data_type *p_window_data_0)
{
/* Save to private variables: */
p_parent_window_data.x = p_window_data_0->x;
p_parent_window_data.y = p_window_data_0->y;
p_parent_window_data.width = p_window_data_0->width;
p_parent_window_data.height = p_window_data_0->height;
p_parent_window_data.window = NULL;
p_parent_window_data.canvas = NULL;
// Initialize width dummy values to avoid problems when not fully initialized:
parent_group = NULL;
parent_height_menu_bar = 0;
/* Initialize font variables */
GSEG_gnome_InitializeFonts();
}
/******************************************************************************
*
******************************************************************************/
void JLP_Gseg_Gnome::GSEG_gnome_InitializePlotWindow(GnomeApp *window0,
GtkWidget *canvas0)
{
p_parent_window_data.window = window0;
p_parent_window_data.canvas = canvas0;
}
/******************************************************************************
*
******************************************************************************/
void JLP_Gseg_Gnome::GSEG_gnome_InitializePlotCanvas(GnomeCanvasGroup *group0,
int height_menu_bar0)
{
parent_group = group0;
parent_height_menu_bar = height_menu_bar0;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_Gseg_Gnome::GSEG_gnome_SetPointersFromPlot(PangoFontDescription **font_text_0)
{
*font_text_0 = font_text1;
return;
}
/*****************************************************************************
*
*****************************************************************************/
void JLP_Gseg_Gnome::GSEG_gnome_InitializeFonts( void )
{
unsigned int size;
/* Set pointers to NULL */
font_date_time1 = NULL;
font_legend1 = NULL;
font_text1 = NULL;
font_tick_labels1 = NULL;
font_axis_labels1 = NULL;
font_title1 = NULL;
/* Specify default font name */
strcpy(font_name1, "Sans");
/* Specify font style and weight */
font_date_time1 = pango_font_description_new();
pango_font_description_set_style(font_date_time1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_date_time1, PANGO_WEIGHT_NORMAL);
font_legend1 = pango_font_description_new();
pango_font_description_set_style(font_legend1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_legend1, PANGO_WEIGHT_NORMAL);
font_text1 = pango_font_description_new();
pango_font_description_set_style(font_text1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_text1, PANGO_WEIGHT_NORMAL);
font_tick_labels1 = pango_font_description_new();
pango_font_description_set_style(font_tick_labels1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_tick_labels1, PANGO_WEIGHT_NORMAL);
font_axis_labels1 = pango_font_description_new();
pango_font_description_set_style(font_axis_labels1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_axis_labels1, PANGO_WEIGHT_NORMAL);
font_title1 = pango_font_description_new();
pango_font_description_set_style(font_title1, PANGO_STYLE_NORMAL);
pango_font_description_set_weight(font_title1, PANGO_WEIGHT_NORMAL);
/* Specify default font point sizes */
font_size_date_time1 = 12;
font_size_legend1 = 14;
font_size_text1 = 14;
font_size_tick_labels1 = 14;
font_size_axis_labels1 = 16;
font_size_title1 = 18;
return;
}
| 35,242
|
https://github.com/joergreichert/fancy_LVB_Telegram_Bot/blob/master/app/helper/globalstations.js
|
Github Open Source
|
Open Source
|
Apache-2.0
| null |
fancy_LVB_Telegram_Bot
|
joergreichert
|
JavaScript
|
Code
| 102
| 365
|
const commonStationHelper = require('./commonstations')
const globalStations = []
exports.isEmpty = function () {
return globalStations.length === 0;
}
exports.getMatchingGlobalStations = function (stationName) {
return commonStationHelper.getMatchingStations(globalStations, stationName)
}
exports.addGlobalStation = function (station) {
if(!containedInGlobalStations(station)) {
globalStations.push(station)
}
}
function getGlobalStationIds() {
return globalStations.map(globalStation => globalStation.id)
}
function containedInGlobalStations(station) {
return getGlobalStationIds().indexOf(station.id) !== -1
}
exports.containedInGlobalStations = containedInGlobalStations;
exports.removeFromGlobalStations = function(station) {
if(containedInGlobalStations(station)) {
if(globalStations.length === 1) {
globalStations.length = 0
} else {
globalStations.splice(globalStations.indexOf(station), 1)
}
}
}
exports.deleteGlobalStations = function () {
globalStations.length = 0
}
exports.globalStationsAsKeyboard = function () {
return {
reply_markup: {
keyboard: commonStationHelper.transformToSelectableStationNames(globalStations),
resize_keyboard: true
}
}
}
| 6,843
|
https://github.com/ElkinMedina/C-e-commerce/blob/master/forms/forms.py
|
Github Open Source
|
Open Source
|
MIT
| null |
C-e-commerce
|
ElkinMedina
|
Python
|
Code
| 37
| 125
|
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField
from wtforms.fields.core import BooleanField
from wtforms.validators import DataRequired
class LoginForm(FlaskForm):
usuario = StringField('Usuario', validators=[DataRequired(message="Este campo es requerido")])
contraseña = PasswordField('Contraseña', validators=[DataRequired(message="Este campo es requerido")])
recordar = BooleanField('Recordar usuario')
| 32,375
|
https://github.com/lousybyte/demo-razor-pages/blob/master/DemoRazor/Data/ProductsBrandData.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
demo-razor-pages
|
lousybyte
|
C#
|
Code
| 59
| 196
|
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DemoRazor.Data
{
public class ProductsBrandData
{
public ProductsBrandData()
{
Products = new HashSet<ProductData>();
}
public long Id { get; set; }
[Required]
[MaxLength(255)]
[DefaultValue("BRAND_NAME")]
public string BrandName { get; set; }
[ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public uint xmin { get; set; }
public virtual ICollection<ProductData> Products { get; set; }
}
}
| 20,677
|
https://github.com/195858/tdi-studio-se/blob/master/main/plugins/org.talend.designer.components.libs/libs_src/salesforceCRMManagement/com/salesforce/soap/partner/SforceServiceStub.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,018
|
tdi-studio-se
|
195858
|
Java
|
Code
| 20,000
| 89,416
|
/** * SforceServiceStub.java * * This file was auto-generated from WSDL by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:33:49 IST) */ package com.salesforce.soap.partner; /* * SforceServiceStub java implementation */ public class SforceServiceStub extends org.apache.axis2.client.Stub implements SforceService { protected org.apache.axis2.description.AxisOperation[] _operations; // hashmaps to keep the fault mapping private java.util.HashMap faultExceptionNameMap = new java.util.HashMap(); private java.util.HashMap faultExceptionClassNameMap = new java.util.HashMap(); private java.util.HashMap faultMessageMap = new java.util.HashMap(); private static int counter = 0; private static synchronized java.lang.String getUniqueSuffix() { // reset the counter if it is greater than 99999 if (counter > 99999) { counter = 0; } counter = counter + 1; return java.lang.Long.toString(java.lang.System.currentTimeMillis()) + "_" + counter; } private void populateAxisService() throws org.apache.axis2.AxisFault { // creating the Service with a unique name _service = new org.apache.axis2.description.AxisService("SforceService" + getUniqueSuffix()); addAnonymousOperations(); // creating the operations org.apache.axis2.description.AxisOperation __operation; _operations = new org.apache.axis2.description.AxisOperation[52]; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge")); _service.addOperation(__operation); _operations[0] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo")); _service.addOperation(__operation); _operations[1] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs")); _service.addOperation(__operation); _operations[2] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions")); _service.addOperation(__operation); _operations[3] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout")); _service.addOperation(__operation); _operations[4] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts")); _service.addOperation(__operation); _operations[5] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView")); _service.addOperation(__operation); _operations[6] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update")); _service.addOperation(__operation); _operations[7] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions")); _service.addOperation(__operation); _operations[8] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword")); _service.addOperation(__operation); _operations[9] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout")); _service.addOperation(__operation); _operations[10] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve")); _service.addOperation(__operation); _operations[11] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll")); _service.addOperation(__operation); _operations[12] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete")); _service.addOperation(__operation); _operations[13] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated")); _service.addOperation(__operation); _operations[14] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "create")); _service.addOperation(__operation); _operations[15] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAvailableQuickActions")); _service.addOperation(__operation); _operations[16] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "sendEmail")); _service.addOperation(__operation); _operations[17] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "search")); _service.addOperation(__operation); _operations[18] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeNouns")); _service.addOperation(__operation); _operations[19] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "query")); _service.addOperation(__operation); _operations[20] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeTheme")); _service.addOperation(__operation); _operations[21] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSObjectListViews")); _service.addOperation(__operation); _operations[22] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getDeleted")); _service.addOperation(__operation); _operations[23] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeFlexiPages")); _service.addOperation(__operation); _operations[24] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSearchScopeOrder")); _service.addOperation(__operation); _operations[25] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoqlListViews")); _service.addOperation(__operation); _operations[26] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSearchLayouts")); _service.addOperation(__operation); _operations[27] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "process")); _service.addOperation(__operation); _operations[28] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeDataCategoryGroupStructures")); _service.addOperation(__operation); _operations[29] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "resetPassword")); _service.addOperation(__operation); _operations[30] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeGlobal")); _service.addOperation(__operation); _operations[31] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAppMenu")); _service.addOperation(__operation); _operations[32] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeCompactLayouts")); _service.addOperation(__operation); _operations[33] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeApprovalLayout")); _service.addOperation(__operation); _operations[34] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "sendEmailMessage")); _service.addOperation(__operation); _operations[35] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeLayout")); _service.addOperation(__operation); _operations[36] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeTabs")); _service.addOperation(__operation); _operations[37] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeKnowledgeSettings")); _service.addOperation(__operation); _operations[38] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeDataCategoryGroups")); _service.addOperation(__operation); _operations[39] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getServerTimestamp")); _service.addOperation(__operation); _operations[40] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "invalidateSessions")); _service.addOperation(__operation); _operations[41] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSObject")); _service.addOperation(__operation); _operations[42] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "login")); _service.addOperation(__operation); _operations[43] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieveQuickActionTemplates")); _service.addOperation(__operation); _operations[44] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryMore")); _service.addOperation(__operation); _operations[45] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSObjects")); _service.addOperation(__operation); _operations[46] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "emptyRecycleBin")); _service.addOperation(__operation); _operations[47] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "upsert")); _service.addOperation(__operation); _operations[48] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "convertLead")); _service.addOperation(__operation); _operations[49] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "delete")); _service.addOperation(__operation); _operations[50] = __operation; __operation = new org.apache.axis2.description.OutInAxisOperation(); __operation.setName(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeGlobalTheme")); _service.addOperation(__operation); _operations[51] = __operation; } // populates the faults private void populateFaults() { faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "merge"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "merge"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "merge"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "merge"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "merge"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "merge"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "merge"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "merge"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "merge"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "merge"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "merge"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "merge"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUserInfo"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUserInfo"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUserInfo"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAllTabs"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAllTabs"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAllTabs"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoftphoneLayout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoftphoneLayout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoftphoneLayout"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "update"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "update"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "update"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "update"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "update"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "update"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "update"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "update"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "update"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "update"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "update"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "update"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "setPassword"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "setPassword"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "setPassword"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "setPassword"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "setPassword"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "setPassword"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidNewPasswordFault"), "setPassword"), "com.salesforce.soap.partner.InvalidNewPasswordFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidNewPasswordFault"), "setPassword"), "com.salesforce.soap.partner.InvalidNewPasswordFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidNewPasswordFault"), "setPassword"), "com.salesforce.soap.partner.fault.InvalidNewPasswordFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "logout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "logout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "logout"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "retrieve"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "retrieve"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "retrieve"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "retrieve"), "com.salesforce.soap.partner.MalformedQueryFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "retrieve"), "com.salesforce.soap.partner.MalformedQueryFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "retrieve"), "com.salesforce.soap.partner.fault.MalformedQueryFaultE"); faultExceptionNameMap .put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName("urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "retrieve"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap .put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName("urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "retrieve"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "retrieve"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "retrieve"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "retrieve"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "retrieve"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "retrieve"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "retrieve"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "retrieve"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "queryAll"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "queryAll"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "queryAll"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryAll"), "com.salesforce.soap.partner.MalformedQueryFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryAll"), "com.salesforce.soap.partner.MalformedQueryFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryAll"), "com.salesforce.soap.partner.fault.MalformedQueryFaultE"); faultExceptionNameMap .put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName("urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "queryAll"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap .put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName("urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "queryAll"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "queryAll"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryAll"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryAll"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryAll"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryAll"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryAll"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryAll"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryAll"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryAll"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryAll"), "com.salesforce.soap.partner.fault.InvalidQueryLocatorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "undelete"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "undelete"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "undelete"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getUpdated"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getUpdated"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getUpdated"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUpdated"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUpdated"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getUpdated"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "create"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "create"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "create"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "create"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "create"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "create"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "create"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "create"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "create"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "create"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "create"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "create"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmail"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmail"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmail"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "search"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "search"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "search"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedSearchFault"), "search"), "com.salesforce.soap.partner.MalformedSearchFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedSearchFault"), "search"), "com.salesforce.soap.partner.MalformedSearchFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedSearchFault"), "search"), "com.salesforce.soap.partner.fault.MalformedSearchFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "search"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "search"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "search"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "search"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "search"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "search"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "query"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "query"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "query"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "query"), "com.salesforce.soap.partner.MalformedQueryFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "query"), "com.salesforce.soap.partner.MalformedQueryFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "query"), "com.salesforce.soap.partner.fault.MalformedQueryFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "query"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "query"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "query"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "query"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "query"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "query"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "query"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "query"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "query"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "query"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "query"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "query"), "com.salesforce.soap.partner.fault.InvalidQueryLocatorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTheme"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTheme"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTheme"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjectListViews"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getDeleted"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getDeleted"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "getDeleted"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getDeleted"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getDeleted"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getDeleted"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeFlexiPages"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeFlexiPages"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeFlexiPages"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeFlexiPages"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeFlexiPages"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeFlexiPages"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSoqlListViews"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSearchLayouts"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "process"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "process"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "process"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "process"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "process"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "process"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroupStructures"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "resetPassword"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "resetPassword"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "resetPassword"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "resetPassword"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "resetPassword"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "resetPassword"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobal"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobal"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobal"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAppMenu"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAppMenu"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeAppMenu"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmailMessage"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmailMessage"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "sendEmailMessage"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeLayout"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeLayout"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeLayout"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeLayout"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeLayout"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "describeLayout"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeLayout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeLayout"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeLayout"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTabs"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTabs"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeTabs"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeKnowledgeSettings"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeKnowledgeSettings"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeKnowledgeSettings"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeDataCategoryGroups"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getServerTimestamp"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getServerTimestamp"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "getServerTimestamp"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "invalidateSessions"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "invalidateSessions"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "invalidateSessions"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObject"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObject"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObject"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObject"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObject"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObject"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "login"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "login"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "login"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "login"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "login"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "login"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "LoginFault"), "login"), "com.salesforce.soap.partner.LoginFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "LoginFault"), "login"), "com.salesforce.soap.partner.LoginFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "LoginFault"), "login"), "com.salesforce.soap.partner.fault.LoginFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryMore"), "com.salesforce.soap.partner.MalformedQueryFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryMore"), "com.salesforce.soap.partner.MalformedQueryFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "MalformedQueryFault"), "queryMore"), "com.salesforce.soap.partner.fault.MalformedQueryFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryMore"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryMore"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "queryMore"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryMore"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryMore"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "queryMore"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryMore"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryMore"), "com.salesforce.soap.partner.InvalidQueryLocatorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidQueryLocatorFault"), "queryMore"), "com.salesforce.soap.partner.fault.InvalidQueryLocatorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjects"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjects"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "describeSObjects"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjects"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjects"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeSObjects"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "emptyRecycleBin"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "emptyRecycleBin"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "emptyRecycleBin"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "upsert"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "upsert"), "com.salesforce.soap.partner.InvalidSObjectFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidSObjectFault"), "upsert"), "com.salesforce.soap.partner.fault.InvalidSObjectFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "upsert"), "com.salesforce.soap.partner.InvalidIdFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "upsert"), "com.salesforce.soap.partner.InvalidIdFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidIdFault"), "upsert"), "com.salesforce.soap.partner.fault.InvalidIdFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "upsert"), "com.salesforce.soap.partner.InvalidFieldFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "upsert"), "com.salesforce.soap.partner.InvalidFieldFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "InvalidFieldFault"), "upsert"), "com.salesforce.soap.partner.fault.InvalidFieldFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "upsert"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "upsert"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "upsert"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "convertLead"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "convertLead"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "convertLead"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "delete"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "delete"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "delete"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); faultExceptionNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobalTheme"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultExceptionClassNameMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobalTheme"), "com.salesforce.soap.partner.UnexpectedErrorFault"); faultMessageMap.put(new org.apache.axis2.client.FaultMapKey(new javax.xml.namespace.QName( "urn:fault.partner.soap.sforce.com", "UnexpectedErrorFault"), "describeGlobalTheme"), "com.salesforce.soap.partner.fault.UnexpectedErrorFaultE"); } /** * Constructor that takes in a configContext */ public SforceServiceStub(org.apache.axis2.context.ConfigurationContext configurationContext, java.lang.String targetEndpoint) throws org.apache.axis2.AxisFault { this(configurationContext, targetEndpoint, false); } /** * Constructor that takes in a configContext and useseperate listner */ public SforceServiceStub(org.apache.axis2.context.ConfigurationContext configurationContext, java.lang.String targetEndpoint, boolean useSeparateListener) throws org.apache.axis2.AxisFault { // To populate AxisService populateAxisService(); populateFaults(); _serviceClient = new org.apache.axis2.client.ServiceClient(configurationContext, _service); _serviceClient.getOptions().setTo(new org.apache.axis2.addressing.EndpointReference(targetEndpoint)); _serviceClient.getOptions().setUseSeparateListener(useSeparateListener); } /** * Default Constructor */ public SforceServiceStub(org.apache.axis2.context.ConfigurationContext configurationContext) throws org.apache.axis2.AxisFault { this(configurationContext, "https://login.salesforce.com/services/Soap/u/34.0"); } /** * Default Constructor */ public SforceServiceStub() throws org.apache.axis2.AxisFault { this("https://login.salesforce.com/services/Soap/u/34.0"); } /** * Constructor taking the target endpoint */ public SforceServiceStub(java.lang.String targetEndpoint) throws org.apache.axis2.AxisFault { this(null, targetEndpoint); } /** * Auto generated method signature Merge and update a set of sObjects based on object id * * @see com.salesforce.soap.partner.SforceService#merge * @param merge563 * * @param sessionHeader564 * * @param callOptions565 * * @param assignmentRuleHeader566 * * @param mruHeader567 * * @param allowFieldTruncationHeader568 * * @param disableFeedTrackingHeader569 * * @param streamingEnabledHeader570 * * @param duplicateRuleHeader571 * * @param localeOptions572 * * @param debuggingHeader573 * * @param packageVersionHeader574 * * @param emailHeader575 * * @throws com.salesforce.soap.partner.InvalidSObjectFault : * @throws com.salesforce.soap.partner.InvalidIdFault : * @throws com.salesforce.soap.partner.InvalidFieldFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.MergeResponse merge( com.salesforce.soap.partner.Merge merge563, com.salesforce.soap.partner.SessionHeader sessionHeader564, com.salesforce.soap.partner.CallOptions callOptions565, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader566, com.salesforce.soap.partner.MruHeader mruHeader567, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader568, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader569, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader570, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader571, com.salesforce.soap.partner.LocaleOptions localeOptions572, com.salesforce.soap.partner.DebuggingHeader debuggingHeader573, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader574, com.salesforce.soap.partner.EmailHeader emailHeader575) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidSObjectFault, com.salesforce.soap.partner.InvalidIdFault, com.salesforce.soap.partner.InvalidFieldFault, com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[0].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:mergeRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), merge563, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge")); env.build(); // add the children only if the parameter is not null if (sessionHeader564 != null) { org.apache.axiom.om.OMElement omElementsessionHeader564 = toOM(sessionHeader564, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementsessionHeader564, env); } // add the children only if the parameter is not null if (callOptions565 != null) { org.apache.axiom.om.OMElement omElementcallOptions565 = toOM(callOptions565, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementcallOptions565, env); } // add the children only if the parameter is not null if (assignmentRuleHeader566 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader566 = toOM(assignmentRuleHeader566, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementassignmentRuleHeader566, env); } // add the children only if the parameter is not null if (mruHeader567 != null) { org.apache.axiom.om.OMElement omElementmruHeader567 = toOM(mruHeader567, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementmruHeader567, env); } // add the children only if the parameter is not null if (allowFieldTruncationHeader568 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader568 = toOM(allowFieldTruncationHeader568, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementallowFieldTruncationHeader568, env); } // add the children only if the parameter is not null if (disableFeedTrackingHeader569 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader569 = toOM(disableFeedTrackingHeader569, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementdisableFeedTrackingHeader569, env); } // add the children only if the parameter is not null if (streamingEnabledHeader570 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader570 = toOM(streamingEnabledHeader570, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementstreamingEnabledHeader570, env); } // add the children only if the parameter is not null if (duplicateRuleHeader571 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader571 = toOM(duplicateRuleHeader571, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementduplicateRuleHeader571, env); } // add the children only if the parameter is not null if (localeOptions572 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions572 = toOM(localeOptions572, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementlocaleOptions572, env); } // add the children only if the parameter is not null if (debuggingHeader573 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader573 = toOM(debuggingHeader573, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementdebuggingHeader573, env); } // add the children only if the parameter is not null if (packageVersionHeader574 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader574 = toOM(packageVersionHeader574, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementpackageVersionHeader574, env); } // add the children only if the parameter is not null if (emailHeader575 != null) { org.apache.axiom.om.OMElement omElementemailHeader575 = toOM(emailHeader575, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementemailHeader575, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.MergeResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.MergeResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { throw (com.salesforce.soap.partner.InvalidSObjectFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { throw (com.salesforce.soap.partner.InvalidIdFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { throw (com.salesforce.soap.partner.InvalidFieldFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Merge and update a set of sObjects based on object id * * @see com.salesforce.soap.partner.SforceService#startmerge * @param merge563 * * @param sessionHeader564 * * @param callOptions565 * * @param assignmentRuleHeader566 * * @param mruHeader567 * * @param allowFieldTruncationHeader568 * * @param disableFeedTrackingHeader569 * * @param streamingEnabledHeader570 * * @param duplicateRuleHeader571 * * @param localeOptions572 * * @param debuggingHeader573 * * @param packageVersionHeader574 * * @param emailHeader575 */ public void startmerge( com.salesforce.soap.partner.Merge merge563, com.salesforce.soap.partner.SessionHeader sessionHeader564, com.salesforce.soap.partner.CallOptions callOptions565, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader566, com.salesforce.soap.partner.MruHeader mruHeader567, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader568, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader569, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader570, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader571, com.salesforce.soap.partner.LocaleOptions localeOptions572, com.salesforce.soap.partner.DebuggingHeader debuggingHeader573, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader574, com.salesforce.soap.partner.EmailHeader emailHeader575, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[0].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:mergeRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), merge563, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge")); // add the soap_headers only if they are not null if (sessionHeader564 != null) { org.apache.axiom.om.OMElement omElementsessionHeader564 = toOM(sessionHeader564, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementsessionHeader564, env); } // add the soap_headers only if they are not null if (callOptions565 != null) { org.apache.axiom.om.OMElement omElementcallOptions565 = toOM(callOptions565, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementcallOptions565, env); } // add the soap_headers only if they are not null if (assignmentRuleHeader566 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader566 = toOM(assignmentRuleHeader566, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementassignmentRuleHeader566, env); } // add the soap_headers only if they are not null if (mruHeader567 != null) { org.apache.axiom.om.OMElement omElementmruHeader567 = toOM(mruHeader567, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementmruHeader567, env); } // add the soap_headers only if they are not null if (allowFieldTruncationHeader568 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader568 = toOM(allowFieldTruncationHeader568, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementallowFieldTruncationHeader568, env); } // add the soap_headers only if they are not null if (disableFeedTrackingHeader569 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader569 = toOM(disableFeedTrackingHeader569, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementdisableFeedTrackingHeader569, env); } // add the soap_headers only if they are not null if (streamingEnabledHeader570 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader570 = toOM(streamingEnabledHeader570, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementstreamingEnabledHeader570, env); } // add the soap_headers only if they are not null if (duplicateRuleHeader571 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader571 = toOM(duplicateRuleHeader571, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementduplicateRuleHeader571, env); } // add the soap_headers only if they are not null if (localeOptions572 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions572 = toOM(localeOptions572, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementlocaleOptions572, env); } // add the soap_headers only if they are not null if (debuggingHeader573 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader573 = toOM(debuggingHeader573, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementdebuggingHeader573, env); } // add the soap_headers only if they are not null if (packageVersionHeader574 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader574 = toOM(packageVersionHeader574, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementpackageVersionHeader574, env); } // add the soap_headers only if they are not null if (emailHeader575 != null) { org.apache.axiom.om.OMElement omElementemailHeader575 = toOM(emailHeader575, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "merge"))); addHeader(omElementemailHeader575, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.MergeResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultmerge((com.salesforce.soap.partner.MergeResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrormerge(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "merge")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { callback.receiveErrormerge((com.salesforce.soap.partner.InvalidSObjectFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { callback.receiveErrormerge((com.salesforce.soap.partner.InvalidIdFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { callback.receiveErrormerge((com.salesforce.soap.partner.InvalidFieldFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrormerge((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrormerge(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrormerge(f); } } else { callback.receiveErrormerge(f); } } else { callback.receiveErrormerge(f); } } else { callback.receiveErrormerge(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrormerge(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[0].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[0].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Returns standard information relevant to the current user * * @see com.salesforce.soap.partner.SforceService#getUserInfo * @param getUserInfo577 * * @param sessionHeader578 * * @param callOptions579 * * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.GetUserInfoResponse getUserInfo( com.salesforce.soap.partner.GetUserInfo getUserInfo577, com.salesforce.soap.partner.SessionHeader sessionHeader578, com.salesforce.soap.partner.CallOptions callOptions579) throws java.rmi.RemoteException , com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[1].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:getUserInfoRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), getUserInfo577, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo")); env.build(); // add the children only if the parameter is not null if (sessionHeader578 != null) { org.apache.axiom.om.OMElement omElementsessionHeader578 = toOM(sessionHeader578, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo"))); addHeader(omElementsessionHeader578, env); } // add the children only if the parameter is not null if (callOptions579 != null) { org.apache.axiom.om.OMElement omElementcallOptions579 = toOM(callOptions579, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo"))); addHeader(omElementcallOptions579, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.GetUserInfoResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.GetUserInfoResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap .containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Returns standard information relevant to the current user * * @see com.salesforce.soap.partner.SforceService#startgetUserInfo * @param getUserInfo577 * * @param sessionHeader578 * * @param callOptions579 */ public void startgetUserInfo( com.salesforce.soap.partner.GetUserInfo getUserInfo577, com.salesforce.soap.partner.SessionHeader sessionHeader578, com.salesforce.soap.partner.CallOptions callOptions579, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[1].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:getUserInfoRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), getUserInfo577, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo")); // add the soap_headers only if they are not null if (sessionHeader578 != null) { org.apache.axiom.om.OMElement omElementsessionHeader578 = toOM(sessionHeader578, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo"))); addHeader(omElementsessionHeader578, env); } // add the soap_headers only if they are not null if (callOptions579 != null) { org.apache.axiom.om.OMElement omElementcallOptions579 = toOM(callOptions579, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUserInfo"))); addHeader(omElementcallOptions579, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.GetUserInfoResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultgetUserInfo((com.salesforce.soap.partner.GetUserInfoResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorgetUserInfo(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUserInfo")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorgetUserInfo((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrorgetUserInfo(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorgetUserInfo(f); } } else { callback.receiveErrorgetUserInfo(f); } } else { callback.receiveErrorgetUserInfo(f); } } else { callback.receiveErrorgetUserInfo(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorgetUserInfo(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[1].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[1].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Describe all tabs available to a user * * @see com.salesforce.soap.partner.SforceService#describeAllTabs * @param describeAllTabs581 * * @param sessionHeader582 * * @param callOptions583 * * @param packageVersionHeader584 * * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.DescribeAllTabsResponse describeAllTabs( com.salesforce.soap.partner.DescribeAllTabs describeAllTabs581, com.salesforce.soap.partner.SessionHeader sessionHeader582, com.salesforce.soap.partner.CallOptions callOptions583, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader584) throws java.rmi.RemoteException , com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[2].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeAllTabsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeAllTabs581, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs")); env.build(); // add the children only if the parameter is not null if (sessionHeader582 != null) { org.apache.axiom.om.OMElement omElementsessionHeader582 = toOM(sessionHeader582, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementsessionHeader582, env); } // add the children only if the parameter is not null if (callOptions583 != null) { org.apache.axiom.om.OMElement omElementcallOptions583 = toOM(callOptions583, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementcallOptions583, env); } // add the children only if the parameter is not null if (packageVersionHeader584 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader584 = toOM(packageVersionHeader584, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementpackageVersionHeader584, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeAllTabsResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.DescribeAllTabsResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Describe all tabs available to a user * * @see com.salesforce.soap.partner.SforceService#startdescribeAllTabs * @param describeAllTabs581 * * @param sessionHeader582 * * @param callOptions583 * * @param packageVersionHeader584 */ public void startdescribeAllTabs( com.salesforce.soap.partner.DescribeAllTabs describeAllTabs581, com.salesforce.soap.partner.SessionHeader sessionHeader582, com.salesforce.soap.partner.CallOptions callOptions583, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader584, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[2].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeAllTabsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeAllTabs581, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs")); // add the soap_headers only if they are not null if (sessionHeader582 != null) { org.apache.axiom.om.OMElement omElementsessionHeader582 = toOM(sessionHeader582, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementsessionHeader582, env); } // add the soap_headers only if they are not null if (callOptions583 != null) { org.apache.axiom.om.OMElement omElementcallOptions583 = toOM(callOptions583, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementcallOptions583, env); } // add the soap_headers only if they are not null if (packageVersionHeader584 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader584 = toOM(packageVersionHeader584, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeAllTabs"))); addHeader(omElementpackageVersionHeader584, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeAllTabsResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultdescribeAllTabs((com.salesforce.soap.partner.DescribeAllTabsResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrordescribeAllTabs(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeAllTabs")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrordescribeAllTabs((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrordescribeAllTabs(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeAllTabs(f); } } else { callback.receiveErrordescribeAllTabs(f); } } else { callback.receiveErrordescribeAllTabs(f); } } else { callback.receiveErrordescribeAllTabs(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrordescribeAllTabs(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[2].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[2].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Describe the details of a series of quick actions * * @see com.salesforce.soap.partner.SforceService#describeQuickActions * @param describeQuickActions586 * * @param sessionHeader587 * * @param callOptions588 * * @param packageVersionHeader589 * * @param localeOptions590 */ public com.salesforce.soap.partner.DescribeQuickActionsResponse describeQuickActions( com.salesforce.soap.partner.DescribeQuickActions describeQuickActions586, com.salesforce.soap.partner.SessionHeader sessionHeader587, com.salesforce.soap.partner.CallOptions callOptions588, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader589, com.salesforce.soap.partner.LocaleOptions localeOptions590) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[3].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeQuickActionsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeQuickActions586, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions")); env.build(); // add the children only if the parameter is not null if (sessionHeader587 != null) { org.apache.axiom.om.OMElement omElementsessionHeader587 = toOM(sessionHeader587, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementsessionHeader587, env); } // add the children only if the parameter is not null if (callOptions588 != null) { org.apache.axiom.om.OMElement omElementcallOptions588 = toOM(callOptions588, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementcallOptions588, env); } // add the children only if the parameter is not null if (packageVersionHeader589 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader589 = toOM(packageVersionHeader589, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementpackageVersionHeader589, env); } // add the children only if the parameter is not null if (localeOptions590 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions590 = toOM(localeOptions590, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementlocaleOptions590, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeQuickActionsResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.DescribeQuickActionsResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Describe the details of a series of quick actions * * @see com.salesforce.soap.partner.SforceService#startdescribeQuickActions * @param describeQuickActions586 * * @param sessionHeader587 * * @param callOptions588 * * @param packageVersionHeader589 * * @param localeOptions590 */ public void startdescribeQuickActions( com.salesforce.soap.partner.DescribeQuickActions describeQuickActions586, com.salesforce.soap.partner.SessionHeader sessionHeader587, com.salesforce.soap.partner.CallOptions callOptions588, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader589, com.salesforce.soap.partner.LocaleOptions localeOptions590, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[3].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeQuickActionsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeQuickActions586, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions")); // add the soap_headers only if they are not null if (sessionHeader587 != null) { org.apache.axiom.om.OMElement omElementsessionHeader587 = toOM(sessionHeader587, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementsessionHeader587, env); } // add the soap_headers only if they are not null if (callOptions588 != null) { org.apache.axiom.om.OMElement omElementcallOptions588 = toOM(callOptions588, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementcallOptions588, env); } // add the soap_headers only if they are not null if (packageVersionHeader589 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader589 = toOM(packageVersionHeader589, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementpackageVersionHeader589, env); } // add the soap_headers only if they are not null if (localeOptions590 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions590 = toOM(localeOptions590, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeQuickActions"))); addHeader(omElementlocaleOptions590, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeQuickActionsResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultdescribeQuickActions((com.salesforce.soap.partner.DescribeQuickActionsResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrordescribeQuickActions(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeQuickActions")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); callback.receiveErrordescribeQuickActions(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeQuickActions(f); } } else { callback.receiveErrordescribeQuickActions(f); } } else { callback.receiveErrordescribeQuickActions(f); } } else { callback.receiveErrordescribeQuickActions(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrordescribeQuickActions(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[3].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[3].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Describe the layout of the SoftPhone * * @see com.salesforce.soap.partner.SforceService#describeSoftphoneLayout * @param describeSoftphoneLayout592 * * @param sessionHeader593 * * @param callOptions594 * * @param packageVersionHeader595 * * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.DescribeSoftphoneLayoutResponse describeSoftphoneLayout( com.salesforce.soap.partner.DescribeSoftphoneLayout describeSoftphoneLayout592, com.salesforce.soap.partner.SessionHeader sessionHeader593, com.salesforce.soap.partner.CallOptions callOptions594, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader595) throws java.rmi.RemoteException , com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[4].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeSoftphoneLayoutRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeSoftphoneLayout592, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout")); env.build(); // add the children only if the parameter is not null if (sessionHeader593 != null) { org.apache.axiom.om.OMElement omElementsessionHeader593 = toOM(sessionHeader593, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementsessionHeader593, env); } // add the children only if the parameter is not null if (callOptions594 != null) { org.apache.axiom.om.OMElement omElementcallOptions594 = toOM(callOptions594, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementcallOptions594, env); } // add the children only if the parameter is not null if (packageVersionHeader595 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader595 = toOM(packageVersionHeader595, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementpackageVersionHeader595, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeSoftphoneLayoutResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.DescribeSoftphoneLayoutResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Describe the layout of the SoftPhone * * @see com.salesforce.soap.partner.SforceService#startdescribeSoftphoneLayout * @param describeSoftphoneLayout592 * * @param sessionHeader593 * * @param callOptions594 * * @param packageVersionHeader595 */ public void startdescribeSoftphoneLayout( com.salesforce.soap.partner.DescribeSoftphoneLayout describeSoftphoneLayout592, com.salesforce.soap.partner.SessionHeader sessionHeader593, com.salesforce.soap.partner.CallOptions callOptions594, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader595, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[4].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describeSoftphoneLayoutRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describeSoftphoneLayout592, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout")); // add the soap_headers only if they are not null if (sessionHeader593 != null) { org.apache.axiom.om.OMElement omElementsessionHeader593 = toOM(sessionHeader593, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementsessionHeader593, env); } // add the soap_headers only if they are not null if (callOptions594 != null) { org.apache.axiom.om.OMElement omElementcallOptions594 = toOM(callOptions594, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementcallOptions594, env); } // add the soap_headers only if they are not null if (packageVersionHeader595 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader595 = toOM(packageVersionHeader595, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describeSoftphoneLayout"))); addHeader(omElementpackageVersionHeader595, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribeSoftphoneLayoutResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultdescribeSoftphoneLayout((com.salesforce.soap.partner.DescribeSoftphoneLayoutResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrordescribeSoftphoneLayout(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describeSoftphoneLayout")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrordescribeSoftphoneLayout((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrordescribeSoftphoneLayout(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribeSoftphoneLayout(f); } } else { callback.receiveErrordescribeSoftphoneLayout(f); } } else { callback.receiveErrordescribeSoftphoneLayout(f); } } else { callback.receiveErrordescribeSoftphoneLayout(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrordescribeSoftphoneLayout(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[4].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[4].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Describe the primary compact layouts for the sObjects requested * * @see com.salesforce.soap.partner.SforceService#describePrimaryCompactLayouts * @param describePrimaryCompactLayouts597 * * @param sessionHeader598 * * @param callOptions599 * * @param packageVersionHeader600 */ public com.salesforce.soap.partner.DescribePrimaryCompactLayoutsResponse describePrimaryCompactLayouts( com.salesforce.soap.partner.DescribePrimaryCompactLayouts describePrimaryCompactLayouts597, com.salesforce.soap.partner.SessionHeader sessionHeader598, com.salesforce.soap.partner.CallOptions callOptions599, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader600) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[5].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describePrimaryCompactLayoutsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope( getFactory(_operationClient.getOptions().getSoapVersionURI()), describePrimaryCompactLayouts597, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts")); env.build(); // add the children only if the parameter is not null if (sessionHeader598 != null) { org.apache.axiom.om.OMElement omElementsessionHeader598 = toOM(sessionHeader598, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementsessionHeader598, env); } // add the children only if the parameter is not null if (callOptions599 != null) { org.apache.axiom.om.OMElement omElementcallOptions599 = toOM(callOptions599, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementcallOptions599, env); } // add the children only if the parameter is not null if (packageVersionHeader600 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader600 = toOM(packageVersionHeader600, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementpackageVersionHeader600, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribePrimaryCompactLayoutsResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.DescribePrimaryCompactLayoutsResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Describe the primary compact layouts for the sObjects requested * * @see com.salesforce.soap.partner.SforceService#startdescribePrimaryCompactLayouts * @param describePrimaryCompactLayouts597 * * @param sessionHeader598 * * @param callOptions599 * * @param packageVersionHeader600 */ public void startdescribePrimaryCompactLayouts( com.salesforce.soap.partner.DescribePrimaryCompactLayouts describePrimaryCompactLayouts597, com.salesforce.soap.partner.SessionHeader sessionHeader598, com.salesforce.soap.partner.CallOptions callOptions599, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader600, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[5].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:describePrimaryCompactLayoutsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), describePrimaryCompactLayouts597, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts")); // add the soap_headers only if they are not null if (sessionHeader598 != null) { org.apache.axiom.om.OMElement omElementsessionHeader598 = toOM( sessionHeader598, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementsessionHeader598, env); } // add the soap_headers only if they are not null if (callOptions599 != null) { org.apache.axiom.om.OMElement omElementcallOptions599 = toOM( callOptions599, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementcallOptions599, env); } // add the soap_headers only if they are not null if (packageVersionHeader600 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader600 = toOM( packageVersionHeader600, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "describePrimaryCompactLayouts"))); addHeader(omElementpackageVersionHeader600, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.DescribePrimaryCompactLayoutsResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultdescribePrimaryCompactLayouts((com.salesforce.soap.partner.DescribePrimaryCompactLayoutsResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrordescribePrimaryCompactLayouts(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "describePrimaryCompactLayouts")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); callback.receiveErrordescribePrimaryCompactLayouts(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrordescribePrimaryCompactLayouts(f); } } else { callback.receiveErrordescribePrimaryCompactLayouts(f); } } else { callback.receiveErrordescribePrimaryCompactLayouts(f); } } else { callback.receiveErrordescribePrimaryCompactLayouts(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrordescribePrimaryCompactLayouts(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[5].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[5].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Execute the specified list view and return the presentation-ready results. * * @see com.salesforce.soap.partner.SforceService#executeListView * @param executeListView602 * * @param sessionHeader603 * * @param callOptions604 * * @param mruHeader605 */ public com.salesforce.soap.partner.ExecuteListViewResponse executeListView( com.salesforce.soap.partner.ExecuteListView executeListView602, com.salesforce.soap.partner.SessionHeader sessionHeader603, com.salesforce.soap.partner.CallOptions callOptions604, com.salesforce.soap.partner.MruHeader mruHeader605) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[6].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:executeListViewRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), executeListView602, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView")); env.build(); // add the children only if the parameter is not null if (sessionHeader603 != null) { org.apache.axiom.om.OMElement omElementsessionHeader603 = toOM(sessionHeader603, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementsessionHeader603, env); } // add the children only if the parameter is not null if (callOptions604 != null) { org.apache.axiom.om.OMElement omElementcallOptions604 = toOM(callOptions604, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementcallOptions604, env); } // add the children only if the parameter is not null if (mruHeader605 != null) { org.apache.axiom.om.OMElement omElementmruHeader605 = toOM(mruHeader605, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementmruHeader605, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.ExecuteListViewResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.ExecuteListViewResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Execute the specified list view and return the presentation-ready * results. * * @see com.salesforce.soap.partner.SforceService#startexecuteListView * @param executeListView602 * * @param sessionHeader603 * * @param callOptions604 * * @param mruHeader605 */ public void startexecuteListView( com.salesforce.soap.partner.ExecuteListView executeListView602, com.salesforce.soap.partner.SessionHeader sessionHeader603, com.salesforce.soap.partner.CallOptions callOptions604, com.salesforce.soap.partner.MruHeader mruHeader605, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[6].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:executeListViewRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), executeListView602, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView")); // add the soap_headers only if they are not null if (sessionHeader603 != null) { org.apache.axiom.om.OMElement omElementsessionHeader603 = toOM(sessionHeader603, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementsessionHeader603, env); } // add the soap_headers only if they are not null if (callOptions604 != null) { org.apache.axiom.om.OMElement omElementcallOptions604 = toOM(callOptions604, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementcallOptions604, env); } // add the soap_headers only if they are not null if (mruHeader605 != null) { org.apache.axiom.om.OMElement omElementmruHeader605 = toOM(mruHeader605, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "executeListView"))); addHeader(omElementmruHeader605, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.ExecuteListViewResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultexecuteListView((com.salesforce.soap.partner.ExecuteListViewResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorexecuteListView(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "executeListView")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); callback.receiveErrorexecuteListView(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorexecuteListView(f); } } else { callback.receiveErrorexecuteListView(f); } } else { callback.receiveErrorexecuteListView(f); } } else { callback.receiveErrorexecuteListView(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorexecuteListView(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[6].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[6].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Update a set of sObjects * * @see com.salesforce.soap.partner.SforceService#update * @param update607 * * @param sessionHeader608 * * @param callOptions609 * * @param assignmentRuleHeader610 * * @param mruHeader611 * * @param allowFieldTruncationHeader612 * * @param disableFeedTrackingHeader613 * * @param streamingEnabledHeader614 * * @param allOrNoneHeader615 * * @param duplicateRuleHeader616 * * @param localeOptions617 * * @param debuggingHeader618 * * @param packageVersionHeader619 * * @param emailHeader620 * * @param ownerChangeOptions621 * * @throws com.salesforce.soap.partner.InvalidSObjectFault : * @throws com.salesforce.soap.partner.InvalidIdFault : * @throws com.salesforce.soap.partner.InvalidFieldFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.UpdateResponse update( com.salesforce.soap.partner.Update update607, com.salesforce.soap.partner.SessionHeader sessionHeader608, com.salesforce.soap.partner.CallOptions callOptions609, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader610, com.salesforce.soap.partner.MruHeader mruHeader611, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader612, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader613, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader614, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader615, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader616, com.salesforce.soap.partner.LocaleOptions localeOptions617, com.salesforce.soap.partner.DebuggingHeader debuggingHeader618, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader619, com.salesforce.soap.partner.EmailHeader emailHeader620, com.salesforce.soap.partner.OwnerChangeOptions ownerChangeOptions621) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidSObjectFault, com.salesforce.soap.partner.InvalidIdFault, com.salesforce.soap.partner.InvalidFieldFault, com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[7].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:updateRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), update607, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update")); env.build(); // add the children only if the parameter is not null if (sessionHeader608 != null) { org.apache.axiom.om.OMElement omElementsessionHeader608 = toOM(sessionHeader608, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementsessionHeader608, env); } // add the children only if the parameter is not null if (callOptions609 != null) { org.apache.axiom.om.OMElement omElementcallOptions609 = toOM(callOptions609, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementcallOptions609, env); } // add the children only if the parameter is not null if (assignmentRuleHeader610 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader610 = toOM(assignmentRuleHeader610, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementassignmentRuleHeader610, env); } // add the children only if the parameter is not null if (mruHeader611 != null) { org.apache.axiom.om.OMElement omElementmruHeader611 = toOM(mruHeader611, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementmruHeader611, env); } // add the children only if the parameter is not null if (allowFieldTruncationHeader612 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader612 = toOM(allowFieldTruncationHeader612, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementallowFieldTruncationHeader612, env); } // add the children only if the parameter is not null if (disableFeedTrackingHeader613 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader613 = toOM(disableFeedTrackingHeader613, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementdisableFeedTrackingHeader613, env); } // add the children only if the parameter is not null if (streamingEnabledHeader614 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader614 = toOM(streamingEnabledHeader614, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementstreamingEnabledHeader614, env); } // add the children only if the parameter is not null if (allOrNoneHeader615 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader615 = toOM(allOrNoneHeader615, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementallOrNoneHeader615, env); } // add the children only if the parameter is not null if (duplicateRuleHeader616 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader616 = toOM(duplicateRuleHeader616, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementduplicateRuleHeader616, env); } // add the children only if the parameter is not null if (localeOptions617 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions617 = toOM(localeOptions617, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementlocaleOptions617, env); } // add the children only if the parameter is not null if (debuggingHeader618 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader618 = toOM(debuggingHeader618, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementdebuggingHeader618, env); } // add the children only if the parameter is not null if (packageVersionHeader619 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader619 = toOM(packageVersionHeader619, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementpackageVersionHeader619, env); } // add the children only if the parameter is not null if (emailHeader620 != null) { org.apache.axiom.om.OMElement omElementemailHeader620 = toOM(emailHeader620, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementemailHeader620, env); } // add the children only if the parameter is not null if (ownerChangeOptions621 != null) { org.apache.axiom.om.OMElement omElementownerChangeOptions621 = toOM(ownerChangeOptions621, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementownerChangeOptions621, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.UpdateResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.UpdateResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { throw (com.salesforce.soap.partner.InvalidSObjectFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { throw (com.salesforce.soap.partner.InvalidIdFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { throw (com.salesforce.soap.partner.InvalidFieldFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Update a set of sObjects * * @see com.salesforce.soap.partner.SforceService#startupdate * @param update607 * * @param sessionHeader608 * * @param callOptions609 * * @param assignmentRuleHeader610 * * @param mruHeader611 * * @param allowFieldTruncationHeader612 * * @param disableFeedTrackingHeader613 * * @param streamingEnabledHeader614 * * @param allOrNoneHeader615 * * @param duplicateRuleHeader616 * * @param localeOptions617 * * @param debuggingHeader618 * * @param packageVersionHeader619 * * @param emailHeader620 * * @param ownerChangeOptions621 */ public void startupdate( com.salesforce.soap.partner.Update update607, com.salesforce.soap.partner.SessionHeader sessionHeader608, com.salesforce.soap.partner.CallOptions callOptions609, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader610, com.salesforce.soap.partner.MruHeader mruHeader611, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader612, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader613, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader614, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader615, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader616, com.salesforce.soap.partner.LocaleOptions localeOptions617, com.salesforce.soap.partner.DebuggingHeader debuggingHeader618, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader619, com.salesforce.soap.partner.EmailHeader emailHeader620, com.salesforce.soap.partner.OwnerChangeOptions ownerChangeOptions621, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[7].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:updateRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), update607, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update")); // add the soap_headers only if they are not null if (sessionHeader608 != null) { org.apache.axiom.om.OMElement omElementsessionHeader608 = toOM(sessionHeader608, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementsessionHeader608, env); } // add the soap_headers only if they are not null if (callOptions609 != null) { org.apache.axiom.om.OMElement omElementcallOptions609 = toOM(callOptions609, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementcallOptions609, env); } // add the soap_headers only if they are not null if (assignmentRuleHeader610 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader610 = toOM(assignmentRuleHeader610, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementassignmentRuleHeader610, env); } // add the soap_headers only if they are not null if (mruHeader611 != null) { org.apache.axiom.om.OMElement omElementmruHeader611 = toOM(mruHeader611, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementmruHeader611, env); } // add the soap_headers only if they are not null if (allowFieldTruncationHeader612 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader612 = toOM(allowFieldTruncationHeader612, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementallowFieldTruncationHeader612, env); } // add the soap_headers only if they are not null if (disableFeedTrackingHeader613 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader613 = toOM(disableFeedTrackingHeader613, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementdisableFeedTrackingHeader613, env); } // add the soap_headers only if they are not null if (streamingEnabledHeader614 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader614 = toOM(streamingEnabledHeader614, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementstreamingEnabledHeader614, env); } // add the soap_headers only if they are not null if (allOrNoneHeader615 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader615 = toOM(allOrNoneHeader615, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementallOrNoneHeader615, env); } // add the soap_headers only if they are not null if (duplicateRuleHeader616 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader616 = toOM(duplicateRuleHeader616, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementduplicateRuleHeader616, env); } // add the soap_headers only if they are not null if (localeOptions617 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions617 = toOM(localeOptions617, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementlocaleOptions617, env); } // add the soap_headers only if they are not null if (debuggingHeader618 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader618 = toOM(debuggingHeader618, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementdebuggingHeader618, env); } // add the soap_headers only if they are not null if (packageVersionHeader619 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader619 = toOM(packageVersionHeader619, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementpackageVersionHeader619, env); } // add the soap_headers only if they are not null if (emailHeader620 != null) { org.apache.axiom.om.OMElement omElementemailHeader620 = toOM(emailHeader620, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementemailHeader620, env); } // add the soap_headers only if they are not null if (ownerChangeOptions621 != null) { org.apache.axiom.om.OMElement omElementownerChangeOptions621 = toOM(ownerChangeOptions621, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "update"))); addHeader(omElementownerChangeOptions621, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.UpdateResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultupdate((com.salesforce.soap.partner.UpdateResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorupdate(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "update")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { callback.receiveErrorupdate((com.salesforce.soap.partner.InvalidSObjectFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { callback.receiveErrorupdate((com.salesforce.soap.partner.InvalidIdFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { callback.receiveErrorupdate((com.salesforce.soap.partner.InvalidFieldFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorupdate((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrorupdate(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorupdate(f); } } else { callback.receiveErrorupdate(f); } } else { callback.receiveErrorupdate(f); } } else { callback.receiveErrorupdate(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorupdate(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[7].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[7].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Perform a series of predefined actions such as quick create or log a task * * @see com.salesforce.soap.partner.SforceService#performQuickActions * @param performQuickActions623 * * @param sessionHeader624 * * @param callOptions625 * * @param assignmentRuleHeader626 * * @param mruHeader627 * * @param allowFieldTruncationHeader628 * * @param disableFeedTrackingHeader629 * * @param streamingEnabledHeader630 * * @param allOrNoneHeader631 * * @param duplicateRuleHeader632 * * @param localeOptions633 * * @param debuggingHeader634 * * @param packageVersionHeader635 * * @param emailHeader636 * * @param ownerChangeOptions637 */ public com.salesforce.soap.partner.PerformQuickActionsResponse performQuickActions( com.salesforce.soap.partner.PerformQuickActions performQuickActions623, com.salesforce.soap.partner.SessionHeader sessionHeader624, com.salesforce.soap.partner.CallOptions callOptions625, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader626, com.salesforce.soap.partner.MruHeader mruHeader627, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader628, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader629, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader630, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader631, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader632, com.salesforce.soap.partner.LocaleOptions localeOptions633, com.salesforce.soap.partner.DebuggingHeader debuggingHeader634, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader635, com.salesforce.soap.partner.EmailHeader emailHeader636, com.salesforce.soap.partner.OwnerChangeOptions ownerChangeOptions637) throws java.rmi.RemoteException { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[8].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:performQuickActionsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), performQuickActions623, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions")); env.build(); // add the children only if the parameter is not null if (sessionHeader624 != null) { org.apache.axiom.om.OMElement omElementsessionHeader624 = toOM(sessionHeader624, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementsessionHeader624, env); } // add the children only if the parameter is not null if (callOptions625 != null) { org.apache.axiom.om.OMElement omElementcallOptions625 = toOM(callOptions625, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementcallOptions625, env); } // add the children only if the parameter is not null if (assignmentRuleHeader626 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader626 = toOM(assignmentRuleHeader626, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementassignmentRuleHeader626, env); } // add the children only if the parameter is not null if (mruHeader627 != null) { org.apache.axiom.om.OMElement omElementmruHeader627 = toOM(mruHeader627, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementmruHeader627, env); } // add the children only if the parameter is not null if (allowFieldTruncationHeader628 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader628 = toOM(allowFieldTruncationHeader628, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementallowFieldTruncationHeader628, env); } // add the children only if the parameter is not null if (disableFeedTrackingHeader629 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader629 = toOM(disableFeedTrackingHeader629, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementdisableFeedTrackingHeader629, env); } // add the children only if the parameter is not null if (streamingEnabledHeader630 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader630 = toOM(streamingEnabledHeader630, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementstreamingEnabledHeader630, env); } // add the children only if the parameter is not null if (allOrNoneHeader631 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader631 = toOM(allOrNoneHeader631, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementallOrNoneHeader631, env); } // add the children only if the parameter is not null if (duplicateRuleHeader632 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader632 = toOM(duplicateRuleHeader632, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementduplicateRuleHeader632, env); } // add the children only if the parameter is not null if (localeOptions633 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions633 = toOM(localeOptions633, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementlocaleOptions633, env); } // add the children only if the parameter is not null if (debuggingHeader634 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader634 = toOM(debuggingHeader634, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementdebuggingHeader634, env); } // add the children only if the parameter is not null if (packageVersionHeader635 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader635 = toOM(packageVersionHeader635, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementpackageVersionHeader635, env); } // add the children only if the parameter is not null if (emailHeader636 != null) { org.apache.axiom.om.OMElement omElementemailHeader636 = toOM(emailHeader636, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementemailHeader636, env); } // add the children only if the parameter is not null if (ownerChangeOptions637 != null) { org.apache.axiom.om.OMElement omElementownerChangeOptions637 = toOM(ownerChangeOptions637, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementownerChangeOptions637, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.PerformQuickActionsResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.PerformQuickActionsResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Perform a series of predefined actions such as quick create or log a * task * * @see com.salesforce.soap.partner.SforceService#startperformQuickActions * @param performQuickActions623 * * @param sessionHeader624 * * @param callOptions625 * * @param assignmentRuleHeader626 * * @param mruHeader627 * * @param allowFieldTruncationHeader628 * * @param disableFeedTrackingHeader629 * * @param streamingEnabledHeader630 * * @param allOrNoneHeader631 * * @param duplicateRuleHeader632 * * @param localeOptions633 * * @param debuggingHeader634 * * @param packageVersionHeader635 * * @param emailHeader636 * * @param ownerChangeOptions637 */ public void startperformQuickActions( com.salesforce.soap.partner.PerformQuickActions performQuickActions623, com.salesforce.soap.partner.SessionHeader sessionHeader624, com.salesforce.soap.partner.CallOptions callOptions625, com.salesforce.soap.partner.AssignmentRuleHeader assignmentRuleHeader626, com.salesforce.soap.partner.MruHeader mruHeader627, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader628, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader629, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader630, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader631, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader632, com.salesforce.soap.partner.LocaleOptions localeOptions633, com.salesforce.soap.partner.DebuggingHeader debuggingHeader634, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader635, com.salesforce.soap.partner.EmailHeader emailHeader636, com.salesforce.soap.partner.OwnerChangeOptions ownerChangeOptions637, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[8].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:performQuickActionsRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), performQuickActions623, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions")); // add the soap_headers only if they are not null if (sessionHeader624 != null) { org.apache.axiom.om.OMElement omElementsessionHeader624 = toOM(sessionHeader624, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementsessionHeader624, env); } // add the soap_headers only if they are not null if (callOptions625 != null) { org.apache.axiom.om.OMElement omElementcallOptions625 = toOM(callOptions625, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementcallOptions625, env); } // add the soap_headers only if they are not null if (assignmentRuleHeader626 != null) { org.apache.axiom.om.OMElement omElementassignmentRuleHeader626 = toOM(assignmentRuleHeader626, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementassignmentRuleHeader626, env); } // add the soap_headers only if they are not null if (mruHeader627 != null) { org.apache.axiom.om.OMElement omElementmruHeader627 = toOM(mruHeader627, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementmruHeader627, env); } // add the soap_headers only if they are not null if (allowFieldTruncationHeader628 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader628 = toOM(allowFieldTruncationHeader628, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementallowFieldTruncationHeader628, env); } // add the soap_headers only if they are not null if (disableFeedTrackingHeader629 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader629 = toOM(disableFeedTrackingHeader629, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementdisableFeedTrackingHeader629, env); } // add the soap_headers only if they are not null if (streamingEnabledHeader630 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader630 = toOM(streamingEnabledHeader630, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementstreamingEnabledHeader630, env); } // add the soap_headers only if they are not null if (allOrNoneHeader631 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader631 = toOM(allOrNoneHeader631, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementallOrNoneHeader631, env); } // add the soap_headers only if they are not null if (duplicateRuleHeader632 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader632 = toOM(duplicateRuleHeader632, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementduplicateRuleHeader632, env); } // add the soap_headers only if they are not null if (localeOptions633 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions633 = toOM(localeOptions633, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementlocaleOptions633, env); } // add the soap_headers only if they are not null if (debuggingHeader634 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader634 = toOM(debuggingHeader634, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementdebuggingHeader634, env); } // add the soap_headers only if they are not null if (packageVersionHeader635 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader635 = toOM(packageVersionHeader635, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementpackageVersionHeader635, env); } // add the soap_headers only if they are not null if (emailHeader636 != null) { org.apache.axiom.om.OMElement omElementemailHeader636 = toOM(emailHeader636, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementemailHeader636, env); } // add the soap_headers only if they are not null if (ownerChangeOptions637 != null) { org.apache.axiom.om.OMElement omElementownerChangeOptions637 = toOM(ownerChangeOptions637, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "performQuickActions"))); addHeader(omElementownerChangeOptions637, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.PerformQuickActionsResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultperformQuickActions((com.salesforce.soap.partner.PerformQuickActionsResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorperformQuickActions(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "performQuickActions")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); callback.receiveErrorperformQuickActions(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorperformQuickActions(f); } } else { callback.receiveErrorperformQuickActions(f); } } else { callback.receiveErrorperformQuickActions(f); } } else { callback.receiveErrorperformQuickActions(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorperformQuickActions(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[8].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[8].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Set a user's password * * @see com.salesforce.soap.partner.SforceService#setPassword * @param setPassword639 * * @param sessionHeader640 * * @param callOptions641 * * @throws com.salesforce.soap.partner.InvalidIdFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : * @throws com.salesforce.soap.partner.InvalidNewPasswordFault : */ public com.salesforce.soap.partner.SetPasswordResponse setPassword( com.salesforce.soap.partner.SetPassword setPassword639, com.salesforce.soap.partner.SessionHeader sessionHeader640, com.salesforce.soap.partner.CallOptions callOptions641) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidIdFault, com.salesforce.soap.partner.UnexpectedErrorFault, com.salesforce.soap.partner.InvalidNewPasswordFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[9].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:setPasswordRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), setPassword639, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword")); env.build(); // add the children only if the parameter is not null if (sessionHeader640 != null) { org.apache.axiom.om.OMElement omElementsessionHeader640 = toOM(sessionHeader640, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword"))); addHeader(omElementsessionHeader640, env); } // add the children only if the parameter is not null if (callOptions641 != null) { org.apache.axiom.om.OMElement omElementcallOptions641 = toOM(callOptions641, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword"))); addHeader(omElementcallOptions641, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.SetPasswordResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.SetPasswordResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap .containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { throw (com.salesforce.soap.partner.InvalidIdFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidNewPasswordFault) { throw (com.salesforce.soap.partner.InvalidNewPasswordFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Set a user's password * * @see com.salesforce.soap.partner.SforceService#startsetPassword * @param setPassword639 * * @param sessionHeader640 * * @param callOptions641 */ public void startsetPassword( com.salesforce.soap.partner.SetPassword setPassword639, com.salesforce.soap.partner.SessionHeader sessionHeader640, com.salesforce.soap.partner.CallOptions callOptions641, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[9].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:setPasswordRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), setPassword639, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword")); // add the soap_headers only if they are not null if (sessionHeader640 != null) { org.apache.axiom.om.OMElement omElementsessionHeader640 = toOM(sessionHeader640, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword"))); addHeader(omElementsessionHeader640, env); } // add the soap_headers only if they are not null if (callOptions641 != null) { org.apache.axiom.om.OMElement omElementcallOptions641 = toOM(callOptions641, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "setPassword"))); addHeader(omElementcallOptions641, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.SetPasswordResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultsetPassword((com.salesforce.soap.partner.SetPasswordResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorsetPassword(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "setPassword")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { callback.receiveErrorsetPassword((com.salesforce.soap.partner.InvalidIdFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorsetPassword((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidNewPasswordFault) { callback.receiveErrorsetPassword((com.salesforce.soap.partner.InvalidNewPasswordFault) ex); return; } callback.receiveErrorsetPassword(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorsetPassword(f); } } else { callback.receiveErrorsetPassword(f); } } else { callback.receiveErrorsetPassword(f); } } else { callback.receiveErrorsetPassword(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorsetPassword(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[9].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[9].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Logout the current user, invalidating the current session. * * @see com.salesforce.soap.partner.SforceService#logout * @param logout643 * * @param sessionHeader644 * * @param callOptions645 * * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.LogoutResponse logout( com.salesforce.soap.partner.Logout logout643, com.salesforce.soap.partner.SessionHeader sessionHeader644, com.salesforce.soap.partner.CallOptions callOptions645) throws java.rmi.RemoteException , com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[10].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:logoutRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), logout643, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout")); env.build(); // add the children only if the parameter is not null if (sessionHeader644 != null) { org.apache.axiom.om.OMElement omElementsessionHeader644 = toOM(sessionHeader644, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout"))); addHeader(omElementsessionHeader644, env); } // add the children only if the parameter is not null if (callOptions645 != null) { org.apache.axiom.om.OMElement omElementcallOptions645 = toOM(callOptions645, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout"))); addHeader(omElementcallOptions645, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.LogoutResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.LogoutResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Logout the current user, invalidating the current session. * * @see com.salesforce.soap.partner.SforceService#startlogout * @param logout643 * * @param sessionHeader644 * * @param callOptions645 */ public void startlogout( com.salesforce.soap.partner.Logout logout643, com.salesforce.soap.partner.SessionHeader sessionHeader644, com.salesforce.soap.partner.CallOptions callOptions645, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[10].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:logoutRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), logout643, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout")); // add the soap_headers only if they are not null if (sessionHeader644 != null) { org.apache.axiom.om.OMElement omElementsessionHeader644 = toOM(sessionHeader644, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout"))); addHeader(omElementsessionHeader644, env); } // add the soap_headers only if they are not null if (callOptions645 != null) { org.apache.axiom.om.OMElement omElementcallOptions645 = toOM(callOptions645, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "logout"))); addHeader(omElementcallOptions645, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.LogoutResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultlogout((com.salesforce.soap.partner.LogoutResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorlogout(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "logout")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorlogout((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrorlogout(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorlogout(f); } } else { callback.receiveErrorlogout(f); } } else { callback.receiveErrorlogout(f); } } else { callback.receiveErrorlogout(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorlogout(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[10].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[10].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Get a set of sObjects * * @see com.salesforce.soap.partner.SforceService#retrieve * @param retrieve647 * * @param sessionHeader648 * * @param callOptions649 * * @param queryOptions650 * * @param mruHeader651 * * @param packageVersionHeader652 * * @throws com.salesforce.soap.partner.InvalidSObjectFault : * @throws com.salesforce.soap.partner.MalformedQueryFault : * @throws com.salesforce.soap.partner.InvalidIdFault : * @throws com.salesforce.soap.partner.InvalidFieldFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.RetrieveResponse retrieve( com.salesforce.soap.partner.Retrieve retrieve647, com.salesforce.soap.partner.SessionHeader sessionHeader648, com.salesforce.soap.partner.CallOptions callOptions649, com.salesforce.soap.partner.QueryOptions queryOptions650, com.salesforce.soap.partner.MruHeader mruHeader651, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader652) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidSObjectFault, com.salesforce.soap.partner.MalformedQueryFault, com.salesforce.soap.partner.InvalidIdFault, com.salesforce.soap.partner.InvalidFieldFault, com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[11].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:retrieveRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), retrieve647, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve")); env.build(); // add the children only if the parameter is not null if (sessionHeader648 != null) { org.apache.axiom.om.OMElement omElementsessionHeader648 = toOM(sessionHeader648, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementsessionHeader648, env); } // add the children only if the parameter is not null if (callOptions649 != null) { org.apache.axiom.om.OMElement omElementcallOptions649 = toOM(callOptions649, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementcallOptions649, env); } // add the children only if the parameter is not null if (queryOptions650 != null) { org.apache.axiom.om.OMElement omElementqueryOptions650 = toOM(queryOptions650, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementqueryOptions650, env); } // add the children only if the parameter is not null if (mruHeader651 != null) { org.apache.axiom.om.OMElement omElementmruHeader651 = toOM(mruHeader651, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementmruHeader651, env); } // add the children only if the parameter is not null if (packageVersionHeader652 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader652 = toOM(packageVersionHeader652, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementpackageVersionHeader652, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.RetrieveResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.RetrieveResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { throw (com.salesforce.soap.partner.InvalidSObjectFault) ex; } if (ex instanceof com.salesforce.soap.partner.MalformedQueryFault) { throw (com.salesforce.soap.partner.MalformedQueryFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { throw (com.salesforce.soap.partner.InvalidIdFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { throw (com.salesforce.soap.partner.InvalidFieldFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Get a set of sObjects * * @see com.salesforce.soap.partner.SforceService#startretrieve * @param retrieve647 * * @param sessionHeader648 * * @param callOptions649 * * @param queryOptions650 * * @param mruHeader651 * * @param packageVersionHeader652 */ public void startretrieve( com.salesforce.soap.partner.Retrieve retrieve647, com.salesforce.soap.partner.SessionHeader sessionHeader648, com.salesforce.soap.partner.CallOptions callOptions649, com.salesforce.soap.partner.QueryOptions queryOptions650, com.salesforce.soap.partner.MruHeader mruHeader651, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader652, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[11].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:retrieveRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), retrieve647, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve")); // add the soap_headers only if they are not null if (sessionHeader648 != null) { org.apache.axiom.om.OMElement omElementsessionHeader648 = toOM(sessionHeader648, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementsessionHeader648, env); } // add the soap_headers only if they are not null if (callOptions649 != null) { org.apache.axiom.om.OMElement omElementcallOptions649 = toOM(callOptions649, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementcallOptions649, env); } // add the soap_headers only if they are not null if (queryOptions650 != null) { org.apache.axiom.om.OMElement omElementqueryOptions650 = toOM(queryOptions650, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementqueryOptions650, env); } // add the soap_headers only if they are not null if (mruHeader651 != null) { org.apache.axiom.om.OMElement omElementmruHeader651 = toOM(mruHeader651, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementmruHeader651, env); } // add the soap_headers only if they are not null if (packageVersionHeader652 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader652 = toOM(packageVersionHeader652, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "retrieve"))); addHeader(omElementpackageVersionHeader652, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.RetrieveResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultretrieve((com.salesforce.soap.partner.RetrieveResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorretrieve(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "retrieve")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { callback.receiveErrorretrieve((com.salesforce.soap.partner.InvalidSObjectFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.MalformedQueryFault) { callback.receiveErrorretrieve((com.salesforce.soap.partner.MalformedQueryFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { callback.receiveErrorretrieve((com.salesforce.soap.partner.InvalidIdFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { callback.receiveErrorretrieve((com.salesforce.soap.partner.InvalidFieldFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorretrieve((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrorretrieve(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorretrieve(f); } } else { callback.receiveErrorretrieve(f); } } else { callback.receiveErrorretrieve(f); } } else { callback.receiveErrorretrieve(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorretrieve(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[11].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[11].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Create a Query Cursor, including deleted sObjects * * @see com.salesforce.soap.partner.SforceService#queryAll * @param queryAll654 * * @param sessionHeader655 * * @param callOptions656 * * @param queryOptions657 * * @throws com.salesforce.soap.partner.InvalidSObjectFault : * @throws com.salesforce.soap.partner.MalformedQueryFault : * @throws com.salesforce.soap.partner.InvalidIdFault : * @throws com.salesforce.soap.partner.InvalidFieldFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : * @throws com.salesforce.soap.partner.InvalidQueryLocatorFault : */ public com.salesforce.soap.partner.QueryAllResponse queryAll( com.salesforce.soap.partner.QueryAll queryAll654, com.salesforce.soap.partner.SessionHeader sessionHeader655, com.salesforce.soap.partner.CallOptions callOptions656, com.salesforce.soap.partner.QueryOptions queryOptions657) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidSObjectFault, com.salesforce.soap.partner.MalformedQueryFault, com.salesforce.soap.partner.InvalidIdFault, com.salesforce.soap.partner.InvalidFieldFault, com.salesforce.soap.partner.UnexpectedErrorFault, com.salesforce.soap.partner.InvalidQueryLocatorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[12].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:queryAllRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), queryAll654, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll")); env.build(); // add the children only if the parameter is not null if (sessionHeader655 != null) { org.apache.axiom.om.OMElement omElementsessionHeader655 = toOM(sessionHeader655, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementsessionHeader655, env); } // add the children only if the parameter is not null if (callOptions656 != null) { org.apache.axiom.om.OMElement omElementcallOptions656 = toOM(callOptions656, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementcallOptions656, env); } // add the children only if the parameter is not null if (queryOptions657 != null) { org.apache.axiom.om.OMElement omElementqueryOptions657 = toOM(queryOptions657, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementqueryOptions657, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.QueryAllResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.QueryAllResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { throw (com.salesforce.soap.partner.InvalidSObjectFault) ex; } if (ex instanceof com.salesforce.soap.partner.MalformedQueryFault) { throw (com.salesforce.soap.partner.MalformedQueryFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { throw (com.salesforce.soap.partner.InvalidIdFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { throw (com.salesforce.soap.partner.InvalidFieldFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } if (ex instanceof com.salesforce.soap.partner.InvalidQueryLocatorFault) { throw (com.salesforce.soap.partner.InvalidQueryLocatorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Create a Query Cursor, including deleted sObjects * * @see com.salesforce.soap.partner.SforceService#startqueryAll * @param queryAll654 * * @param sessionHeader655 * * @param callOptions656 * * @param queryOptions657 */ public void startqueryAll( com.salesforce.soap.partner.QueryAll queryAll654, com.salesforce.soap.partner.SessionHeader sessionHeader655, com.salesforce.soap.partner.CallOptions callOptions656, com.salesforce.soap.partner.QueryOptions queryOptions657, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[12].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:queryAllRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), queryAll654, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll")); // add the soap_headers only if they are not null if (sessionHeader655 != null) { org.apache.axiom.om.OMElement omElementsessionHeader655 = toOM(sessionHeader655, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementsessionHeader655, env); } // add the soap_headers only if they are not null if (callOptions656 != null) { org.apache.axiom.om.OMElement omElementcallOptions656 = toOM(callOptions656, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementcallOptions656, env); } // add the soap_headers only if they are not null if (queryOptions657 != null) { org.apache.axiom.om.OMElement omElementqueryOptions657 = toOM(queryOptions657, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "queryAll"))); addHeader(omElementqueryOptions657, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.QueryAllResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultqueryAll((com.salesforce.soap.partner.QueryAllResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorqueryAll(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "queryAll")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.InvalidSObjectFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.MalformedQueryFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.MalformedQueryFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidIdFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.InvalidIdFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidFieldFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.InvalidFieldFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } if (ex instanceof com.salesforce.soap.partner.InvalidQueryLocatorFault) { callback.receiveErrorqueryAll((com.salesforce.soap.partner.InvalidQueryLocatorFault) ex); return; } callback.receiveErrorqueryAll(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorqueryAll(f); } } else { callback.receiveErrorqueryAll(f); } } else { callback.receiveErrorqueryAll(f); } } else { callback.receiveErrorqueryAll(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorqueryAll(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[12].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[12].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Undelete a set of sObjects * * @see com.salesforce.soap.partner.SforceService#undelete * @param undelete659 * * @param sessionHeader660 * * @param callOptions661 * * @param allowFieldTruncationHeader662 * * @param disableFeedTrackingHeader663 * * @param streamingEnabledHeader664 * * @param allOrNoneHeader665 * * @param duplicateRuleHeader666 * * @param localeOptions667 * * @param debuggingHeader668 * * @param packageVersionHeader669 * * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.UndeleteResponse undelete( com.salesforce.soap.partner.Undelete undelete659, com.salesforce.soap.partner.SessionHeader sessionHeader660, com.salesforce.soap.partner.CallOptions callOptions661, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader662, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader663, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader664, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader665, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader666, com.salesforce.soap.partner.LocaleOptions localeOptions667, com.salesforce.soap.partner.DebuggingHeader debuggingHeader668, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader669) throws java.rmi.RemoteException , com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[13].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:undeleteRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), undelete659, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete")); env.build(); // add the children only if the parameter is not null if (sessionHeader660 != null) { org.apache.axiom.om.OMElement omElementsessionHeader660 = toOM(sessionHeader660, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementsessionHeader660, env); } // add the children only if the parameter is not null if (callOptions661 != null) { org.apache.axiom.om.OMElement omElementcallOptions661 = toOM(callOptions661, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementcallOptions661, env); } // add the children only if the parameter is not null if (allowFieldTruncationHeader662 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader662 = toOM(allowFieldTruncationHeader662, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementallowFieldTruncationHeader662, env); } // add the children only if the parameter is not null if (disableFeedTrackingHeader663 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader663 = toOM(disableFeedTrackingHeader663, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementdisableFeedTrackingHeader663, env); } // add the children only if the parameter is not null if (streamingEnabledHeader664 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader664 = toOM(streamingEnabledHeader664, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementstreamingEnabledHeader664, env); } // add the children only if the parameter is not null if (allOrNoneHeader665 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader665 = toOM(allOrNoneHeader665, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementallOrNoneHeader665, env); } // add the children only if the parameter is not null if (duplicateRuleHeader666 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader666 = toOM(duplicateRuleHeader666, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementduplicateRuleHeader666, env); } // add the children only if the parameter is not null if (localeOptions667 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions667 = toOM(localeOptions667, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementlocaleOptions667, env); } // add the children only if the parameter is not null if (debuggingHeader668 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader668 = toOM(debuggingHeader668, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementdebuggingHeader668, env); } // add the children only if the parameter is not null if (packageVersionHeader669 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader669 = toOM(packageVersionHeader669, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementpackageVersionHeader669, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.UndeleteResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.UndeleteResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Undelete a set of sObjects * * @see com.salesforce.soap.partner.SforceService#startundelete * @param undelete659 * * @param sessionHeader660 * * @param callOptions661 * * @param allowFieldTruncationHeader662 * * @param disableFeedTrackingHeader663 * * @param streamingEnabledHeader664 * * @param allOrNoneHeader665 * * @param duplicateRuleHeader666 * * @param localeOptions667 * * @param debuggingHeader668 * * @param packageVersionHeader669 */ public void startundelete( com.salesforce.soap.partner.Undelete undelete659, com.salesforce.soap.partner.SessionHeader sessionHeader660, com.salesforce.soap.partner.CallOptions callOptions661, com.salesforce.soap.partner.AllowFieldTruncationHeader allowFieldTruncationHeader662, com.salesforce.soap.partner.DisableFeedTrackingHeader disableFeedTrackingHeader663, com.salesforce.soap.partner.StreamingEnabledHeader streamingEnabledHeader664, com.salesforce.soap.partner.AllOrNoneHeader allOrNoneHeader665, com.salesforce.soap.partner.DuplicateRuleHeader duplicateRuleHeader666, com.salesforce.soap.partner.LocaleOptions localeOptions667, com.salesforce.soap.partner.DebuggingHeader debuggingHeader668, com.salesforce.soap.partner.PackageVersionHeader packageVersionHeader669, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[13].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:undeleteRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), undelete659, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete")); // add the soap_headers only if they are not null if (sessionHeader660 != null) { org.apache.axiom.om.OMElement omElementsessionHeader660 = toOM(sessionHeader660, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementsessionHeader660, env); } // add the soap_headers only if they are not null if (callOptions661 != null) { org.apache.axiom.om.OMElement omElementcallOptions661 = toOM(callOptions661, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementcallOptions661, env); } // add the soap_headers only if they are not null if (allowFieldTruncationHeader662 != null) { org.apache.axiom.om.OMElement omElementallowFieldTruncationHeader662 = toOM(allowFieldTruncationHeader662, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementallowFieldTruncationHeader662, env); } // add the soap_headers only if they are not null if (disableFeedTrackingHeader663 != null) { org.apache.axiom.om.OMElement omElementdisableFeedTrackingHeader663 = toOM(disableFeedTrackingHeader663, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementdisableFeedTrackingHeader663, env); } // add the soap_headers only if they are not null if (streamingEnabledHeader664 != null) { org.apache.axiom.om.OMElement omElementstreamingEnabledHeader664 = toOM(streamingEnabledHeader664, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementstreamingEnabledHeader664, env); } // add the soap_headers only if they are not null if (allOrNoneHeader665 != null) { org.apache.axiom.om.OMElement omElementallOrNoneHeader665 = toOM(allOrNoneHeader665, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementallOrNoneHeader665, env); } // add the soap_headers only if they are not null if (duplicateRuleHeader666 != null) { org.apache.axiom.om.OMElement omElementduplicateRuleHeader666 = toOM(duplicateRuleHeader666, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementduplicateRuleHeader666, env); } // add the soap_headers only if they are not null if (localeOptions667 != null) { org.apache.axiom.om.OMElement omElementlocaleOptions667 = toOM(localeOptions667, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementlocaleOptions667, env); } // add the soap_headers only if they are not null if (debuggingHeader668 != null) { org.apache.axiom.om.OMElement omElementdebuggingHeader668 = toOM(debuggingHeader668, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementdebuggingHeader668, env); } // add the soap_headers only if they are not null if (packageVersionHeader669 != null) { org.apache.axiom.om.OMElement omElementpackageVersionHeader669 = toOM(packageVersionHeader669, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "undelete"))); addHeader(omElementpackageVersionHeader669, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.UndeleteResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultundelete((com.salesforce.soap.partner.UndeleteResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorundelete(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "undelete")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { callback.receiveErrorundelete((com.salesforce.soap.partner.UnexpectedErrorFault) ex); return; } callback.receiveErrorundelete(new java.rmi.RemoteException(ex.getMessage(), ex)); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } catch (org.apache.axis2.AxisFault e) { // we cannot intantiate the class - throw the original Axis fault callback.receiveErrorundelete(f); } } else { callback.receiveErrorundelete(f); } } else { callback.receiveErrorundelete(f); } } else { callback.receiveErrorundelete(error); } } public void onFault(org.apache.axis2.context.MessageContext faultContext) { org.apache.axis2.AxisFault fault = org.apache.axis2.util.Utils.getInboundFaultFromMessageContext(faultContext); onError(fault); } public void onComplete() { try { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } catch (org.apache.axis2.AxisFault axisFault) { callback.receiveErrorundelete(axisFault); } } }); org.apache.axis2.util.CallbackReceiver _callbackReceiver = null; if (_operations[13].getMessageReceiver() == null && _operationClient.getOptions().isUseSeparateListener()) { _callbackReceiver = new org.apache.axis2.util.CallbackReceiver(); _operations[13].setMessageReceiver(_callbackReceiver); } // execute the operation client _operationClient.execute(false); } /** * Auto generated method signature Get the IDs for updated sObjects * * @see com.salesforce.soap.partner.SforceService#getUpdated * @param getUpdated671 * * @param sessionHeader672 * * @param callOptions673 * * @throws com.salesforce.soap.partner.InvalidSObjectFault : * @throws com.salesforce.soap.partner.UnexpectedErrorFault : */ public com.salesforce.soap.partner.GetUpdatedResponse getUpdated( com.salesforce.soap.partner.GetUpdated getUpdated671, com.salesforce.soap.partner.SessionHeader sessionHeader672, com.salesforce.soap.partner.CallOptions callOptions673) throws java.rmi.RemoteException , com.salesforce.soap.partner.InvalidSObjectFault, com.salesforce.soap.partner.UnexpectedErrorFault { org.apache.axis2.context.MessageContext _messageContext = null; try { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[14].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:getUpdatedRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create a message context _messageContext = new org.apache.axis2.context.MessageContext(); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), getUpdated671, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated")); env.build(); // add the children only if the parameter is not null if (sessionHeader672 != null) { org.apache.axiom.om.OMElement omElementsessionHeader672 = toOM(sessionHeader672, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated"))); addHeader(omElementsessionHeader672, env); } // add the children only if the parameter is not null if (callOptions673 != null) { org.apache.axiom.om.OMElement omElementcallOptions673 = toOM(callOptions673, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated"))); addHeader(omElementcallOptions673, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // set the message context with that soap envelope _messageContext.setEnvelope(env); // add the message contxt to the operation client _operationClient.addMessageContext(_messageContext); // execute the operation client _operationClient.execute(true); org.apache.axis2.context.MessageContext _returnMessageContext = _operationClient .getMessageContext(org.apache.axis2.wsdl.WSDLConstants.MESSAGE_LABEL_IN_VALUE); org.apache.axiom.soap.SOAPEnvelope _returnEnv = _returnMessageContext.getEnvelope(); java.lang.Object object = fromOM(_returnEnv.getBody().getFirstElement(), com.salesforce.soap.partner.GetUpdatedResponse.class, getEnvelopeNamespaces(_returnEnv)); return (com.salesforce.soap.partner.GetUpdatedResponse) object; } catch (org.apache.axis2.AxisFault f) { org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { throw (com.salesforce.soap.partner.InvalidSObjectFault) ex; } if (ex instanceof com.salesforce.soap.partner.UnexpectedErrorFault) { throw (com.salesforce.soap.partner.UnexpectedErrorFault) ex; } throw new java.rmi.RemoteException(ex.getMessage(), ex); } catch (java.lang.ClassCastException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.ClassNotFoundException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.NoSuchMethodException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.reflect.InvocationTargetException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.IllegalAccessException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } catch (java.lang.InstantiationException e) { // we cannot intantiate the class - throw the original Axis fault throw f; } } else { throw f; } } else { throw f; } } finally { if (_messageContext.getTransportOut() != null) { _messageContext.getTransportOut().getSender().cleanup(_messageContext); } } } /** * Auto generated method signature for Asynchronous Invocations Get the IDs for updated sObjects * * @see com.salesforce.soap.partner.SforceService#startgetUpdated * @param getUpdated671 * * @param sessionHeader672 * * @param callOptions673 */ public void startgetUpdated( com.salesforce.soap.partner.GetUpdated getUpdated671, com.salesforce.soap.partner.SessionHeader sessionHeader672, com.salesforce.soap.partner.CallOptions callOptions673, final com.salesforce.soap.partner.SforceServiceCallbackHandler callback) throws java.rmi.RemoteException { org.apache.axis2.client.OperationClient _operationClient = _serviceClient.createClient(_operations[14].getName()); _operationClient.getOptions().setAction("urn:partner.soap.sforce.com:Soap:getUpdatedRequest"); _operationClient.getOptions().setExceptionToBeThrownOnSOAPFault(true); addPropertyToOperationClient(_operationClient, org.apache.axis2.description.WSDL2Constants.ATTR_WHTTP_QUERY_PARAMETER_SEPARATOR, "&"); // create SOAP envelope with that payload org.apache.axiom.soap.SOAPEnvelope env = null; final org.apache.axis2.context.MessageContext _messageContext = new org.apache.axis2.context.MessageContext(); // Style is Doc. env = toEnvelope(getFactory(_operationClient.getOptions().getSoapVersionURI()), getUpdated671, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated")), new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated")); // add the soap_headers only if they are not null if (sessionHeader672 != null) { org.apache.axiom.om.OMElement omElementsessionHeader672 = toOM(sessionHeader672, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated"))); addHeader(omElementsessionHeader672, env); } // add the soap_headers only if they are not null if (callOptions673 != null) { org.apache.axiom.om.OMElement omElementcallOptions673 = toOM(callOptions673, optimizeContent(new javax.xml.namespace.QName("urn:partner.soap.sforce.com", "getUpdated"))); addHeader(omElementcallOptions673, env); } // adding SOAP soap_headers _serviceClient.addHeadersToEnvelope(env); // create message context with that soap envelope _messageContext.setEnvelope(env); // add the message context to the operation client _operationClient.addMessageContext(_messageContext); _operationClient.setCallback(new org.apache.axis2.client.async.AxisCallback() { public void onMessage(org.apache.axis2.context.MessageContext resultContext) { try { org.apache.axiom.soap.SOAPEnvelope resultEnv = resultContext.getEnvelope(); java.lang.Object object = fromOM(resultEnv.getBody().getFirstElement(), com.salesforce.soap.partner.GetUpdatedResponse.class, getEnvelopeNamespaces(resultEnv)); callback.receiveResultgetUpdated((com.salesforce.soap.partner.GetUpdatedResponse) object); } catch (org.apache.axis2.AxisFault e) { callback.receiveErrorgetUpdated(e); } } public void onError(java.lang.Exception error) { if (error instanceof org.apache.axis2.AxisFault) { org.apache.axis2.AxisFault f = (org.apache.axis2.AxisFault) error; org.apache.axiom.om.OMElement faultElt = f.getDetail(); if (faultElt != null) { if (faultExceptionNameMap.containsKey(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated"))) { // make the fault by reflection try { java.lang.String exceptionClassName = (java.lang.String) faultExceptionClassNameMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated")); java.lang.Class exceptionClass = java.lang.Class.forName(exceptionClassName); java.lang.reflect.Constructor constructor = exceptionClass.getConstructor(String.class); java.lang.Exception ex = (java.lang.Exception) constructor.newInstance(f.getMessage()); // message class java.lang.String messageClassName = (java.lang.String) faultMessageMap .get(new org.apache.axis2.client.FaultMapKey(faultElt.getQName(), "getUpdated")); java.lang.Class messageClass = java.lang.Class.forName(messageClassName); java.lang.Object messageObject = fromOM(faultElt, messageClass, null); java.lang.reflect.Method m = exceptionClass.getMethod("setFaultMessage", new java.lang.Class[] { messageClass }); m.invoke(ex, new java.lang.Object[] { messageObject }); if (ex instanceof com.salesforce.soap.partner.InvalidSObjectFault) { callback.receiveErrorgetUpdated((com.salesforce.soap.partner.InvalidSObjectFault) ex); return; } if
| 29,000
|
https://github.com/graceshopper-codename/graceshopper/blob/master/client/components/productsByTag.js
|
Github Open Source
|
Open Source
|
MIT
| null |
graceshopper
|
graceshopper-codename
|
JavaScript
|
Code
| 91
| 300
|
import React from 'react'
import {getTagProduct} from '../store/products'
import {connect} from 'react-redux'
import OneProduct from './individualprod'
import {Link} from 'react-router-dom'
export class TaggedProducts extends React.Component {
componentDidMount() {
const tag = this.props.match.params.productTag
this.props.getTagProduct(tag)
}
render() {
let products = this.props.products.product
return (
<div>
<h1> All {this.props.match.params.productTag} Games</h1>
<Link to="/products">
<button className="button" type="button">
Return to all products
</button>
</Link>
<div>
<OneProduct products={products} />
</div>
</div>
)
}
}
const mapStateToProps = state => ({
products: state.products
})
const mapDispatchToProps = dispatch => ({
getTagProduct: tag => dispatch(getTagProduct(tag))
})
export default connect(mapStateToProps, mapDispatchToProps)(TaggedProducts)
| 31,060
|
https://github.com/axon7-oss/android_device_zte_axon7/blob/master/tools/sgdisk/gptcl.cc
|
Github Open Source
|
Open Source
|
FTL
| 2,021
|
android_device_zte_axon7
|
axon7-oss
|
C++
|
Code
| 2,455
| 6,771
|
/*
Implementation of GPTData class derivative with popt-based command
line processing
Copyright (C) 2010-2014 Roderick W. Smith
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <string.h>
#include <string>
#include <iostream>
#include <sstream>
#include <errno.h>
#include "gptcl.h"
GPTDataCL::GPTDataCL(void) {
attributeOperation = backupFile = partName = hybrids = newPartInfo = NULL;
mbrParts = twoParts = outDevice = typeCode = partGUID = diskGUID = NULL;
alignment = DEFAULT_ALIGNMENT;
deletePartNum = infoPartNum = largestPartNum = bsdPartNum = 0;
tableSize = GPT_SIZE;
} // GPTDataCL constructor
GPTDataCL::GPTDataCL(string filename) {
} // GPTDataCL constructor with filename
GPTDataCL::~GPTDataCL(void) {
} // GPTDataCL destructor
void GPTDataCL::LoadBackupFile(string backupFile, int &saveData, int &neverSaveData) {
if (LoadGPTBackup(backupFile) == 1) {
JustLooking(0);
saveData = 1;
} else {
saveData = 0;
neverSaveData = 1;
cerr << "Error loading backup file!\n";
} // else
} // GPTDataCL::LoadBackupFile()
// Perform the actions specified on the command line. This is necessarily one
// monster of a function!
// Returns values:
// 0 = success
// 1 = too few arguments
// 2 = error when reading partition table
// 3 = non-GPT disk and no -g option
// 4 = unable to save changes
// 8 = disk replication operation (-R) failed
int GPTDataCL::DoOptions(int argc, char* argv[]) {
GPTData secondDevice;
int opt, numOptions = 0, saveData = 0, neverSaveData = 0;
int partNum = 0, newPartNum = -1, saveNonGPT = 1, retval = 0, pretend = 0;
uint64_t low, high, startSector, endSector, sSize, mainTableLBA;
uint64_t temp; // temporary variable; free to use in any case
char *device;
string cmd, typeGUID, name;
PartType typeHelper;
struct poptOption theOptions[] =
{
{"attributes", 'A', POPT_ARG_STRING, &attributeOperation, 'A', "operate on partition attributes",
"list|[partnum:show|or|nand|xor|=|set|clear|toggle|get[:bitnum|hexbitmask]]"},
{"set-alignment", 'a', POPT_ARG_INT, &alignment, 'a', "set sector alignment", "value"},
{"backup", 'b', POPT_ARG_STRING, &backupFile, 'b', "backup GPT to file", "file"},
{"change-name", 'c', POPT_ARG_STRING, &partName, 'c', "change partition's name", "partnum:name"},
{"recompute-chs", 'C', POPT_ARG_NONE, NULL, 'C', "recompute CHS values in protective/hybrid MBR", ""},
{"delete", 'd', POPT_ARG_INT, &deletePartNum, 'd', "delete a partition", "partnum"},
{"display-alignment", 'D', POPT_ARG_NONE, NULL, 'D', "show number of sectors per allocation block", ""},
{"move-second-header", 'e', POPT_ARG_NONE, NULL, 'e', "move second header to end of disk", ""},
{"end-of-largest", 'E', POPT_ARG_NONE, NULL, 'E', "show end of largest free block", ""},
{"first-in-largest", 'f', POPT_ARG_NONE, NULL, 'f', "show start of the largest free block", ""},
{"first-aligned-in-largest", 'F', POPT_ARG_NONE, NULL, 'F', "show start of the largest free block, aligned", ""},
{"mbrtogpt", 'g', POPT_ARG_NONE, NULL, 'g', "convert MBR to GPT", ""},
{"randomize-guids", 'G', POPT_ARG_NONE, NULL, 'G', "randomize disk and partition GUIDs", ""},
{"hybrid", 'h', POPT_ARG_STRING, &hybrids, 'h', "create hybrid MBR", "partnum[:partnum...][:EE]"},
{"info", 'i', POPT_ARG_INT, &infoPartNum, 'i', "show detailed information on partition", "partnum"},
{"move-main-table", 'j', POPT_ARG_INT, &mainTableLBA, 'j', "adjust the location of the main partition table", "sector"},
{"load-backup", 'l', POPT_ARG_STRING, &backupFile, 'l', "load GPT backup from file", "file"},
{"list-types", 'L', POPT_ARG_NONE, NULL, 'L', "list known partition types", ""},
{"gpttombr", 'm', POPT_ARG_STRING, &mbrParts, 'm', "convert GPT to MBR", "partnum[:partnum...]"},
{"new", 'n', POPT_ARG_STRING, &newPartInfo, 'n', "create new partition", "partnum:start:end"},
{"largest-new", 'N', POPT_ARG_INT, &largestPartNum, 'N', "create largest possible new partition", "partnum"},
{"clear", 'o', POPT_ARG_NONE, NULL, 'o', "clear partition table", ""},
{"print-mbr", 'O', POPT_ARG_NONE, NULL, 'O', "print MBR partition table", ""},
{"print", 'p', POPT_ARG_NONE, NULL, 'p', "print partition table", ""},
{"pretend", 'P', POPT_ARG_NONE, NULL, 'P', "make changes in memory, but don't write them", ""},
{"transpose", 'r', POPT_ARG_STRING, &twoParts, 'r', "transpose two partitions", "partnum:partnum"},
{"replicate", 'R', POPT_ARG_STRING, &outDevice, 'R', "replicate partition table", "device_filename"},
{"sort", 's', POPT_ARG_NONE, NULL, 's', "sort partition table entries", ""},
{"resize-table", 'S', POPT_ARG_INT, &tableSize, 'S', "resize partition table", "numparts"},
{"typecode", 't', POPT_ARG_STRING, &typeCode, 't', "change partition type code", "partnum:{hexcode|GUID}"},
{"transform-bsd", 'T', POPT_ARG_INT, &bsdPartNum, 'T', "transform BSD disklabel partition to GPT", "partnum"},
{"partition-guid", 'u', POPT_ARG_STRING, &partGUID, 'u', "set partition GUID", "partnum:guid"},
{"disk-guid", 'U', POPT_ARG_STRING, &diskGUID, 'U', "set disk GUID", "guid"},
{"verify", 'v', POPT_ARG_NONE, NULL, 'v', "check partition table integrity", ""},
{"version", 'V', POPT_ARG_NONE, NULL, 'V', "display version information", ""},
{"zap", 'z', POPT_ARG_NONE, NULL, 'z', "zap (destroy) GPT (but not MBR) data structures", ""},
{"zap-all", 'Z', POPT_ARG_NONE, NULL, 'Z', "zap (destroy) GPT and MBR data structures", ""},
POPT_AUTOHELP { NULL, 0, 0, NULL, 0, NULL, NULL }
};
// Create popt context...
poptCon = poptGetContext(NULL, argc, (const char**) argv, theOptions, 0);
poptSetOtherOptionHelp(poptCon, " [OPTION...] <device>");
if (argc < 2) {
poptPrintUsage(poptCon, stderr, 0);
return 1;
}
// Do one loop through the options to find the device filename and deal
// with options that don't require a device filename, to flag destructive
// (o, z, or Z) options, and to flag presence of a --pretend/-P option
while ((opt = poptGetNextOpt(poptCon)) > 0) {
switch (opt) {
case 'A':
cmd = GetString(attributeOperation, 1);
if (cmd == "list")
Attributes::ListAttributes();
break;
case 'L':
typeHelper.ShowAllTypes(0);
break;
case 'P':
pretend = 1;
break;
case 'V':
cout << "GPT fdisk (sgdisk) version " << GPTFDISK_VERSION << "\n\n";
break;
default:
break;
} // switch
numOptions++;
} // while
// Assume first non-option argument is the device filename....
device = (char*) poptGetArg(poptCon);
poptResetContext(poptCon);
if (device != NULL) {
JustLooking(); // reset as necessary
BeQuiet(); // Tell called functions to be less verbose & interactive
if (LoadPartitions((string) device)) {
if ((WhichWasUsed() == use_mbr) || (WhichWasUsed() == use_bsd))
saveNonGPT = 0; // flag so we don't overwrite unless directed to do so
sSize = GetBlockSize();
while ((opt = poptGetNextOpt(poptCon)) > 0) {
switch (opt) {
case 'A': {
if (cmd != "list") {
partNum = (int) GetInt(attributeOperation, 1) - 1;
if (partNum < 0)
partNum = newPartNum;
if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
switch (ManageAttributes(partNum, GetString(attributeOperation, 2),
GetString(attributeOperation, 3))) {
case -1:
saveData = 0;
neverSaveData = 1;
break;
case 1:
JustLooking(0);
saveData = 1;
break;
default:
break;
} // switch
} else {
cerr << "Error: Invalid partition number " << partNum + 1 << "\n";
saveData = 0;
neverSaveData = 1;
} // if/else reasonable partition #
} // if (cmd != "list")
break;
} // case 'A':
case 'a':
SetAlignment(alignment);
break;
case 'b':
SaveGPTBackup(backupFile);
free(backupFile);
break;
case 'c':
cout << "Setting name!\n";
JustLooking(0);
partNum = (int) GetInt(partName, 1) - 1;
if (partNum < 0)
partNum = newPartNum;
cout << "partNum is " << partNum << "\n";
if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
name = GetString(partName, 2);
if (SetName(partNum, (UnicodeString) name.c_str())) {
saveData = 1;
} else {
cerr << "Unable to set partition " << partNum + 1
<< "'s name to '" << GetString(partName, 2) << "'!\n";
neverSaveData = 1;
} // if/else
free(partName);
}
break;
case 'C':
JustLooking(0);
RecomputeCHS();
saveData = 1;
break;
case 'd':
JustLooking(0);
if (DeletePartition(deletePartNum - 1) == 0) {
cerr << "Error " << errno << " deleting partition!\n";
neverSaveData = 1;
} else saveData = 1;
break;
case 'D':
cout << GetAlignment() << "\n";
break;
case 'e':
JustLooking(0);
MoveSecondHeaderToEnd();
saveData = 1;
break;
case 'E':
cout << FindLastInFree(FindFirstInLargest()) << "\n";
break;
case 'f':
cout << FindFirstInLargest() << "\n";
break;
case 'F':
temp = FindFirstInLargest();
Align(&temp);
cout << temp << "\n";
break;
case 'g':
JustLooking(0);
saveData = 1;
saveNonGPT = 1;
break;
case 'G':
JustLooking(0);
saveData = 1;
RandomizeGUIDs();
break;
case 'h':
JustLooking(0);
if (BuildMBR(hybrids, 1) == 1)
saveData = 1;
break;
case 'i':
ShowPartDetails(infoPartNum - 1);
break;
case 'j':
if (MoveMainTable(mainTableLBA)) {
JustLooking(0);
saveData = 1;
} else {
neverSaveData = 1;
} // if/else
break;
case 'l':
LoadBackupFile(backupFile, saveData, neverSaveData);
free(backupFile);
break;
case 'L':
break;
case 'm':
JustLooking(0);
if (BuildMBR(mbrParts, 0) == 1) {
if (!pretend) {
if (SaveMBR()) {
DestroyGPT();
} else
cerr << "Problem saving MBR!\n";
} // if
saveNonGPT = 0;
pretend = 1; // Not really, but works around problem if -g is used with this...
saveData = 0;
} // if
break;
case 'n':
JustLooking(0);
newPartNum = (int) GetInt(newPartInfo, 1) - 1;
if (newPartNum < 0)
newPartNum = FindFirstFreePart();
low = FindFirstInLargest();
Align(&low);
high = FindLastInFree(low);
startSector = IeeeToInt(GetString(newPartInfo, 2), sSize, low, high, low);
endSector = IeeeToInt(GetString(newPartInfo, 3), sSize, startSector, high, high);
if (CreatePartition(newPartNum, startSector, endSector)) {
saveData = 1;
} else {
cerr << "Could not create partition " << newPartNum + 1 << " from "
<< startSector << " to " << endSector << "\n";
neverSaveData = 1;
} // if/else
free(newPartInfo);
break;
case 'N':
JustLooking(0);
startSector = FindFirstInLargest();
Align(&startSector);
endSector = FindLastInFree(startSector);
if (largestPartNum <= 0)
largestPartNum = FindFirstFreePart() + 1;
if (CreatePartition(largestPartNum - 1, startSector, endSector)) {
saveData = 1;
} else {
cerr << "Could not create partition " << largestPartNum << " from "
<< startSector << " to " << endSector << "\n";
neverSaveData = 1;
} // if/else
break;
case 'o':
JustLooking(0);
ClearGPTData();
saveData = 1;
break;
case 'O':
DisplayMBRData();
break;
case 'p':
DisplayGPTData();
break;
case 'P':
pretend = 1;
break;
case 'r':
JustLooking(0);
uint64_t p1, p2;
p1 = GetInt(twoParts, 1) - 1;
p2 = GetInt(twoParts, 2) - 1;
if (SwapPartitions((uint32_t) p1, (uint32_t) p2) == 0) {
neverSaveData = 1;
cerr << "Cannot swap partitions " << p1 + 1 << " and " << p2 + 1 << "\n";
} else saveData = 1;
break;
case 'R':
secondDevice = *this;
secondDevice.SetDisk(outDevice);
secondDevice.JustLooking(0);
if (!secondDevice.SaveGPTData(1))
retval = 8;
break;
case 's':
JustLooking(0);
SortGPT();
saveData = 1;
break;
case 'S':
JustLooking(0);
if (SetGPTSize(tableSize) == 0)
neverSaveData = 1;
else
saveData = 1;
break;
case 't':
JustLooking(0);
partNum = (int) GetInt(typeCode, 1) - 1;
if (partNum < 0)
partNum = newPartNum;
if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
// Remember the original hex value requested
string raw = GetString(typeCode, 2);
if (raw.size() == 4) {
typeRaw[partNum] = StrToHex(raw, 0);
}
typeHelper = GetString(typeCode, 2);
if ((typeHelper != (GUIDData) "00000000-0000-0000-0000-000000000000") &&
(ChangePartType(partNum, typeHelper))) {
saveData = 1;
} else {
cerr << "Could not change partition " << partNum + 1
<< "'s type code to " << GetString(typeCode, 2) << "!\n";
neverSaveData = 1;
} // if/else
free(typeCode);
}
break;
case 'T':
JustLooking(0);
XFormDisklabel(bsdPartNum - 1);
saveData = 1;
break;
case 'u':
JustLooking(0);
saveData = 1;
partNum = (int) GetInt(partGUID, 1) - 1;
if (partNum < 0)
partNum = newPartNum;
if ((partNum >= 0) && (partNum < (int) GetNumParts())) {
SetPartitionGUID(partNum, GetString(partGUID, 2).c_str());
}
break;
case 'U':
JustLooking(0);
saveData = 1;
SetDiskGUID(diskGUID);
break;
case 'v':
Verify();
break;
case 'z':
if (!pretend) {
DestroyGPT();
} // if
saveNonGPT = 1;
saveData = 0;
break;
case 'Z':
if (!pretend) {
DestroyGPT();
DestroyMBR();
} // if
saveNonGPT = 1;
saveData = 0;
break;
default:
cerr << "Unknown option (-" << opt << ")!\n";
break;
} // switch
} // while
} else { // if loaded OK
poptResetContext(poptCon);
// Do a few types of operations even if there are problems....
while ((opt = poptGetNextOpt(poptCon)) > 0) {
switch (opt) {
case 'l':
LoadBackupFile(backupFile, saveData, neverSaveData);
cout << "Information: Loading backup partition table; will override earlier problems!\n";
free(backupFile);
retval = 0;
break;
case 'o':
JustLooking(0);
ClearGPTData();
saveData = 1;
cout << "Information: Creating fresh partition table; will override earlier problems!\n";
retval = 0;
break;
case 'v':
cout << "Verification may miss some problems or report too many!\n";
Verify();
break;
case 'z':
if (!pretend) {
DestroyGPT();
} // if
saveNonGPT = 1;
saveData = 0;
break;
case 'Z':
if (!pretend) {
DestroyGPT();
DestroyMBR();
} // if
saveNonGPT = 1;
saveData = 0;
break;
} // switch
} // while
retval = 2;
} // if/else loaded OK
if ((saveData) && (!neverSaveData) && (saveNonGPT) && (!pretend)) {
if (!SaveGPTData(1))
retval = 4;
}
if (saveData && (!saveNonGPT)) {
cout << "Non-GPT disk; not saving changes. Use -g to override.\n";
retval = 3;
} // if
if (neverSaveData) {
cerr << "Error encountered; not saving changes.\n";
retval = 4;
} // if
} // if (device != NULL)
poptFreeContext(poptCon);
return retval;
} // GPTDataCL::DoOptions()
// Create a hybrid or regular MBR from GPT data structures
int GPTDataCL::BuildMBR(char* argument, int isHybrid) {
int numParts, allOK = 1, i, origPartNum;
int eeLast, mbrNum = 0;
MBRPart newPart;
BasicMBRData newMBR;
if (argument != NULL) {
numParts = CountColons(argument) + 1;
if (isHybrid) {
eeLast = GetString(argument, numParts) == "EE";
if (eeLast) {
numParts--;
}
}
if (numParts <= (4 - isHybrid)) {
newMBR.SetDisk(GetDisk());
for (i = 0; i < numParts; i++) {
origPartNum = GetInt(argument, i + 1) - 1;
if (IsUsedPartNum(origPartNum) && (partitions[origPartNum].IsSizedForMBR() == MBR_SIZED_GOOD)) {
mbrNum = i + (isHybrid && ! eeLast);
newPart.SetInclusion(PRIMARY);
newPart.SetLocation(operator[](origPartNum).GetFirstLBA(),
operator[](origPartNum).GetLengthLBA());
newPart.SetStatus(0);
newPart.SetType((uint8_t)(operator[](origPartNum).GetHexType() / 0x0100));
// If we were created with a specific hex type, use that instead
// of risking fidelity loss by doing a GUID-based lookup
if (typeRaw.count(origPartNum) == 1) {
newPart.SetType(typeRaw[origPartNum]);
}
newMBR.AddPart(mbrNum, newPart);
} else {
cerr << "Original partition " << origPartNum + 1 << " does not exist or is too big! Aborting operation!\n";
allOK = 0;
} // if/else
} // for
if (isHybrid) {
if (eeLast) {
mbrNum = i;
} else {
mbrNum = 0;
}
newPart.SetInclusion(PRIMARY);
newPart.SetLocation(1, newMBR.FindLastInFree(1));
newPart.SetStatus(0);
newPart.SetType(0xEE);
newMBR.AddPart(mbrNum, newPart);
} // if
if (allOK)
SetProtectiveMBR(newMBR);
} else allOK = 0;
} else allOK = 0;
if (!allOK)
cerr << "Problem creating MBR!\n";
return allOK;
} // GPTDataCL::BuildMBR()
// Returns the number of colons in argument string, ignoring the
// first character (thus, a leading colon is ignored, as GetString()
// does).
int CountColons(char* argument) {
int num = 0;
while ((argument[0] != '\0') && (argument = strchr(&argument[1], ':')))
num++;
return num;
} // GPTDataCL::CountColons()
// Extract integer data from argument string, which should be colon-delimited
uint64_t GetInt(const string & argument, int itemNum) {
uint64_t retval;
istringstream inString(GetString(argument, itemNum));
inString >> retval;
return retval;
} // GPTDataCL::GetInt()
// Extract string data from argument string, which should be colon-delimited
// If string begins with a colon, that colon is skipped in the counting. If an
// invalid itemNum is specified, returns an empty string.
string GetString(string argument, int itemNum) {
size_t startPos = 0, endPos = 0;
string retVal = "";
int foundLast = 0;
int numFound = 0;
if (argument[0] == ':')
argument.erase(0, 1);
while ((numFound < itemNum) && (!foundLast)) {
endPos = argument.find(':', startPos);
numFound++;
if (endPos == string::npos) {
foundLast = 1;
endPos = argument.length();
} else if (numFound < itemNum) {
startPos = endPos + 1;
} // if/elseif
} // while
if ((numFound == itemNum) && (numFound > 0))
retVal = argument.substr(startPos, endPos - startPos);
return retVal;
} // GetString()
| 30,771
|
https://github.com/rtvt123/spliceengine/blob/master/assembly/mapr5.1.0/src/main/resources/scripts/install-oracle-jdk7-centos.sh
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, BSD-3-Clause, LicenseRef-scancode-generic-cla, Apache-2.0
| 2,016
|
spliceengine
|
rtvt123
|
Shell
|
Code
| 55
| 208
|
#!/bin/bash
# Install Oracle JDK 7 for RedHat/CentOS from RPM. This script needs to be run with sudo/root privileges.
# Select correct RPM based on 32/64bit system type
if [ `getconf LONG_BIT` = "64" ]
then
RPM="jdk-7u72-linux-x64.rpm"
else
RPM="jdk-7u72-linux-i586.rpm"
fi
URL="http://download.oracle.com/otn-pub/java/jdk/7u72-b14/"
yum -y install wget
wget --no-check-certificate --no-cookies --header "Cookie: oraclelicense=accept-securebackup-cookie" "${URL}${RPM}"
rpm -Uhv "${RPM}"
| 32,735
|
https://github.com/mback2k/tsoexpert/blob/master/src/de/uxnr/tsoexpert/game/communication/vo/StreetVO.java
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
tsoexpert
|
mback2k
|
Java
|
Code
| 61
| 195
|
package de.uxnr.tsoexpert.game.communication.vo;
import de.uxnr.amf.v3.AMF3_Object;
public class StreetVO extends AMF3_Object {
private int grid;
private int playerID;
private int streetBits;
private int streetCityLevel;
private int streetVariation;
public int getGrid() {
return this.grid;
}
public int getPlayerID() {
return this.playerID;
}
public int getStreetBits() {
return this.streetBits;
}
public int getStreetCityLevel() {
return this.streetCityLevel;
}
public int getStreetVariation() {
return this.streetVariation;
}
}
| 5,016
|
https://github.com/seanperkins/pdredesign-sevenzo/blob/master/app/assets/stylesheets/home/testimonial.sass
|
Github Open Source
|
Open Source
|
MIT
| null |
pdredesign-sevenzo
|
seanperkins
|
Sass
|
Code
| 89
| 351
|
.testimonial
display: flex
flex-direction: row
flex-wrap: wrap
padding: 50px 0
%testimonial-column
display: flex
flex-direction: column
.testimonial-column-text
@extend %testimonial-column
.quote
border: 0
padding: 10px 20px
margin-bottom: 0
q
quotes: "\201C" "\201D" "\2018" "\2019"
font-size: 1.35em
&:before
content: open-quote
font-size: 1em
&:after
content: close-quote
font-size: 1em
.quote-footer
font-size: 100%
color: $primary-color
margin-top: 1.25em
cite
font-style: normal
a
align-self: center
.subtext
font-size: 70%
padding: 10px 20px
.testimonial-column-picture
@extend %testimonial-column
justify-content: center
align-items: center
margin: 0 auto
.testimonial-background
background: $off-white
.testimonial-background-alt
background: $background-color
.natural-order
display: flex
flex-direction: row
.reverse-order
@extend .natural-order
flex-direction: row-reverse
| 34,520
|
https://github.com/emipa606/LinkableSettings/blob/master/Source/LinkableSettings/LinkableSettingsMod.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
LinkableSettings
|
emipa606
|
C#
|
Code
| 972
| 4,149
|
using System;
using System.Linq;
using Mlie;
using RimWorld;
using UnityEngine;
using Verse;
using Verse.Sound;
namespace LinkableSettings;
[StaticConstructorOnStartup]
internal class LinkableSettingsMod : Mod
{
/// <summary>
/// The instance of the settings to be read by the mod
/// </summary>
public static LinkableSettingsMod instance;
private static readonly Vector2 buttonSize = new Vector2(120f, 25f);
private static readonly Vector2 iconSize = new Vector2(24f, 24f);
private static readonly Vector2 imageSize = new Vector2(128f, 128f);
private static readonly int buttonSpacer = 200;
private static readonly float columnSpacer = 0.1f;
private static float leftSideWidth;
private static Listing_Standard listing_Standard;
private static Vector2 tabsScrollPosition;
private static string currentVersion;
private static readonly Vector2 searchSize = new Vector2(280f, 24f);
private static string searchText = "";
/// <summary>
/// The private settings
/// </summary>
private LinkableSettingsModSettings settings;
/// <summary>
/// Constructor
/// </summary>
/// <param name="content"></param>
public LinkableSettingsMod(ModContentPack content)
: base(content)
{
instance = this;
currentVersion =
VersionFromManifest.GetVersionFromModMetaData(
ModLister.GetActiveModWithIdentifier("Mlie.LinkableSettings"));
}
private static string SelectedDef { get; set; } = "Settings";
/// <summary>
/// The instance-settings for the mod
/// </summary>
internal LinkableSettingsModSettings Settings
{
get
{
if (settings == null)
{
settings = GetSettings<LinkableSettingsModSettings>();
}
return settings;
}
set => settings = value;
}
/// <summary>
/// The settings-window
/// </summary>
/// <param name="rect"></param>
public override void DoSettingsWindowContents(Rect rect)
{
base.DoSettingsWindowContents(rect);
var rect2 = rect.ContractedBy(1);
leftSideWidth = rect2.ContractedBy(10).width / 5 * 2;
listing_Standard = new Listing_Standard();
DrawOptions(rect2);
DrawTabsList(rect2);
Settings.Write();
}
/// <summary>
/// The title for the mod-settings
/// </summary>
/// <returns></returns>
public override string SettingsCategory()
{
return "Linkable Settings";
}
private static void DrawButton(Action action, string text, Vector2 pos)
{
var rect = new Rect(pos.x, pos.y, buttonSize.x, buttonSize.y);
if (!Widgets.ButtonText(rect, text, true, false, Color.white))
{
return;
}
SoundDefOf.Designate_DragStandard_Changed.PlayOneShotOnCamera();
action();
}
public override void WriteSettings()
{
base.WriteSettings();
Main.UpdateFacilities();
}
private void DrawIcon(ThingDef thingDef, Rect rect)
{
if (thingDef?.graphicData?.Graphic?.MatSingle?.mainTexture == null)
{
return;
}
var texture2D = thingDef.graphicData.Graphic.MatSingle.mainTexture;
if (thingDef.graphicData.graphicClass == typeof(Graphic_Random))
{
texture2D = ((Graphic_Random)thingDef.graphicData.Graphic).FirstSubgraphic().MatSingle.mainTexture;
}
if (thingDef.graphicData.graphicClass == typeof(Graphic_Multi))
{
texture2D = ((Graphic_Multi)thingDef.graphicData.Graphic).MatNorth.mainTexture;
}
if (texture2D.width != texture2D.height)
{
var ratio = (float)texture2D.width / texture2D.height;
if (ratio < 1)
{
rect.x += (rect.width - (rect.width * ratio)) / 2;
rect.width *= ratio;
}
else
{
rect.y += (rect.height - (rect.height / ratio)) / 2;
rect.height /= ratio;
}
}
GUI.DrawTexture(rect, texture2D);
}
private void DrawOptions(Rect rect)
{
var optionsOuterContainer = rect.ContractedBy(10);
optionsOuterContainer.x += leftSideWidth + columnSpacer;
optionsOuterContainer.width -= leftSideWidth + columnSpacer;
Widgets.DrawBoxSolid(optionsOuterContainer, Color.grey);
var optionsInnerContainer = optionsOuterContainer.ContractedBy(1);
Widgets.DrawBoxSolid(optionsInnerContainer, new ColorInt(42, 43, 44).ToColor);
var frameRect = optionsInnerContainer.ContractedBy(10);
frameRect.x = leftSideWidth + columnSpacer + 20;
frameRect.y += 15;
frameRect.height -= 15;
var contentRect = frameRect;
contentRect.x = 0;
contentRect.y = 0;
switch (SelectedDef)
{
case null:
return;
case "Settings":
{
listing_Standard.Begin(frameRect);
Text.Font = GameFont.Medium;
listing_Standard.Label("LiSe.settings".Translate());
Text.Font = GameFont.Small;
listing_Standard.Gap();
if (Main.HaveAnySavedSettings())
{
var labelPoint = listing_Standard.Label("LiSe.resetall.label".Translate(), -1F,
"LiSe.resetall.tooltip".Translate());
DrawButton(() =>
{
Find.WindowStack.Add(Dialog_MessageBox.CreateConfirmation(
"LiSe.resetall.confirm".Translate(),
Main.ResetToVanilla));
}, "LiSe.resetall.button".Translate(),
new Vector2(labelPoint.position.x + buttonSpacer, labelPoint.position.y));
}
else
{
listing_Standard.Gap(buttonSize.y);
}
listing_Standard.CheckboxLabeled("LiSe.logging.label".Translate(), ref Settings.VerboseLogging,
"LiSe.logging.tooltip".Translate());
if (currentVersion != null)
{
listing_Standard.Gap();
GUI.contentColor = Color.gray;
listing_Standard.Label("LiSe.version.label".Translate(currentVersion));
GUI.contentColor = Color.white;
}
listing_Standard.End();
break;
}
default:
{
var currentDef = DefDatabase<ThingDef>.GetNamedSilentFail(SelectedDef);
listing_Standard.Begin(frameRect);
if (currentDef == null)
{
listing_Standard.Label("LiSe.error.thing".Translate(SelectedDef));
listing_Standard.End();
break;
}
Text.Font = GameFont.Medium;
var labelPoint = listing_Standard.Label(currentDef.label.CapitalizeFirst(), -1F,
currentDef.defName);
Text.Font = GameFont.Small;
var modName = currentDef.modContentPack?.Name;
var modId = currentDef.modContentPack?.PackageId;
if (currentDef.modContentPack != null)
{
listing_Standard.Label($"{modName}", -1F, modId);
}
else
{
listing_Standard.Gap();
}
var description = currentDef.description;
if (!string.IsNullOrEmpty(description))
{
if (description.Length > 400)
{
description = description.Substring(0, 400) + "...";
}
Widgets.Label(new Rect(labelPoint.x, labelPoint.y + 50, 320, 150), description);
}
listing_Standard.Gap(150);
var iconRect = new Rect(labelPoint.x + 325, labelPoint.y + 5, imageSize.x, imageSize.y);
DrawIcon(currentDef, iconRect);
listing_Standard.GapLine();
var linkType = instance.Settings.FacilityType.ContainsKey(currentDef.defName)
? instance.Settings.FacilityType[currentDef.defName]
: Main.VanillaFacilityType[currentDef.defName];
Text.Font = GameFont.Medium;
labelPoint = listing_Standard.Label("LiSe.linktype.label".Translate(), -1f,
"LiSe.linktype.description".Translate());
Text.Font = GameFont.Small;
if (Main.HaveAnySavedSettings(currentDef.defName))
{
DrawButton(() => { Main.ResetToVanilla(currentDef.defName); }, "LiSe.reset.button".Translate(),
new Vector2(labelPoint.position.x + frameRect.width - buttonSize.x, labelPoint.position.y));
}
if (listing_Standard.RadioButton("LiSe.range.label".Translate(), linkType == 0, 0f,
"LiSe.range.description".Translate()))
{
instance.Settings.FacilityType[currentDef.defName] = 0;
}
if (listing_Standard.RadioButton("LiSe.room.label".Translate(), linkType == 4, 0f,
"LiSe.room.description".Translate()))
{
instance.Settings.FacilityType[currentDef.defName] = 4;
}
if (listing_Standard.RadioButton("LiSe.mustBePlacedAdjacent.label".Translate(), linkType == 1, 0f,
"LiSe.mustBePlacedAdjacent.description".Translate()))
{
instance.Settings.FacilityType[currentDef.defName] = 1;
}
if (listing_Standard.RadioButton("LiSe.mustBePlacedAdjacentCardinalToBedHead.label".Translate(),
linkType == 2, 0f,
"LiSe.mustBePlacedAdjacentCardinalToBedHead.description".Translate()))
{
instance.Settings.FacilityType[currentDef.defName] = 2;
}
if (listing_Standard.RadioButton(
"LiSe.mustBePlacedAdjacentCardinalToAndFacingBedHead.label".Translate(), linkType == 3, 0f,
"LiSe.mustBePlacedAdjacentCardinalToAndFacingBedHead.description".Translate()))
{
instance.Settings.FacilityType[currentDef.defName] = 3;
}
if (instance.Settings.FacilityType.ContainsKey(currentDef.defName) &&
instance.Settings.FacilityType[currentDef.defName] == Main.VanillaFacilityType[currentDef.defName])
{
instance.Settings.FacilityType.Remove(currentDef.defName);
}
listing_Standard.Gap();
if (linkType is 0 or 4)
{
var linkRange = instance.Settings.FacilityRange.ContainsKey(currentDef.defName)
? instance.Settings.FacilityRange[currentDef.defName]
: Main.VanillaFacilityRange[currentDef.defName];
var currentRange = linkRange;
listing_Standard.Label("LiSe.linkrange.label".Translate(linkRange), -1f,
"LiSe.linkrange.description".Translate());
linkRange = (float)Math.Round(listing_Standard.Slider(linkRange, 1f, 100f));
if (linkRange != currentRange)
{
instance.Settings.FacilityRange[currentDef.defName] = linkRange;
}
if (instance.Settings.FacilityRange.ContainsKey(currentDef.defName) &&
instance.Settings.FacilityRange[currentDef.defName] ==
Main.VanillaFacilityRange[currentDef.defName])
{
instance.Settings.FacilityRange.Remove(currentDef.defName);
}
listing_Standard.Gap();
}
var linkAmount = instance.Settings.FacilityAmount.ContainsKey(currentDef.defName)
? instance.Settings.FacilityAmount[currentDef.defName]
: Main.VanillaFacilityAmount[currentDef.defName];
var currentAmount = linkAmount;
listing_Standard.Label("LiSe.linkamount.label".Translate(linkAmount), -1f,
"LiSe.linkamount.description".Translate());
linkAmount = (int)Math.Round(listing_Standard.Slider(linkAmount, 1f, 25f));
if (linkAmount != currentAmount)
{
instance.Settings.FacilityAmount[currentDef.defName] = linkAmount;
}
if (instance.Settings.FacilityAmount.ContainsKey(currentDef.defName) &&
instance.Settings.FacilityAmount[currentDef.defName] ==
Main.VanillaFacilityAmount[currentDef.defName])
{
instance.Settings.FacilityAmount.Remove(currentDef.defName);
}
listing_Standard.End();
break;
}
}
}
private void DrawTabsList(Rect rect)
{
var scrollContainer = rect.ContractedBy(10);
scrollContainer.width = leftSideWidth;
Widgets.DrawBoxSolid(scrollContainer, Color.grey);
var innerContainer = scrollContainer.ContractedBy(1);
Widgets.DrawBoxSolid(innerContainer, new ColorInt(42, 43, 44).ToColor);
var tabFrameRect = innerContainer.ContractedBy(5);
tabFrameRect.y += 15;
tabFrameRect.height -= 15;
searchText =
Widgets.TextField(
new Rect(
scrollContainer.position + new Vector2(5, 46),
searchSize),
searchText);
TooltipHandler.TipRegion(new Rect(
scrollContainer.position + new Vector2(5, 46),
searchSize), "LiSe.search".Translate());
GUI.DrawTexture(new Rect(scrollContainer.position + new Vector2(5 + searchSize.x, 46), iconSize), Main.Search);
var tabContentRect = tabFrameRect;
tabContentRect.x = 0;
tabContentRect.y = 0;
tabContentRect.width -= 20;
var allFacilities = Main.AllFacilities.OrderBy(def => def.label).ToList();
if (!string.IsNullOrEmpty(searchText))
{
allFacilities = allFacilities.Where(def =>
def.label.ToLower().Contains(searchText.ToLower()) ||
def.modContentPack?.Name.ToLower().Contains(searchText.ToLower()) == true).ToList();
}
var listAddition = 50;
tabContentRect.height = (allFacilities.Count * 25f) + listAddition;
Widgets.BeginScrollView(tabFrameRect, ref tabsScrollPosition, tabContentRect);
listing_Standard.Begin(tabContentRect);
if (listing_Standard.ListItemSelectable("LiSe.settings".Translate(), Color.yellow,
out _, SelectedDef == "Settings"))
{
SelectedDef = SelectedDef == "Settings" ? null : "Settings";
}
listing_Standard.ListItemSelectable(null, Color.yellow, out _);
foreach (var thingDef in allFacilities)
{
if (Main.HaveAnySavedSettings(thingDef.defName))
{
GUI.color = Color.green;
}
if (listing_Standard.ListItemSelectable(thingDef.label.CapitalizeFirst(), Color.yellow,
out var position,
SelectedDef == thingDef.defName))
{
SelectedDef = SelectedDef == thingDef.defName ? null : thingDef.defName;
}
GUI.color = Color.white;
position.x = position.x + tabContentRect.width - iconSize.x;
DrawIcon(thingDef, new Rect(position, iconSize));
}
listing_Standard.End();
Widgets.EndScrollView();
}
}
| 6,436
|
https://github.com/swh0318/coolq-php-sqk/blob/master/src/Core/Protocols/GuzzleProtocol.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
coolq-php-sqk
|
swh0318
|
PHP
|
Code
| 812
| 3,344
|
<?php
/**
* Created by PhpStorm.
* User: kilingzhang
* Date: 2018/8/26
* Time: 21:52
*/
namespace Kilingzhang\QQ\Core\Protocols;
use GuzzleHttp\Exception\ClientException;
use Kilingzhang\QQ\Core\Exceptions\Exception;
use Kilingzhang\QQ\Core\Response;
use function Kilingzhang\QQ\http_put;
use function Kilingzhang\QQ\http_server;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Psr\Http\Message\ResponseInterface;
class GuzzleProtocol implements Protocol
{
private $url;
private $host;
private $port;
private $client;
private $response;
private $accessToken;
private $secret;
private $isSignature = true;
private $options = [];
private $content = [];
/**
* GuzzleProtocol constructor.
* @param string $url
* @param string $access_token
* @param string $secret
* @throws Exception
*/
public function __construct(string $url = '127.0.0.1:5700', string $access_token = '', string $secret = '')
{
$this->url = $url;
$hosts = explode(':', $this->url);
if (count($hosts) != 2) {
throw new Exception('missing url or port');
}
$this->host = $hosts[0];
$this->port = $hosts[1];
$this->accessToken = $access_token;
$this->secret = $secret;
$this->options['headers'] = [
'Authorization' => 'Token ' . $this->accessToken
];
$this->client = new Client([
// Base URI is used with relative requests
'base_uri' => $this->url,
// You can set any number of default request options.
'timeout' => 10.0,
]);
}
public function send($uri, $param = [], $method = 'POST'): Response
{
try {
$this->response = $this->client->request($method, $uri, array_merge($this->options, [
'query' => $param
]));
$response = $this->response;
if ($response->getStatusCode() == 200) {
$response = $response->getBody();
$response = json_decode($response, true);
$code = $response['retcode'];
$data = $response['data'];
if ($code != 0) {
return Response::response(200, $code, []);
}
$data = empty($data) ? [] : $data;
return Response::ok($data);
}
} catch (ClientException $e) {
//如果 http_errors 请求参数设置成true,在400级别的错误的时候将会抛出
switch ($e->getCode()) {
case 400:
return Response::notFoundResourceError();
break;
case 401:
//401 配置文件中已填写access_token 初始化CoolQ对象时未传值
return Response::accessTokenNoneError();
break;
case 403:
//403 验证access_token错误
return Response::accessTokenError();
break;
case 404:
return Response::notFoundResourceError();
break;
case 406:
return Response::contentTypeError();
break;
default:
return Response::error([
'message' => $e->getMessage()
]);
break;
}
} catch (RequestException $e) {
//在发送网络错误(连接超时、DNS错误等)时,将会抛出 GuzzleHttp\Exception\RequestException 异常。
//一般为coolq-http-api插件未开启 接口地址无法访问
switch ($e->getCode()) {
case 0:
return Response::pluginServerError($this->client);
break;
default:
return Response::error([
'message' => $e->getMessage()
]);
break;
}
}
return $response;
}
public function sendAsync($uri, $param = [], $method = 'POST'): Response
{
$promise = $this->client->requestAsync($method, $uri, array_merge($this->options, [
'query' => $param
]));
$promise->then(
function (ResponseInterface $res) {
echo $res->getBody() . "\n";
},
function (RequestException $e) {
echo $e->getMessage() . "\n";
echo $e->getRequest()->getMethod();
})->wait();
// return $promise;
}
public function isValidated(): bool
{
$signature = http_server('HTTP_X_SIGNATURE');
$signature = $signature == '' ? '' : substr($signature, 5, strlen($signature));
$putParams = http_put();
if ($this->isSignature && !empty($signature) && (hash_hmac('sha1', \GuzzleHttp\json_encode($putParams, JSON_UNESCAPED_UNICODE), $this->secret) != $signature)) {
//sha1验证失败
return false;
}
return true;
}
/**
* @return array
* @throws Exception
*/
public function getContent(): array
{
$content = http_put();
if (empty($content)) {
throw new Exception('put params not be empty');
}
switch ($content['post_type']) {
//收到消息
case 'message':
$message_type = $content['message_type'];
switch ($message_type) {
//私聊消息
case "private":
$this->content = [
'message_type' => $content['message_type'],
'message_id' => $content['message_id'],
'font' => $content['font'],
'user_id' => $content['user_id'],
'message' => $content['message'],
//消息子类型,如果是好友则是 "friend",
//如果从群或讨论组来的临时会话则分别是 "group"、"discuss"
//"friend"、"group"、"discuss"、"other"
'sub_type' => $content['sub_type'],
];
break;
//群消息
case "group":
$this->content = [
'message_type' => $content['message_type'],
'message_id' => $content['message_id'],
'font' => $content['font'],
'user_id' => $content['user_id'],
'message' => $content['message'],
'group_id' => $content['group_id'],
//匿名用户显示名
'anonymous' => $content['anonymous'],
//匿名用户 flag,在调用禁言 API 时需要传入
'anonymous_flag' => empty($content['anonymous']['flag']) ? '' : $content['anonymous']['flag'],
];
// {"reply":"message","block": true,"at_sender":true,"kick":false,"ban":false}
break;
//讨论组消息
case "discuss":
$this->content = [
'message_type' => $content['message_type'],
'message_id' => $content['message_id'],
'font' => $content['font'],
'discuss_id' => $content['discuss_id'],
'user_id' => $content['user_id'],
'message' => $content['message'],
];
// {"reply":"message","block": true,"at_sender":true}
break;
}
break;
//群、讨论组变动等非消息类事件
case 'notice': //兼容4.0
case 'event':
$event = empty($content['event']) ? $content['notice_type'] : $content['event'];//兼容4.0
switch ($event) {
//群管理员变动
case "group_admin":
$this->content = [
'event' => empty($content['event']) ? $content['notice_type'] : $content['event'],
//"set"、"unset" 事件子类型,分别表示设置和取消管理员
'sub_type' => $content['sub_type'],
'group_id' => $content['group_id'],
'user_id' => $content['user_id'],
];
break;
//群成员减少
case "group_decrease":
$this->content = [
'event' => empty($content['event']) ? $content['notice_type'] : $content['event'],
//"leave"、"kick"、"kick_me" 事件子类型,分别表示主动退群、成员被踢、登录号被踢
'sub_type' => $content['sub_type'],
'group_id' => $content['group_id'],
'user_id' => $content['user_id'],
'operator_id' => $content['operator_id'],
];
break;
//群成员增加
case "group_increase":
$this->content = [
'event' => empty($content['event']) ? $content['notice_type'] : $content['event'],
//"approve"、"invite" 事件子类型,分别表示管理员已同意入群、管理员邀请入群
'sub_type' => $content['sub_type'],
'group_id' => $content['group_id'],
'user_id' => $content['user_id'],
'operator_id' => $content['operator_id'],
];
break;
//群文件上传
case "group_upload":
$this->content = [
'event' => empty($content['event']) ? $content['notice_type'] : $content['event'],
'group_id' => $content['group_id'],
'user_id' => $content['user_id'],
#字段名 数据类型 说明
#id string 文件 ID
#name string 文件名
#size number 文件大小(字节数)
#busid number busid(目前不清楚有什么作用)
'file' => $content['file'],
];
break;
//好友添加
case "friend_added":
$this->content = [
'event' => empty($content['event']) ? $content['notice_type'] : $content['event'],
'user_id' => $content['user_id'],
];
break;
}
break;
//加好友请求、加群请求/邀请
case 'request':
$request_type = $content['request_type'];
switch ($request_type) {
case "friend":
$this->content = [
'request_type' => $content['request_type'],
'user_id' => $content['user_id'],
'message' => empty($content['message']) ? $content['comment'] : $content['message'],//兼容4.0
'flag' => $content['flag'],
];
//{"block": true,"approve":true,"reason":"就是拒绝你 不行啊"}
break;
case "group":
$this->content = [
'request_type' => $content['request_type'],
//"add"、"invite" 请求子类型,分别表示加群请求、邀请登录号入群
'sub_type' => $content['sub_type'],
'group_id' => $content['group_id'],
'user_id' => $content['user_id'],
'message' => empty($content['message']) ? $content['comment'] : $content['message'],//兼容4.0
'flag' => $content['flag'],
];
//{"block": true,"approve":true,"reason":"就是拒绝你 不行啊"}
break;
}
break;
default:
$this->content = $content;
break;
}
$this->content['post_type'] = $content['post_type'];
return $this->content;
}
public function returnApi(Response $response)
{
echo json_encode($response, JSON_UNESCAPED_UNICODE);
exit();
}
public function isCli(): bool
{
return false;
}
}
| 28,678
|
https://github.com/SEPIA-Framework/sepia-installation-and-setup/blob/master/sepia-custom-bundle-folder/run-sepia.sh
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
sepia-installation-and-setup
|
SEPIA-Framework
|
Shell
|
Code
| 711
| 2,152
|
#!/bin/bash
#
# make sure we are in the right folder
SCRIPT_PATH="$(realpath "$BASH_SOURCE")"
SEPIA_FOLDER="$(dirname "$SCRIPT_PATH")"
LOG="${SEPIA_FOLDER}/startup-log.out"
cd "$SEPIA_FOLDER"
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Starting SEPIA-Home ..." > "$LOG"
#
# set local Java path
if [ -f "java/version" ]; then
new_java_home=$(cat java/version)
export JAVA_HOME=$(pwd)/java/$new_java_home
export PATH=$JAVA_HOME/bin:$PATH
echo "Found local Java version: $JAVA_HOME"
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Found local Java version: $JAVA_HOME" >> "$LOG"
echo ""
elif [ $(command -v java | wc -l) -gt 0 ]; then
java -version
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Found system Java version: $(javac -version)" >> "$LOG"
echo ""
else
echo "No Java version found! Please install Java JDK 11 (e.g.: openjdk-11-jdk-headless)."
echo "Check SEPIA installer or setup scripts for more info."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - No Java version found! Please install Java JDK 11 (e.g.: openjdk-11-jdk-headless)" >> "$LOG"
exit 1
fi
#
SEPIA_VER=$(cat version | grep SEPIA)
echo "Running: $SEPIA_VER"
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Running: $SEPIA_VER" >> "$LOG"
echo ""
#
cd elasticsearch
if [ $(sysctl vm.max_map_count | grep 262144 | wc -l) -eq 0 ]; then
echo "WARNING: Elasticsearch requires 'vm.max_map_count=262144' to run stable."
echo "To set it once use this (on your host machine):"
echo "sudo sysctl -w vm.max_map_count=262144"
echo "To set it permanently you can try:"
echo "sudo su -c \"echo 'vm.max_map_count=262144' >> /etc/sysctl.d/99-sysctl.conf\""
echo "$(date +'%Y_%m_%d_%H:%M:%S') - WARNING: Elasticsearch requires 'vm.max_map_count=262144' to run stable." >> "$LOG"
echo ""
fi
./run.sh
# echo -e 'Waiting for Elasticsearch...\n'
./wait.sh
echo "Checking Elasticsearch setup ..."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Checking Elasticsearch setup ..." >> "$LOG"
es_check=$(curl --silent http://127.0.0.1:20724/users | grep mappings)
if [ -z "$es_check" ]; then
echo "Elasticsearch is NOT yet setup (or not running with default settings)! Run setup.sh first."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Elasticsearch is NOT yet setup (or not running with default settings)! Run setup.sh first" >> "$LOG"
exit 1
else
echo "Elasticsearch looks GOOD."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Elasticsearch looks GOOD" >> "$LOG"
fi
sleep 2
cd ..
if [ -f "sepia-assist-server/Xtensions/TTS/marytts/bin/marytts-server" ]; then
echo -e '\nChecking extensions ...\n'
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Checking MaryTTS server ..." >> "$LOG"
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:59125/voices)
if [ $STATUS -eq 200 ]; then
echo "MaryTTS server is running."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - MaryTTS server is running" >> "$LOG"
else
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Starting MaryTTS server, please wait ..." >> "$LOG"
echo "Starting MaryTTS server, please wait ..."
echo "INFO: This extension is recommended for systems with 2GB memory or more."
cd sepia-assist-server/Xtensions/TTS/marytts/bin
bash marytts-server > /dev/null 2>&1 &
n=0
while [ $n -le 30 ]
do
STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:59125/voices)
if [ $STATUS -eq 200 ]; then
break
else
printf "."
sleep 2
fi
n=$(( $n + 1 ))
done
if [ $STATUS -eq 200 ]; then
if [ $n -le 10 ]; then
echo "MaryTTS server looks GOOD."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - MaryTTS server looks GOOD" >> "$LOG"
else
echo "MaryTTS server looks OK but took quite long to start."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - MaryTTS server looks OK but took quite long to start" >> "$LOG"
fi
else
echo "$(date +'%Y_%m_%d_%H:%M:%S') - MaryTTS server did NOT respond, ignoring it for now" >> "$LOG"
echo "MaryTTS server did NOT respond, ignoring it for now."
echo "Plz check 'sepia-assist-server\Xtensions\TTS\marytts' for more info."
pkill -f 'java .*sepia-assist.*marytts.server.*'
fi
cd ../../../../..
fi
sleep 2
fi
echo -e '\nStarting SEPIA servers ...\n'
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Starting SEPIA 'Assist' server ..." >> "$LOG"
cd sepia-assist-server
./run.sh
cd ..
#wait for server to be active
sleep 4
#sleep 15
cd sepia-assist-server
TOOLS_JAR=$(ls | grep "^sepia-core-tools.*jar" | tail -n 1)
java -jar $TOOLS_JAR connection-check httpGetJson -url=http://localhost:20721/ping -maxTries=10 -waitBetween=2500 -expectKey=result -expectValue=success
if [ $? -eq 0 ]
then
printf ""
else
echo "TIMEOUT - It took too long to start the server. Please check error logs at 'sepia-assist-server/log.out'."
echo "$(date +'%Y_%m_%d_%H:%M:%S') - It took too long to start the server. Please check error logs at 'sepia-assist-server/log.out'" >> "$LOG"
exit 1
fi
cd ..
cd sepia-websocket-server-java
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Starting SEPIA 'Chat' server ..." >> "$LOG"
./run.sh
cd ..
sleep 2
cd sepia-teach-server
echo "$(date +'%Y_%m_%d_%H:%M:%S') - Starting SEPIA 'Teach' server ..." >> "$LOG"
./run.sh
cd ..
sleep 2
echo -e '\n---- Wait a second (or 5) ----\n'
sleep 5
echo -e '---- Testing cluster ----\n'
./test-cluster.sh
echo "$(date +'%Y_%m_%d_%H:%M:%S') - DONE" >> "$LOG"
| 7,988
|
https://github.com/EdwinFajardoBarrera/google-code-jam/blob/master/solutions/standing-ovation/go/approach3/approach3.go
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
google-code-jam
|
EdwinFajardoBarrera
|
Go
|
Code
| 161
| 495
|
package main
import (
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
)
func main() {
pwd, _ := os.Getwd()
file, err := ioutil.ReadFile(pwd + "/" + os.Args[1])
if err != nil {
fmt.Println(err)
return
}
input := string(file)
input = input[:len(input)-1]
results := getResults(input)
printResults(results)
}
func printResults(results []int) {
for i := 0; i < len(results); i++ {
fmt.Printf("Case #%v: %v\n", i+1, results[i])
}
}
func getResults(input string) []int {
lines := strings.Split(input, "\n")
var results []int
for i := 1; i < len(lines); i++ {
testCase := lines[i]
results = append(results, getTestCaseResult(testCase))
}
return results
}
func getTestCaseResult(testCase string) int {
maxShyness, _ := strconv.Atoi(strings.Split(testCase, " ")[0])
audience := strings.Split(strings.Split(testCase, " ")[1], "")
standingPeopleCount := 0
friendsCount := 0
for shynessLevel := 0; shynessLevel <= maxShyness; shynessLevel++ {
peopleCount, _ := strconv.Atoi(audience[shynessLevel])
if shynessLevel > standingPeopleCount {
friendsNeeded := shynessLevel - standingPeopleCount
friendsCount += friendsNeeded
standingPeopleCount += friendsNeeded + peopleCount
} else {
standingPeopleCount += peopleCount
}
}
return friendsCount
}
| 18,629
|
https://github.com/Shicw/SelectCourseSystem/blob/master/application/admin/model/StudentCourseModel.php
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
SelectCourseSystem
|
Shicw
|
PHP
|
Code
| 30
| 75
|
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2018/11/22
* Time: 11:07
*/
namespace app\admin\model;
use think\Model;
class StudentCourseModel extends Model
{
protected $table = 'student_course';
}
| 18,355
|
https://github.com/zymethyang/Backend-WebVideo/blob/master/src/models/botChannel.js
|
Github Open Source
|
Open Source
|
MIT
| null |
Backend-WebVideo
|
zymethyang
|
JavaScript
|
Code
| 30
| 96
|
var mongoose = require('mongoose');
var timestamps = require('mongoose-timestamp');
var Schema = mongoose.Schema;
var BotChannel = new Schema({
id: {
type: String,
unique: true
}
});
BotChannel.plugin(timestamps);
module.exports = mongoose.model('BotChannel', BotChannel);
| 3,029
|
https://github.com/Simula-UiB/CRHS/blob/master/soccs/src/bin/cli/main.rs
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
CRHS
|
Simula-UiB
|
Rust
|
Code
| 1,367
| 3,936
|
use std::borrow::Borrow;
use std::thread;
use std::time::Duration;
use structopt::StructOpt;
use crush::soc::bdd::differential::StyledProgressBar;
use dl_options::DlOptions;
use pathfinder::diff_solver::post_processing_v5::DisplayResult;
use soccs::dl::{DLmode, OutFiles, RawSoc, Setup, SolvedSoC, StopAfter};
use soccs::dl::builders::cg::{BtHandler, CgBuilder, SbHandler};
use soccs::dl::cg_original::cipher::{Cipher, name_to_cipher, prince};
use soccs::dl::progress::{MyStyledSpinner, Progress};
use crate::batches::*;
mod dl_options;
mod batches;
fn main() {
match DlOptions::from_args() {
DlOptions::Diff {
cipher,
soft_lim,
soft_lim_exponent,
num_rounds,
out_parent_folder,
in_parent_folder,
silent_mode,
} => {
// Prince is the only cipher that actually behaves differently after the reflective round.
// In the original CryptaGraph implementation, this was bypassed. Unfortunately for us,
// this bypass means that the original CG implementation of Prince breaks CG's own Cipher
// trait: It always returns the "forward" S-box, even when it should return the inverse
// S-box.
// In order to fix this, any Prince instance needs to know how many rounds it is. I.e.
// when we've passed the reflective round and should get the inverse S-box instead. In order
// to do this in a backwards compatible way, we decided to add a num_rounds: Option<usize>
// field in Prince. This means that we need to set the num_rounds manually after creation,
// which in turns means that we must create the Prince instance manually. (Trait Cipher
// does not have a "set_num_rounds" fn.)
// (We could have used Any, but that would mean adding more changes to the original
// Prince impl).
let cipher: Box<dyn Cipher + Send> =
if cipher == "prince".to_string() {
let mut prince = prince::Prince::new();
prince.set_num_rounds(num_rounds);
Box::new(prince)
} else {
match name_to_cipher(cipher.as_ref()) {
Some(c) => c,
None => {
println!("Cipher not supported. Check --help for supported ciphers.");
return;
}
}
};
let soft_lim = unwrap_soft_lim(soft_lim, soft_lim_exponent);
let out_files = OutFiles::new(out_parent_folder, &cipher.name(), num_rounds, &DLmode::Differential, soft_lim);
let setup = Setup::new(
cipher.name(),
cipher.structure(),
num_rounds,
soft_lim,
DLmode::Differential,
StopAfter::Process,
out_files,
in_parent_folder,
silent_mode,
);
run(setup, cipher);
},
DlOptions::Lin {
cipher,
soft_lim,
soft_lim_exponent,
num_rounds,
out_parent_folder,
in_parent_folder,
silent_mode,
} => {
// Prince is the only cipher that actually behaves differently after the reflective round.
// In the original CryptaGraph implementation, this was bypassed. Unfortunately for us,
// this bypass means that the original CG implementation of Prince breaks CG's own Cipher
// trait: It always returns the "forward" S-box, even when it should return the inverse
// S-box.
// In order to fix this, any Prince instance needs to know how many rounds it is. I.e.
// when we've passed the reflective round and should get the inverse S-box instead. In order
// to do this in a backwards compatible way, we decided to add a num_rounds: Option<usize>
// field in Prince. This means that we need to set the num_rounds manually after creation,
// which in turns means that we must create the Prince instance manually. (Trait Cipher
// does not have a "set_num_rounds" fn.)
// (We could have used Any, but that would mean adding more changes to the original
// Prince impl).
let cipher: Box<dyn Cipher + Send> =
if cipher == "prince".to_string() {
let mut prince = prince::Prince::new();
prince.set_num_rounds(num_rounds);
Box::new(prince)
} else {
match name_to_cipher(cipher.as_ref()) {
Some(c) => c,
None => {
println!("Cipher not supported. Check --help for supported ciphers.");
return;
}
}
};
let soft_lim = unwrap_soft_lim(soft_lim, soft_lim_exponent);
let out_files = OutFiles::new(out_parent_folder,
&cipher.name(),
num_rounds,
&DLmode::Linear,
soft_lim);
let setup = Setup::new(
cipher.name(),
cipher.structure(),
num_rounds,
soft_lim,
DLmode::Linear,
StopAfter::Process,
out_files,
in_parent_folder,
silent_mode,
);
run(setup, cipher);
},
DlOptions::CG {
soft_lim_exponent,
out_parent_folder,
in_parent_folder,
batch,
linear,
differential,
} => {
if (linear | differential) == false {
println!("Neither liner nor differential is set to be run. At least one of them must be set for any analysis to be done.");
return;
}
let mut setups_to_run = vec![];
if differential {
match batch {
0 => setups_to_run.append(
&mut as_from_paper_diff_batch_0(soft_lim_exponent.unwrap())),
1 => setups_to_run.append(
&mut as_from_paper_diff_batch_1(soft_lim_exponent.unwrap())),
2 => setups_to_run.append(
&mut as_from_paper_diff_batch_2(soft_lim_exponent.unwrap())),
3 => setups_to_run.append(
&mut as_from_paper_diff_batch_3(soft_lim_exponent.unwrap())),
4 => setups_to_run.append(
&mut as_from_paper_diff_batch_4(soft_lim_exponent.unwrap())),
_ => panic!("Batch not found!"),
};
}
if linear {
match batch {
0 => setups_to_run.append(
&mut as_from_paper_lin_batch_0(soft_lim_exponent.unwrap())),
1 => setups_to_run.append(
&mut as_from_paper_lin_batch_1(soft_lim_exponent.unwrap())),
2 => setups_to_run.append(
&mut as_from_paper_lin_batch_2(soft_lim_exponent.unwrap())),
3 => setups_to_run.append(
&mut as_from_paper_lin_batch_3(soft_lim_exponent.unwrap())),
4 => setups_to_run.append(
&mut as_from_paper_lin_batch_4(soft_lim_exponent.unwrap())),
_ => panic!("Batch not found!"),
};
}
// Prince is the only cipher that actually behaves differently after the reflective round.
// In the original CryptaGraph implementation, this was bypassed. Unfortunately for us,
// this bypass means that the original CG implementation of Prince breaks CG's own Cipher
// trait: It always returns the "forward" S-box, even when it should return the inverse
// S-box.
// In order to fix this, any Prince instance needs to know how many rounds it is. I.e.
// when we've passed the reflective round and should get the inverse S-box instead. In order
// to do this in a backwards compatible way, we decided to add a num_rounds: Option<usize>
// field in Prince. This means that we need to set the num_rounds manually after creation,
// which in turns means that we must create the Prince instance manually. (Trait Cipher
// does not have a "set_num_rounds" fn.)
// (We could have used Any, but that would mean adding more changes to the original
// Prince impl).
for settings in setups_to_run {
let cipher: Box<dyn Cipher + Send> =
if settings.cipher == "prince".to_string() {
let mut prince = prince::Prince::new();
prince.set_num_rounds(settings.num_rounds);
Box::new(prince)
} else {
match name_to_cipher(&settings.cipher) {
Some(c) => c,
None => {
println!("Cipher not supported. Check --help for supported ciphers.");
return;
}
}
};
// This allows for cipher dependent adjustments. More specifically, it allows AES
// and Khazad to set a lower soft lim, as they have a higher S-box bit count.
let soft_lim = unwrap_soft_lim(None, Some(settings.soft_lim_e));
let mut out_parent_folder = out_parent_folder.clone();
out_parent_folder.push(settings.out_parent_folder.clone());
let out_files = OutFiles::new(out_parent_folder,
&cipher.name(),
settings.num_rounds,
&settings.mode.clone(),
soft_lim);
let setup = Setup::new(
cipher.name(),
cipher.structure(),
settings.num_rounds,
soft_lim,
settings.mode.clone(),
StopAfter::Process,
out_files,
in_parent_folder.clone(),
true,
);
run(setup, cipher);
}
}
}
}
fn unwrap_soft_lim(soft_lim: Option<usize>, soft_lim_exponent: Option<usize>) -> usize {
if let Some(sl) = soft_lim {
sl
} else if let Some(exp) = soft_lim_exponent {
2_usize.pow(exp as u32)
} else {
panic!("No soft limit detected, unable to proceed.");
}
}
// ===============================================================================================
// ===============================================================================================
/// Cipher cant implement clone, so I need a duplicate from the beginning...
fn run(setup: Setup, cipher: Box<dyn Cipher + Send>) {
let progress_arena = Progress::new();
let main_pb = init_main_pb(&progress_arena, &setup, &cipher.name());
let solved_soc =
if setup.in_parent_folder().is_none()
{
main_pb.set_message("Building SoC");
drive_progress(progress_arena.clone());
let build_progress = progress_arena.new_spinner();
// build raw
build_progress.set_message("Building SoC from cipher specs.");
let raw_soc = from_beginning(&setup, cipher);
build_progress.finish_and_clear();
main_pb.inc(1);
// then solve
main_pb.set_message(&format!("Solving: {}", setup.cipher_name()));
raw_soc.solve_soc(&setup, progress_arena.clone())
} else
{
main_pb.set_message("Loading SoC from file");
drive_progress(progress_arena.clone());
from_solved_soc(&setup,progress_arena.new_spinner(), cipher.as_ref())
};
main_pb.inc(1);
match setup.stop_after() {
StopAfter::Solve => {
main_pb.finish_with_message("SoC solved, we're done!");
// Allow main pb to be shut down, avoids mix-ups in the final printout
thread::sleep(Duration::from_secs(1));
return;
},
_ => {},
}
main_pb.set_message("Analysing the Solved SoC");
let result = solved_soc.analyse(progress_arena.clone())
// TODO update error handling as error handling improves
.expect("Something went wrong");
main_pb.inc(1);
main_pb.finish_with_message("All done!");
// Allow main pb to be shut down, avoids mixups in the final printout
thread::sleep(Duration::from_secs(1));
// Print result
if !setup.silent_mode() {
// FIXME made into comments as quickfix
println!("{}", DisplayResult::AsSummary(&result));
// let buff = result.1.print().unwrap();
// println!("{}", buff);
}
}
///
fn init_main_pb(progress_arena: &Progress,
setup: &Setup,
cipher_name: &str,
) -> MyStyledSpinner
{
let main_pb = progress_arena.new_main_spinner();
main_pb.println(
&format!("Received Cipher: {}, num rounds: {}, soft limit: {}, mode: {}",
cipher_name, setup.num_rounds(), setup.soft_lim(), setup.dl_mode(),
));
main_pb.enable_steady_tick(1000);
main_pb
}
/// Drives the progress bar. Not calling this may result in deadlocks. See progress.rs for more.
fn drive_progress(progress_arena: Progress) {
let _ = thread::spawn(move || {
progress_arena.join();
});
}
/// Builds the SoC "from the beginning". I.e. from the cipher spec, as an unsolved cipher,
/// rather than from a file (where the SoC may, in theory, be in any state: Solved, partially
/// solved or unsolved).
#[inline]
fn from_beginning(setup: &Setup, cipher: Box<dyn Cipher>)
-> RawSoc<BtHandler, SbHandler>
{
CgBuilder::from_cipher(setup, cipher.borrow())
}
/// Builds the SoC from file. Even though a SoC read in from file can, in theory, be in any
/// state (solved, partially solved or unsolved), we will assume that the SoC we read in is
/// a Solved SoC.
/// Feeding any other state to this fn is undefined behaviour.
#[inline]
fn from_solved_soc(setup: &Setup, progress_spinner: MyStyledSpinner, cipher: &dyn Cipher)
-> SolvedSoC<BtHandler, SbHandler, Progress>
{
CgBuilder::from_parent_folder(
setup,
cipher,
progress_spinner,
setup.in_parent_folder()
.expect("Why call from parent folder when no parent folder is given?")
.clone(),
)
}
| 1,223
|
https://github.com/aboutbits/react-material-icons/blob/master/src/IconFemaleRounded.tsx
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-unknown-license-reference, MIT
| 2,023
|
react-material-icons
|
aboutbits
|
TSX
|
Code
| 54
| 406
|
import React from 'react'
import { IconProps } from './types'
const IconFemaleRounded: React.FC<IconProps> = ({ ...props }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
enableBackground="new 0 0 24 24"
viewBox="0 0 24 24"
{...props}
>
{props.title && <title>{props.title}</title>}
<rect fill="none" height="24" width="24" />
<path d="M12,6c1.93,0,3.5,1.57,3.5,3.5S13.93,13,12,13s-3.5-1.57-3.5-3.5S10.07,6,12,6z M13,14.91c2.56-0.47,4.5-2.71,4.5-5.41 C17.5,6.46,15.04,4,12,4S6.5,6.46,6.5,9.5c0,2.7,1.94,4.94,4.5,5.41V17h-1c-0.55,0-1,0.45-1,1s0.45,1,1,1h1v1c0,0.55,0.45,1,1,1 s1-0.45,1-1v-1h1c0.55,0,1-0.45,1-1s-0.45-1-1-1h-1V14.91z" />
</svg>
)
export { IconFemaleRounded as default }
| 23,995
|
https://github.com/EventStore/pulumi-eventstorecloud/blob/master/sdk/dotnet/Config/Config.cs
|
Github Open Source
|
Open Source
|
ECL-2.0, Apache-2.0
| 2,021
|
pulumi-eventstorecloud
|
EventStore
|
C#
|
Code
| 203
| 534
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Immutable;
namespace Pulumi.Eventstorecloud
{
public static class Config
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "IDE1006", Justification =
"Double underscore prefix used to avoid conflicts with variable names.")]
private sealed class __Value<T>
{
private readonly Func<T> _getter;
private T _value = default!;
private bool _set;
public __Value(Func<T> getter)
{
_getter = getter;
}
public T Get() => _set ? _value : _getter();
public void Set(T value)
{
_value = value;
_set = true;
}
}
private static readonly Pulumi.Config __config = new Pulumi.Config("eventstorecloud");
private static readonly __Value<string?> _organizationId = new __Value<string?>(() => __config.Get("organizationId"));
public static string? OrganizationId
{
get => _organizationId.Get();
set => _organizationId.Set(value);
}
private static readonly __Value<string?> _token = new __Value<string?>(() => __config.Get("token"));
public static string? Token
{
get => _token.Get();
set => _token.Set(value);
}
private static readonly __Value<string?> _tokenStore = new __Value<string?>(() => __config.Get("tokenStore"));
public static string? TokenStore
{
get => _tokenStore.Get();
set => _tokenStore.Set(value);
}
private static readonly __Value<string?> _url = new __Value<string?>(() => __config.Get("url"));
public static string? Url
{
get => _url.Get();
set => _url.Set(value);
}
}
}
| 7,219
|
https://github.com/IlyasDeckers/vuetiful/blob/master/_templates/new/plugin/unit.ejs.t
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
vuetiful
|
IlyasDeckers
|
EJS
|
Code
| 70
| 238
|
---
to: "src/plugins/<%= h.inflection.dasherize(name) %>.unit.js"
---
<%
const fileName = h.inflection.dasherize(name)
const noPath = fileName.substr(fileName.lastIndexOf('/') + 1 )
const importName = h.inflection.camelize(noPath.replace(/-/g, '_'))
%>import * as <%= noPath %> from './<%= noPath %>'
import { createLocalVue } from 'vue-test-utils'
describe('@plugins/<%= fileName %>', () => {
const localVue = createLocalVue()
localVue.use(<%= noPath %>)
describe('Init', () => {
it('is an object', () => {
expect(typeof localVue.prototype.$<%= noPath %>)
.toBe('object')
})
})
})
| 46,628
|
https://github.com/martin-ronquillo/tiendita/blob/master/resources/views/livewire/responder/card-body.blade.php
|
Github Open Source
|
Open Source
|
MIT
| 2,020
|
tiendita
|
martin-ronquillo
|
Blade
|
Code
| 189
| 911
|
@if ($empty === 1)
<div id="pregunta{{$pregunta->id}}" class="collapse show" aria-labelledby="pregunta{{$pregunta->id}}">
<div class="card-body">
<div class="row">
<div class="col-12">
<span class="text-secondary" style="font-size: 11px;">
{{ $pregunta->users->name }} {{ $pregunta->users->apellido_pater }} ({{ $pregunta->users->email }})
</span>
<p class="mt-1">
<b>{{ $pregunta->pregunta }}</b>
</p>
</div>
<div class="col-12 mt-3">
<div class="row">
<div class="col-8">
<textarea
name="respuesta"
cols="70"
rows="2"
wire:model.debounce.2000s="respuesta"
placeholder="Intenta responder con detalle a la pregunta"
style="
border: solid 1px rgba(128, 128, 128, 0.342);
border-radius: 5px;
padding: 10px;
">
</textarea>
<br>
@error('respuesta')
<span class="text-danger">{{ $message }}</span>
<br>
@enderror
</div>
<div class="col-4">
<button class="btn btn-primary btn-lg mt-2" wire:click="store({{$pregunta->id}})" style="margin-left: -60px;">
Responder
</button>
</div>
</div>
</div>
</div>
</div>
</div>
@else
<div id="pregunta{{$pregunta->id}}" class="collapse" aria-labelledby="pregunta{{$pregunta->id}}">
<div class="card-body">
<div class="row">
<div class="col-12">
<span class="text-secondary" style="font-size: 11px;">
{{ $pregunta->users->name }} {{ $pregunta->users->apellido_pater }} ({{ $pregunta->users->email }})
</span>
<p class="mt-1">
<b>{{ $pregunta->pregunta }}</b>
</p>
</div>
<div class="col-12 mt-3">
<div class="row">
<div class="col-8">
<textarea
name="respuesta"
cols="70"
rows="2"
wire:model.debounce.2000s="respuesta"
placeholder="Intenta responder con detalle a la pregunta"
style="
border: solid 1px rgba(128, 128, 128, 0.342);
border-radius: 5px;
padding: 10px;
">
</textarea>
<br>
@error('respuesta')
<span class="text-danger">{{ $message }}</span>
<br>
@enderror
</div>
<div class="col-4">
<button class="btn btn-primary btn-lg mt-2" wire:click="store({{$pregunta->id}})" style="margin-left: -60px;">
Responder
</button>
</div>
</div>
</div>
</div>
</div>
</div>
@endif
| 42,695
|
https://github.com/P3D-Legacy/P3D-Legacy-MapEditor/blob/master/P3D-Legacy-MapEditor/Components/Camera/BaseCamera.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,019
|
P3D-Legacy-MapEditor
|
P3D-Legacy
|
C#
|
Code
| 1,975
| 6,004
|
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace P3D.Legacy.MapEditor.Components.Camera
{
// TODO: remove velocity and keep it simple
// http://www.dhpoware.com/demos/xnaFirstPersonCamera.html
public abstract class BaseCamera : IGameComponent
{
#region Default Values
public const float DEFAULT_FOVX = 45.0f;
public const float DEFAULT_ZNEAR = 0.1f;
public const float DEFAULT_ZFAR = 1000.0f;
protected static Vector3 WORLD_X_AXIS = Vector3.UnitX;
protected static Vector3 WORLD_Y_AXIS = Vector3.UnitY;
protected static Vector3 WORLD_Z_AXIS = Vector3.UnitZ;
protected const float DEFAULT_ACCELERATION_X = 8.0f;
protected const float DEFAULT_ACCELERATION_Y = 8.0f;
protected const float DEFAULT_ACCELERATION_Z = 8.0f;
protected const float DEFAULT_VELOCITY_X = 2.0f;
protected const float DEFAULT_VELOCITY_Y = 2.0f;
protected const float DEFAULT_VELOCITY_Z = 2.0f;
protected const float DEFAULT_FAST_MULTIPLIER = 2.0f;
protected const float DEFAULT_MOUSE_SMOOTHING_SENSITIVITY = 0.5f;
protected const float DEFAULT_SPEED_ROTATION = 0.2f;
protected const int MOUSE_SMOOTHING_CACHE_SIZE = 10;
#endregion
protected float _fovx = DEFAULT_FOVX;
protected float _aspectRatio;
protected float _znear = DEFAULT_ZNEAR;
protected float _zfar = DEFAULT_ZFAR;
protected Vector3 _eye = Vector3.Zero;
protected Vector3 _target = Vector3.Zero;
protected Vector3 _targetYAxis = Vector3.UnitY;
protected Vector3 _velocity;
protected bool _cameraLocked;
protected bool _forwardsPressed;
protected bool _backwardsPressed;
protected bool _lshiftPressed;
protected bool _spacePressed;
protected bool _strafeRightPressed;
protected bool _strafeLeftPressed;
protected int _mouseIndex;
protected float _mouseSmoothingSensitivity = DEFAULT_MOUSE_SMOOTHING_SENSITIVITY;
protected Vector2[] _mouseMovement = { new Vector2(0.0f, 0.0f), new Vector2(0.0f, 0.0f) };
protected Vector2[] _mouseSmoothingCache = new Vector2[MOUSE_SMOOTHING_CACHE_SIZE];
protected Vector2 _smoothedMouseMovement;
protected MouseState _currentMouseState;
protected MouseState _previousMouseState;
#region Properties
public Vector3 Acceleration { get; set; } = new Vector3(DEFAULT_ACCELERATION_X, DEFAULT_ACCELERATION_Y, DEFAULT_ACCELERATION_Z);
protected Vector3 _currentVelocity;
public Vector3 CurrentVelocity => _currentVelocity;
public bool EnableMouseSmoothing { get; set; } = true;
protected float _accumHeadingDegrees;
public float HeadingDegrees => -_accumHeadingDegrees;
protected float _accumPitchDegrees;
public float PitchDegrees => -_accumPitchDegrees;
protected Quaternion _orientation = Quaternion.Identity;
public Quaternion Orientation => _orientation;
public Vector3 Position
{
get => _eye;
set
{
_eye = value;
UpdateViewMatrix();
}
}
public Matrix ProjectionMatrix { get; protected set; }
public float RotationSpeed { get; set; } = DEFAULT_SPEED_ROTATION;
public Vector3 VelocityStandard { get; set; } = new Vector3(DEFAULT_VELOCITY_X, DEFAULT_VELOCITY_Y, DEFAULT_VELOCITY_Z);
public Vector3 VelocityFast { get; set; } = new Vector3(DEFAULT_VELOCITY_X, DEFAULT_VELOCITY_Y, DEFAULT_VELOCITY_Z) * DEFAULT_FAST_MULTIPLIER;
protected Vector3 _viewDir = Vector3.Forward;
public Vector3 ViewDirection => _viewDir;
protected Matrix _viewMatrix = Matrix.Identity;
public Matrix ViewMatrix => _viewMatrix;
protected Vector3 _xAxis = Vector3.UnitX;
public Vector3 XAxis => _xAxis;
protected Vector3 _yAxis = Vector3.UnitY;
public Vector3 YAxis => _yAxis;
protected Vector3 _zAxis = Vector3.UnitZ;
public Vector3 ZAxis => _zAxis;
#endregion
#region Public Methods
protected GraphicsDevice GraphicsDevice;
protected BaseCamera(GraphicsDevice graphicsDevice)
{
GraphicsDevice = graphicsDevice;
// Initialize camera state.
_velocity = VelocityStandard;
// Setup perspective projection matrix.
_aspectRatio = graphicsDevice.Viewport.AspectRatio;
UpdateProjectionMatrix(_fovx, _aspectRatio, _znear, _zfar);
}
public abstract void Initialize();
public void LookAt(Vector3 target) => LookAt(_eye, target, _yAxis);
public void LookAt(Vector3 eye, Vector3 target, Vector3 up)
{
_eye = eye;
_target = target;
_zAxis = eye - target;
_zAxis.Normalize();
_viewDir.X = -_zAxis.X;
_viewDir.Y = -_zAxis.Y;
_viewDir.Z = -_zAxis.Z;
Vector3.Cross(ref up, ref _zAxis, out _xAxis);
_xAxis.Normalize();
Vector3.Cross(ref _zAxis, ref _xAxis, out _yAxis);
_yAxis.Normalize();
_xAxis.Normalize();
_viewMatrix.M11 = _xAxis.X;
_viewMatrix.M21 = _xAxis.Y;
_viewMatrix.M31 = _xAxis.Z;
Vector3.Dot(ref _xAxis, ref eye, out _viewMatrix.M41);
_viewMatrix.M41 = -_viewMatrix.M41;
_viewMatrix.M12 = _yAxis.X;
_viewMatrix.M22 = _yAxis.Y;
_viewMatrix.M32 = _yAxis.Z;
Vector3.Dot(ref _yAxis, ref eye, out _viewMatrix.M42);
_viewMatrix.M42 = -_viewMatrix.M42;
_viewMatrix.M13 = _zAxis.X;
_viewMatrix.M23 = _zAxis.Y;
_viewMatrix.M33 = _zAxis.Z;
Vector3.Dot(ref _zAxis, ref eye, out _viewMatrix.M43);
_viewMatrix.M43 = -_viewMatrix.M43;
_viewMatrix.M14 = 0.0f;
_viewMatrix.M24 = 0.0f;
_viewMatrix.M34 = 0.0f;
_viewMatrix.M44 = 1.0f;
_accumPitchDegrees = MathHelper.ToDegrees((float)Math.Asin(_viewMatrix.M23));
_accumHeadingDegrees = MathHelper.ToDegrees((float)Math.Atan2(_viewMatrix.M13, _viewMatrix.M33));
Quaternion.CreateFromRotationMatrix(ref _viewMatrix, out _orientation);
}
/// <summary>
/// Moves the camera by dx world units to the left or right; dy
/// world units upwards or downwards; and dz world units forwards
/// or backwards.
/// </summary>
/// <param name="dx">Distance to move left or right.</param>
/// <param name="dy">Distance to move up or down.</param>
/// <param name="dz">Distance to move forwards or backwards.</param>
public void Move(float dx, float dy, float dz)
{
// Calculate the forwards direction. Can't just use the
// camera's view direction as doing so will cause the camera to
// move more slowly as the camera's view approaches 90 degrees
// straight up and down.
var forwards = Vector3.Normalize(Vector3.Cross(WORLD_Y_AXIS, _xAxis));
_eye += _xAxis * dx;
_eye += WORLD_Y_AXIS * dy;
_eye += forwards * dz;
Position = _eye;
}
public void UpdateProjectionMatrix(float fovx, float aspect, float znear, float zfar)
{
_fovx = fovx;
_aspectRatio = aspect;
_znear = znear;
_zfar = zfar;
ProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(_fovx), _aspectRatio, _znear, _zfar);
}
public void Rotate(float headingDegrees, float pitchDegrees)
{
headingDegrees = -headingDegrees;
pitchDegrees = -pitchDegrees;
_accumPitchDegrees += pitchDegrees;
if (_accumPitchDegrees > 90.0f)
{
pitchDegrees = 90.0f - (_accumPitchDegrees - pitchDegrees);
_accumPitchDegrees = 90.0f;
}
if (_accumPitchDegrees < -90.0f)
{
pitchDegrees = -90.0f - (_accumPitchDegrees - pitchDegrees);
_accumPitchDegrees = -90.0f;
}
_accumHeadingDegrees += headingDegrees;
if (_accumHeadingDegrees > 360.0f)
_accumHeadingDegrees -= 360.0f;
if (_accumHeadingDegrees < -360.0f)
_accumHeadingDegrees += 360.0f;
var heading = MathHelper.ToRadians(headingDegrees);
var pitch = MathHelper.ToRadians(pitchDegrees);
// Rotate the camera about the world Y axis.
if (heading != 0.0f)
{
Quaternion.CreateFromAxisAngle(ref WORLD_Y_AXIS, heading, out var rotation);
Quaternion.Concatenate(ref rotation, ref _orientation, out _orientation);
}
// Rotate the camera about its local X axis.
if (pitch != 0.0f)
{
Quaternion.CreateFromAxisAngle(ref WORLD_X_AXIS, pitch, out var rotation);
Quaternion.Concatenate(ref _orientation, ref rotation, out _orientation);
}
UpdateViewMatrix();
}
public Ray GetMouseRay()
{
var mouse = _currentMouseState;
var nearPoint = new Vector3(mouse.Position.ToVector2(), 0);
var farPoint = new Vector3(mouse.Position.ToVector2(), 1);
nearPoint = GraphicsDevice.Viewport.Unproject(nearPoint, ProjectionMatrix, ViewMatrix, Matrix.Identity);
farPoint = GraphicsDevice.Viewport.Unproject(farPoint, ProjectionMatrix, ViewMatrix, Matrix.Identity);
var direction = farPoint - nearPoint;
direction.Normalize();
return new Ray(nearPoint, direction);
}
#endregion
protected abstract void SetMousePosition(int x, int y);
protected abstract void SetMouseCursorVisible(bool visible);
protected abstract Point GetScreenCenter();
#region Private Methods
/// <summary>
/// Filters the mouse movement based on a weighted sum of mouse
/// movement from previous frames.
/// <para>
/// For further details see:
/// Nettle, Paul "Smooth Mouse Filtering", flipCode's Ask Midnight column.
/// http://www.flipcode.com/cgi-bin/fcarticles.cgi?show=64462
/// </para>
/// </summary>
/// <param name="x">Horizontal mouse distance from window center.</param>
/// <param name="y">Vertice mouse distance from window center.</param>
protected void PerformMouseFiltering(Vector2 mouse)
{
// Shuffle all the entries in the cache.
// Newer entries at the front. Older entries towards the back.
for (var i = _mouseSmoothingCache.Length - 1; i > 0; --i)
{
_mouseSmoothingCache[i].X = _mouseSmoothingCache[i - 1].X;
_mouseSmoothingCache[i].Y = _mouseSmoothingCache[i - 1].Y;
}
// Store the current mouse movement entry at the front of cache.
_mouseSmoothingCache[0].X = mouse.X;
_mouseSmoothingCache[0].Y = mouse.Y;
var averageX = 0.0f;
var averageY = 0.0f;
var averageTotal = 0.0f;
var currentWeight = 1.0f;
// Filter the mouse movement with the rest of the cache entries.
// Use a weighted average where newer entries have more effect than
// older entries (towards the back of the cache).
for (var i = 0; i < _mouseSmoothingCache.Length; ++i)
{
averageX += _mouseSmoothingCache[i].X * currentWeight;
averageY += _mouseSmoothingCache[i].Y * currentWeight;
averageTotal += 1.0f * currentWeight;
currentWeight *= _mouseSmoothingSensitivity;
}
// Calculate the new smoothed mouse movement.
_smoothedMouseMovement.X = averageX / averageTotal;
_smoothedMouseMovement.Y = averageY / averageTotal;
}
/// <summary>
/// Averages the mouse movement over a couple of frames to smooth out
/// the mouse movement.
/// </summary>
/// <param name="x">Horizontal mouse distance from window center.</param>
/// <param name="y">Vertice mouse distance from window center.</param>
protected void PerformMouseSmoothing(Vector2 mouse)
{
_mouseMovement[_mouseIndex].X = mouse.X;
_mouseMovement[_mouseIndex].Y = mouse.Y;
_smoothedMouseMovement.X = (_mouseMovement[0].X + _mouseMovement[1].X) * 0.5f;
_smoothedMouseMovement.Y = (_mouseMovement[0].Y + _mouseMovement[1].Y) * 0.5f;
_mouseIndex ^= 1;
_mouseMovement[_mouseIndex].X = 0.0f;
_mouseMovement[_mouseIndex].Y = 0.0f;
}
/// <summary>
/// Dampens the rotation by applying the rotation speed to it.
/// </summary>
/// <param name="headingDegrees">Y axis rotation in degrees.</param>
/// <param name="pitchDegrees">X axis rotation in degrees.</param>
protected void RotateSmoothly(float headingDegrees, float pitchDegrees)
{
headingDegrees *= RotationSpeed;
pitchDegrees *= RotationSpeed;
Rotate(headingDegrees, pitchDegrees);
}
protected void UpdateMouse(MouseState mouseState)
{
_previousMouseState = _currentMouseState;
_currentMouseState = mouseState;
if (_currentMouseState.RightButton == ButtonState.Pressed)
{
SetMouseCursorVisible(false);
var center = GetScreenCenter();
var delta = new Vector2(center.X - _currentMouseState.X, center.Y - _currentMouseState.Y);
SetMousePosition(center.X, center.Y);
if (!_cameraLocked)
_cameraLocked = true;
else
{
if (EnableMouseSmoothing)
{
PerformMouseFiltering(delta);
PerformMouseSmoothing(_smoothedMouseMovement);
}
else
_smoothedMouseMovement = delta;
}
}
else
{
SetMouseCursorVisible(true);
_cameraLocked = false;
_smoothedMouseMovement = Vector2.Zero;
}
RotateSmoothly(_smoothedMouseMovement.X, _smoothedMouseMovement.Y);
}
/// <summary>
/// Moves the camera based on player input.
/// </summary>
/// <param name="direction">Direction moved.</param>
/// <param name="elapsedTimeSec">Elapsed game time.</param>
protected void UpdatePosition(ref Vector3 direction, float elapsedTimeSec)
{
if (_currentVelocity.LengthSquared() != 0.0f)
{
// Only move the camera if the velocity vector is not of zero
// length. Doing this guards against the camera slowly creeping
// around due to floating point rounding errors.
var displacement = _currentVelocity * elapsedTimeSec + 0.5f * Acceleration * elapsedTimeSec * elapsedTimeSec;
// Floating point rounding errors will slowly accumulate and
// cause the camera to move along each axis. To prevent any
// unintended movement the displacement vector is clamped to
// zero for each direction that the camera isn't moving in.
// Note that the UpdateVelocity() method will slowly decelerate
// the camera's velocity back to a stationary state when the
// camera is no longer moving along that direction. To account
// for this the camera's current velocity is also checked.
if (direction.X == 0.0f && Math.Abs(_currentVelocity.X) < 1e-6f)
displacement.X = 0.0f;
if (direction.Y == 0.0f && Math.Abs(_currentVelocity.Y) < 1e-6f)
displacement.Y = 0.0f;
if (direction.Z == 0.0f && Math.Abs(_currentVelocity.Z) < 1e-6f)
displacement.Z = 0.0f;
Move(displacement.X, displacement.Y, displacement.Z);
}
// Continuously update the camera's velocity vector even if the
// camera hasn't moved during this call. When the camera is no
// longer being moved the camera is decelerating back to its
// stationary state.
UpdateVelocity(ref direction, elapsedTimeSec);
}
/// <summary>
/// Updates the camera's velocity based on the supplied movement
/// direction and the elapsed time (since this method was last
/// called). The movement direction is the in the range [-1,1].
/// </summary>
/// <param name="direction">Direction moved.</param>
/// <param name="elapsedTimeSec">Elapsed game time.</param>
protected void UpdateVelocity(ref Vector3 direction, float elapsedTimeSec)
{
if (direction.X != 0.0f)
{
// Camera is moving along the x axis.
// Linearly accelerate up to the camera's max speed.
_currentVelocity.X += direction.X * Acceleration.X * elapsedTimeSec;
if (_currentVelocity.X > _velocity.X)
_currentVelocity.X = _velocity.X;
else if (_currentVelocity.X < -_velocity.X)
_currentVelocity.X = -_velocity.X;
}
else
{
// Camera is no longer moving along the x axis.
// Linearly decelerate back to stationary state.
if (_currentVelocity.X > 0.0f)
{
if ((_currentVelocity.X -= Acceleration.X * elapsedTimeSec) < 0.0f)
_currentVelocity.X = 0.0f;
}
else
{
if ((_currentVelocity.X += Acceleration.X * elapsedTimeSec) > 0.0f)
_currentVelocity.X = 0.0f;
}
}
if (direction.Y != 0.0f)
{
// Camera is moving along the y axis. There are two cases here:
// jumping and crouching. When jumping we're always applying a
// negative acceleration to simulate the force of gravity.
// However when crouching we apply a positive acceleration and
// rely more on the direction.
_currentVelocity.Y += direction.Y * Acceleration.Y * elapsedTimeSec;
if (_currentVelocity.Y > _velocity.Y)
_currentVelocity.Y = _velocity.Y;
else if (_currentVelocity.Y < -_velocity.Y)
_currentVelocity.Y = -_velocity.Y;
}
else
{
// Camera is no longer moving along the y axis.
// Linearly decelerate back to stationary state.
if (_currentVelocity.Y > 0.0f)
{
if ((_currentVelocity.Y -= Acceleration.Y * elapsedTimeSec) < 0.0f)
_currentVelocity.Y = 0.0f;
}
else
{
if ((_currentVelocity.Y += Acceleration.Y * elapsedTimeSec) > 0.0f)
_currentVelocity.Y = 0.0f;
}
}
if (direction.Z != 0.0f)
{
// Camera is moving along the z axis.
// Linearly accelerate up to the camera's max speed.
_currentVelocity.Z += direction.Z * Acceleration.Z * elapsedTimeSec;
if (_currentVelocity.Z > _velocity.Z)
_currentVelocity.Z = _velocity.Z;
else if (_currentVelocity.Z < -_velocity.Z)
_currentVelocity.Z = -_velocity.Z;
}
else
{
// Camera is no longer moving along the z axis.
// Linearly decelerate back to stationary state.
if (_currentVelocity.Z > 0.0f)
{
if ((_currentVelocity.Z -= Acceleration.Z * elapsedTimeSec) < 0.0f)
_currentVelocity.Z = 0.0f;
}
else
{
if ((_currentVelocity.Z += Acceleration.Z * elapsedTimeSec) > 0.0f)
_currentVelocity.Z = 0.0f;
}
}
}
protected void UpdateViewMatrix()
{
Matrix.CreateFromQuaternion(ref _orientation, out _viewMatrix);
_xAxis.X = _viewMatrix.M11;
_xAxis.Y = _viewMatrix.M21;
_xAxis.Z = _viewMatrix.M31;
_yAxis.X = _viewMatrix.M12;
_yAxis.Y = _viewMatrix.M22;
_yAxis.Z = _viewMatrix.M32;
_zAxis.X = _viewMatrix.M13;
_zAxis.Y = _viewMatrix.M23;
_zAxis.Z = _viewMatrix.M33;
_viewMatrix.M41 = -Vector3.Dot(_xAxis, _eye);
_viewMatrix.M42 = -Vector3.Dot(_yAxis, _eye);
_viewMatrix.M43 = -Vector3.Dot(_zAxis, _eye);
_viewDir.X = -_zAxis.X;
_viewDir.Y = -_zAxis.Y;
_viewDir.Z = -_zAxis.Z;
}
#endregion
}
}
| 30,132
|
https://github.com/lurichte/codecharta/blob/master/visualization/app/codeCharta/util/nodePathHelper.ts
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| null |
codecharta
|
lurichte
|
TypeScript
|
Code
| 52
| 166
|
import { CodeChartaService } from "../codeCharta.service"
export function getUpdatedBlacklistItemPath(fileName: string, path: string): string {
if (isAbsoluteRootPath(path)) {
return getUpdatedPath(fileName, path)
}
return path
}
export function getUpdatedPath(fileName: string, path: string): string {
const folderArray = path.split("/")
folderArray.splice(2, 0, fileName)
return folderArray.join("/")
}
function isAbsoluteRootPath(path: string): boolean {
return path.startsWith(CodeChartaService.ROOT_PATH + "/")
}
| 33,042
|
https://github.com/bespoke-code/CarND-P8-Kidnapped-Vehicle-Project/blob/master/src/particle_filter.cpp
|
Github Open Source
|
Open Source
|
MIT
| null |
CarND-P8-Kidnapped-Vehicle-Project
|
bespoke-code
|
C++
|
Code
| 1,236
| 3,311
|
/*
* particle_filter.cpp
*
* Created on: Dec 12, 2016
* Author: Tiffany Huang
*/
#include <random>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <cmath>
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include "particle_filter.h"
using namespace std;
void ParticleFilter::init(double x, double y, double theta, double std[]) {
// Set the number of particles. Initialize all particles to first position (based on estimates of
// x, y, theta and their uncertainties from GPS) and all weights to 1.
// Add random Gaussian noise to each particle.
// NOTE: Consult particle_filter.h for more information about this method (and others in this file).
num_particles = 60; // may be changed/tuned
default_random_engine gen;
double std_x, std_y, std_theta; // Standard deviations for x, y, and theta
//Set standard deviations for x, y, and theta
std_x = std[0];
std_y = std[1];
std_theta = std[2];
// This line creates a normal (Gaussian) distribution for x
// Create normal distributions for y and theta
normal_distribution<double> dist_x(x, std_x);
normal_distribution<double> dist_y(y, std_y);
normal_distribution<double> dist_theta(theta, std_theta);
for (int i = 0; i < num_particles; ++i) {
double sample_x, sample_y, sample_theta;
Particle p;
sample_x = dist_x(gen);
sample_y = dist_y(gen);
sample_theta = dist_theta(gen);
p.id = i;
p.x = sample_x;
p.y = sample_y;
p.theta = sample_theta;
p.weight = 1.0;
particles.push_back(p);
weights.push_back(1.0);
}
this->is_initialized = true;
}
void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) {
// Add measurements to each particle and add random Gaussian noise.
// NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful.
// http://en.cppreference.com/w/cpp/numeric/random/normal_distribution
// http://www.cplusplus.com/reference/random/default_random_engine/
std::default_random_engine gen;
double std_x, std_y, std_theta; // Standard deviations for x, y, and theta
//Set standard deviations for x, y, and theta
std_x = std_pos[0];
std_y = std_pos[1];
std_theta = std_pos[2];
// This line creates a normal (Gaussian) distribution for x
// Create normal distributions for y and theta
normal_distribution<double> dist_x(0, std_x);
normal_distribution<double> dist_y(0, std_y);
normal_distribution<double> dist_theta(0, std_theta);
for (auto &p: particles) {
//avoid division by zero
// if yaw rate is zero
if(std::fabs(yaw_rate) > 0.001) {
double yaw_dt = yaw_rate*delta_t;
double v_yaw = velocity/yaw_rate;
// calculate px, py when yaw rate is zero
p.x = p.x + v_yaw * (std::sin(p.theta + yaw_dt) - std::sin(p.theta));
p.y = p.y + v_yaw * (-std::cos(p.theta + yaw_dt) + std::cos(p.theta));
p.theta = p.theta + yaw_dt;
}
else {
// calculate px, py otherwise
p.x = p.x + velocity * std::cos(p.theta)*delta_t;
p.y = p.y + velocity * std::sin(p.theta)*delta_t;
}
p.x += dist_x(gen);
p.y += dist_y(gen);
p.theta += dist_theta(gen);
}
}
void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) {
// Finds the predicted measurement that is closest to each observed measurement
// and assign the observed measurement to this particular landmark.
// NOTE: this method will NOT be called by the grading code. But you will probably find it useful to
// implement this method and use it as a helper during the updateWeights phase.
for (auto &observation : observations) {
// set minimum distance to a disproportionately large number at first
double min_dist = 999999.99;
// set an invalid ID prior to matching
int map_id = -1;
for (auto lm_predicted : predicted) {
// get distance between current/predicted landmarks
double distance = dist(observation.x, observation.y, lm_predicted.x, lm_predicted.y);
// find the landmark closest to the current observation
if (distance < min_dist) {
min_dist = distance;
map_id = lm_predicted.id;
}
}
// set the observation's id to the nearest predicted landmark's id
observation.id = map_id;
}
}
void ParticleFilter::updateWeights(double sensor_range, double std_landmark[],
const std::vector<LandmarkObs> &observations, const Map &map_landmarks) {
// Updates the weights of each particle using a multi-variate Gaussian distribution.
// You can read more about this distribution here: https://en.wikipedia.org/wiki/Multivariate_normal_distribution
// NOTE: The observations are given in the VEHICLE'S coordinate system. Your particles are located
// according to the MAP'S coordinate system. You will need to transform between the two systems.
// Keep in mind that this transformation requires both rotation AND translation (but no scaling).
// The following is a good resource for the theory:
// https://www.willamette.edu/~gorr/classes/GeneralGraphics/Transforms/transforms2d.htm
// and the following is a good resource for the actual equation to implement (look at equation
// 3.33
// http://planning.cs.uiuc.edu/node99.html
// these parameters are fixed throughout the loop, so they are calculated once
double sx = std_landmark[0];
double sy = std_landmark[1];
double weights_sum = 0.0;
for(int i=0; i<num_particles; ++i) {
// get particle data
double px = particles[i].x;
double py = particles[i].y;
double heading = particles[i].theta;
//// for each particle: ////
// convert the observations to global (map) coordinate system
vector<LandmarkObs> observations_global_coords;
for (const auto &observation : observations) {
double trans_x = cos(heading)* observation.x - sin(heading)* observation.y + px;
double trans_y = sin(heading)* observation.x + cos(heading)* observation.y + py;
LandmarkObs obs_map{observation.id, trans_x, trans_y};
observations_global_coords.push_back(obs_map);
}
// Check which landmarks are nearby (0-sensor_range)
std::vector<LandmarkObs> nearby_landmarks;
for (auto landmark : map_landmarks.landmark_list) {
// extract landmark info for clarity
float x_landmark = landmark.x_f;
float y_landmark = landmark.y_f;
int id_landmark = landmark.id_i;
// filter out only landmarks within the sensor range of the current particle
// if the distance to the landmark is within the circle governed by the sensor_range, it's in!
if (dist(x_landmark,y_landmark, px, py) <= sensor_range) {
LandmarkObs landmark_in_range{id_landmark, x_landmark, y_landmark};
// put all nearby landmarks in a vector
nearby_landmarks.push_back(landmark_in_range);
}
}
// match observations with known landmarks
dataAssociation(nearby_landmarks, observations_global_coords);
// check measurement probability
// initial weight is 1
particles[i].weight = 1.0;
for(auto &observation: observations_global_coords) {
double x_obs = observation.x, y_obs = observation.y;
double x_lm, y_lm;
// get the x,y coordinates of the predicted landmark associated with the current observation
for (auto landmark : nearby_landmarks) {
if (landmark.id == observation.id) {
x_lm = landmark.x;
y_lm = landmark.y;
}
}
// here we have the landmark's and observed X and Y coordinates.
// calculating weight using a multivariate gaussian
double dx = x_lm - x_obs;
double dy = y_lm - y_obs;
// set weight (importance)
particles[i].weight *= ( 1/(2*M_PI*sx*sy)) * std::exp( -(std::pow(dx, 2) / (2*std::pow(sx, 2)) +
(std::pow(dy, 2) / (2*std::pow(sy, 2)))));
weights[i] = particles[i].weight;
}
weights_sum += particles[i].weight;
}
for(int i=0; i<num_particles; ++i) {
particles[i].weight /=weights_sum;
weights[i] /= weights_sum;
}
}
void ParticleFilter::resample() {
// Resample particles with replacement with probability proportional to their weight.
// NOTE: You may find std::discrete_distribution helpful here.
// http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution
// Resamples particles with replacement with probability proportional to their weight.
std::vector<Particle> resampled_particles;
// This link was useful for this part:
// https://stackoverflow.com/questions/31153610/setting-up-a-discrete-distribution-in-c
// Using a discrete distribution to resample particles
std::random_device rd;
std::default_random_engine gen(rd());
for (int i=0; i<num_particles; ++i) {
discrete_distribution<int> index(weights.begin(), weights.end());
resampled_particles.push_back(particles[index(gen)]);
}
particles = resampled_particles;
}
Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations,
const std::vector<double>& sense_x, const std::vector<double>& sense_y)
{
//particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to
// associations: The landmark id that goes along with each listed association
// sense_x: the associations x mapping already converted to world coordinates
// sense_y: the associations y mapping already converted to world coordinates
particle.associations= associations;
particle.sense_x = sense_x;
particle.sense_y = sense_y;
}
string ParticleFilter::getAssociations(Particle best)
{
vector<int> v = best.associations;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<int>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseX(Particle best)
{
vector<double> v = best.sense_x;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
string ParticleFilter::getSenseY(Particle best)
{
vector<double> v = best.sense_y;
stringstream ss;
copy( v.begin(), v.end(), ostream_iterator<float>(ss, " "));
string s = ss.str();
s = s.substr(0, s.length()-1); // get rid of the trailing space
return s;
}
| 27,955
|
https://github.com/jack-r-warren/best_effort_parser/blob/master/test/name_test.dart
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,019
|
best_effort_parser
|
jack-r-warren
|
Dart
|
Code
| 990
| 3,146
|
import 'package:best_effort_parser/name.dart';
import 'package:best_effort_parser/src/name/parsed_name.dart';
import 'package:test/test.dart';
main() {
group('NameParser', () {
group('.parse(String input)', () {
test('returns in the case of null or empty input', () {
['', null].map(NameParser.basic().parse).forEach((result) {
[
result.given,
result.family,
result.droppingParticle,
result.nonDroppingParticle,
result.suffix
].forEach((str) => expect(str, isEmpty));
});
});
test('groups first and middle names', () {
var result = NameParser.basic().parse('Jack Ramsey Warren');
expect(result.given, 'Jack Ramsey');
expect(result.family, 'Warren');
expect(result.droppingParticle, isEmpty);
expect(result.nonDroppingParticle, isEmpty);
expect(result.suffix, isEmpty);
});
test('groups first and middle initials', () {
var result = NameParser.basic().parse('J. R. Warren');
expect(result.given, 'J. R.');
expect(result.family, 'Warren');
});
test('strips out odd whitespace', () {
var result = NameParser.basic().parse('Jack Ramsey Warren');
expect(result.given, 'Jack Ramsey');
expect(result.family, 'Warren');
});
test('leaves floating punctuation', () {
var result = NameParser.basic().parse('Jack - Ramsey Warren');
expect(result.given, 'Jack - Ramsey');
expect(result.family, 'Warren');
});
test(
'rotates the first comma-separated portion to the end to handle last, first',
() {
var result = NameParser.basic().parse('Warren, Jack Ramsey');
expect(result.given, 'Jack Ramsey');
expect(result.family, 'Warren');
});
test('handles particles properly', () {
var result = NameParser.basic().parse('Jean de La Fontaine');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test('handles particles properly with full last, first ordering', () {
var result = NameParser.basic().parse('de La Fontaine, Jean');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test('handles particles properly with partial last, first ordering', () {
var result = NameParser.basic().parse('La Fontaine, Jean de');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test('handles particles properly with partial last, first ordering', () {
var result = NameParser.basic().parse('La Fontaine, Jean de');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test(
'handles particles properly with partial last, first ordering with an odd comma',
() {
var result = NameParser.basic().parse('La Fontaine, Jean, de');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test('handles particles properly with minimal last, first ordering', () {
var result = NameParser.basic().parse('Fontaine, Jean de La');
expect(result.given, 'Jean');
expect(result.family, 'Fontaine');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, 'La');
expect(result.suffix, isEmpty);
});
test('handles lowercase particles as dropping', () {
var result = NameParser.basic().parse('Willem de Kooning');
expect(result.given, 'Willem');
expect(result.family, 'Kooning');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, isEmpty);
});
test('handles lowercase particles as dropping in last, first', () {
var result = NameParser.basic().parse('de Kooning, Willem');
expect(result.given, 'Willem');
expect(result.family, 'Kooning');
expect(result.droppingParticle, 'de');
expect(result.nonDroppingParticle, isEmpty);
});
test('handles uppercase particles as non-dropping', () {
var result = NameParser.basic().parse('Willem De Kooning');
expect(result.given, 'Willem');
expect(result.family, 'Kooning');
expect(result.droppingParticle, isEmpty);
expect(result.nonDroppingParticle, 'De');
});
test('handles uppercase particles as non-dropping in last, first', () {
var result = NameParser.basic().parse('De Kooning, Willem');
expect(result.given, 'Willem');
expect(result.family, 'Kooning');
expect(result.droppingParticle, isEmpty);
expect(result.nonDroppingParticle, 'De');
});
test('handles suffixes', () {
var result = NameParser.basic().parse('Elizabeth Alexandra Mary II');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test('handles suffixes when comma-separated', () {
var result = NameParser.basic().parse('Elizabeth Alexandra Mary, II');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test('handles suffixes in last, first when the suffix follows last', () {
var result = NameParser.basic().parse('Mary II, Elizabeth Alexandra');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test(
'handles suffixes in last, first when the suffix follows last with a comma',
() {
var result = NameParser.basic().parse('Mary, II, Elizabeth Alexandra');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test('handles suffixes in last, first when the suffix is at the end', () {
var result = NameParser.basic().parse('Mary, Elizabeth Alexandra II');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test(
'handles suffixes in last, first when the suffix is at the end with a comma',
() {
var result = NameParser.basic().parse('Mary, Elizabeth Alexandra, II');
expect(result.given, 'Elizabeth Alexandra');
expect(result.family, 'Mary');
expect(result.suffix, 'II');
});
test(
'handles all-caps names as expected, with particles being non-dropping',
() {
var result = NameParser.basic().parse('WILLEM DE KOONING');
expect(result.given, 'WILLEM');
expect(result.family, 'KOONING');
expect(result.nonDroppingParticle, 'DE');
});
test('handles multiple of different parts', () {
final target = ParsedName('family1 family2',
given: 'given1 given2',
droppingParticle: 'de van',
nonDroppingParticle: 'Di La',
suffix: 'Jr. III PhD.');
final parser = NameParser.basic();
final samples = <String>[
'given1 given2 de van Di La family1 family2 Jr. III PhD.',
'given1 given2 de Di van La family1 family2 Jr. III PhD.',
'given1 given2 de van Di La family1 family2, Jr. III PhD.',
'given1 given2 de van Di La family1 family2 Jr., III PhD.',
'given1 given2 de van Di La family1 family2, Jr. III, PhD.',
'family1 family2 Jr. III PhD., given1 given2 de van Di La',
'family1 family2, Jr. III PhD., given1 given2 de van Di La',
'family1 family2, Jr., III PhD., given1, given2, de van, Di La',
'family1 family2 Jr., given1 given2 de van Di La III PhD.',
'Di La family1 family2, given1 given2 de van, Jr. III PhD.',
'de van Di La family1 family2, given1 given2, Jr. III PhD.',
'Di La de van family1 family2, given1, given2 Jr. III PhD.',
].map(parser.parse);
expect(samples, everyElement(equals(target)));
});
test('puts suffixes as the family if that\'s all we have', () {
expect(NameParser.basic().parse('I II III').family, 'I II III');
});
});
});
group('ParsedName', () {
group('operator ==', () {
test('returns false on different types', () {
// ignore: unrelated_type_equality_checks
expect(ParsedName('foo') == 5, isFalse);
});
test('returns false if fields are different, true if same', () {
final samples = [
ParsedName('abc'),
ParsedName('', given: 'abc'),
ParsedName('', droppingParticle: 'abc'),
ParsedName('', nonDroppingParticle: 'abc'),
ParsedName('', suffix: 'abc')
];
for (int a = 0; a < 5; a++) {
for (int b = 0; b < 5; b++) {
expect(samples[a] == samples[b], a == b);
}
}
});
});
group('toString()', () {
test('uses space separation by default', () {
var result = NameParser.basic().parse('Jack Warren');
expect(result.toString(), 'Jack Warren');
});
test('can use a custom separator', () {
var result = NameParser.basic().parse('Jack Warren');
expect(result.toString(separator: '.'), 'Jack.Warren');
});
});
group('diagonisticString()', () {
test('fills its default parameters', () {
var result = NameParser.basic()
.parse('given1 given2 de van Di La family1 family2 Jr. III PhD.');
expect(
result.diagnosticString(),
'[Given]: given1 given2 [Dropping Particle]: de van [Non-dropping Particle]: Di La '
'[Family]: family1 family2 [Suffix]: Jr. III PhD.');
});
test('can have customized labels/separators', () {
var result = NameParser.basic()
.parse('given1 given2 de van Di La family1 family2 Jr. III PhD.');
expect(
result.diagnosticString(
separator: '-',
givenLabel: '',
droppingParticleLabel: '',
nonDroppingParticleLabel: '',
familyLabel: '',
suffixLabel: ''),
result.toString(separator: '-'));
});
});
});
}
| 5,711
|
https://github.com/AntoniyaIvanova/SoftUni/blob/master/C#/C# Advanced/C# Advanced/05. Defining Classes/EXERCISE/09. Pokemon Trainer/Trainer.cs
|
Github Open Source
|
Open Source
|
MIT
| null |
SoftUni
|
AntoniyaIvanova
|
C#
|
Code
| 106
| 350
|
namespace _09._Pokemon_Trainer
{
using System.Collections.Generic;
public class Trainer
{
public string Name;
public int NumberOfBadges;
public List<Pokemon> Pokemons;
public Trainer(string name)
{
Name = name;
NumberOfBadges = 0;
Pokemons = new List<Pokemon>();
}
public bool ContainsType(string element)
{
foreach (var pokemon in Pokemons)
{
if (pokemon.Element == element)
{
return true;
}
}
return false;
}
public void AddPokemon(Pokemon pokemon)
{
Pokemons.Add(pokemon);
}
public void DecreaseHealth()
{
for (int i = 0; i < Pokemons.Count; i++)
{
if (Pokemons[i].Health - 10 > 0)
{
Pokemons[i].Health -= 10;
}
else
{
Pokemons.Remove(Pokemons[i]);
}
}
}
public override string ToString()
{
return $"{this.Name} {this.NumberOfBadges} {this.Pokemons.Count}";
}
}
}
| 10,592
|
https://github.com/ljm556-max/xing-ui-v3/blob/master/src/lib/Button.vue
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
xing-ui-v3
|
ljm556-max
|
Vue
|
Code
| 590
| 2,113
|
<template>
<button class="xx-button" :class="buttonClasses" :disabled="disabled">
<span v-if="loading" class="xx-loadingIndicator"></span>
<slot></slot>
</button>
</template>
<script>
import { computed } from 'vue'
export default {
name: 'x-button',
props: {
size: {
type: String,
default: 'normal'
},
theme: {
type: String,
default: 'default'
},
level: {
type: String,
default: 'normal'
},
disabled: {
type: Boolean,
default: false
},
loading: {
type: Boolean,
default: false
}
},
setup (props) {
const { theme, size, level } = props
const buttonClasses = computed(() => {
return {
[`xx-theme-${theme}`]:theme,
[`xx-size-${size}`]:size,
[`xx-level-${level}`]:level
}
})
return { buttonClasses }
}
}
</script>
<style scoped lang="scss">
@import "../assets/css/xing-ui-v3.scss";
.xx-button {
display: inline-flex;
justify-content: center;
align-items: center;
box-sizing: border-box;
padding: 0 $padding-lg;
height: $button-normal-height;
border: none;
box-shadow: $button-shadow;
border-radius: $border-radius;
font-size: $button-normal-font-size;
white-space: nowrap;
cursor: pointer;
transition: background $button-duration;
&:focus { outline: none; }
&::-moz-focus-inner { border: 0; }
&.xx-theme-primary {
background: $button-primary-background;
color: $white;
@media (any-hover: hover){
&:hover, &:focus { background: $main-hover-color;}
}
&:active { background: $main-active-color; }
}
&.xx-theme-default {
padding: 0 $padding-lg - 1;
background: $white;
border: $button-default-border;
color: $button-default-color;
transition: all $button-duration;
@media (any-hover: hover){
&:hover,
&:focus {
border-color: $button-default-focus-color;
color: $button-default-focus-color;
}
}
&:active {
background: $main-color-light;
border-color: $main-active-color;
color: $main-active-color;
}
}
&.xx-theme-link {
background: none;
box-shadow: none;
color: $button-link-color;
@media (any-hover: hover){
&:hover,&:focus { color: $main-hover-color; }
}
&:active { color: $main-active-color; }
}
&.xx-size-mini {
padding: 0 $padding-xs;
height: $button-mini-height;
font-size: $button-mini-font-size;
}
&.xx-size-small {
height: $button-small-height;
font-size: $button-small-font-size;
padding: 0 $padding-md;
}
&.xx-size-large {
height: $button-large-height;
font-size: $button-large-font-size;
padding: 0 $padding-lg * 2;
}
&.xx-theme-primary {
&.xx-level-info {
background: $info;
@media (any-hover: hover){
&:hover, &:focus { background: $info-hover; }
}
&:active { background: $info-active; }
}
&.xx-level-warning {
background: $warning;
@media (any-hover: hover){
&:hover, &:focus { background: $warning-hover; }
}
&:active { background: $warning-active; }
}
&.xx-level-danger {
background: $error;
@media (any-hover: hover){
&:hover, &:focus { background: $error-hover; }
}
&:active { background: $error-active; }
}
&.xx-level-success {
background: $success;
@media (any-hover: hover){
&:hover, &:focus { background: $success-hover; }
}
&:active { background: $success-active; }
}
}
&.xx-theme-default {
&.xx-level-info {
color: $info;
border-color: $info;
@media (any-hover: hover){
&:hover, &:focus { border-color: $info-hover; color: $info-hover; }
}
&:active {
background: lighten($info, 25%);
border-color: $info-active;
color: $info-active;
}
}
&.xx-level-warning {
color: $warning;
border-color: $warning;
@media (any-hover: hover){
&:hover, &:focus { border-color: $warning-hover; color: $warning-hover; }
}
&:active {
background: lighten($warning, 25%);
border-color: $warning-active;
color: $warning-active;
}
}
&.xx-level-danger {
color: $error;
border-color: $error;
@media (any-hover: hover){
&:hover, &:focus { border-color: $error-hover; color: $error-hover; }
}
&:active {
background: lighten($error, 25%);
border-color: $error-active;
color: $error-active;
}
}
&.xx-level-success {
color: $success;
border-color: $success;
@media (any-hover: hover){
&:hover, &:focus { border-color: $success-hover; color: $success-hover; }
}
&:active {
background: lighten($success, 25%);
border-color: $success-active;
color: $success-active;
}
}
}
&.xx-theme-link {
background: none;
box-shadow: none;
color: $button-link-color;
@media (any-hover: hover){
&:hover,&:focus { color: $main-hover-color; }
}
&:active { color: $main-active-color; }
}
&.xx-theme-link {
&.xx-level-info {
color: $info;
@media (any-hover: hover){
&:hover,&:focus { color: $info-hover; }
}
&:active { color: $info-active; }
}
&.xx-level-warning {
color: $warning;
@media (any-hover: hover){
&:hover,&:focus { color: $warning-hover; }
}
&:active { color: $warning-active; }
}
&.xx-level-success {
color: $success;
@media (any-hover: hover){
&:hover,&:focus { color: $success-hover; }
}
&:active { color: $success-active; }
}
&.xx-level-danger {
color: $error;
@media (any-hover: hover){
&:hover,&:focus { color: $error-hover; }
}
&:active { color: $error-active; }
}
}
&[disabled] { cursor: not-allowed; }
&.xx-theme-default {
&[disabled] {
color: $button-disabled;
&:hover { border-color: $button-disabled;}
}
}
&.xx-theme-primary {
&[disabled] { background: $button-disabled; }
}
&.xx-theme-link {
&[disabled] { color: $button-disabled; }
}
}
</style>
| 27,211
|
https://github.com/Ashersam/NewAgUpdater/blob/master/src/components/Content/Translation/TranslationPanel.js
|
Github Open Source
|
Open Source
|
MIT
| null |
NewAgUpdater
|
Ashersam
|
JavaScript
|
Code
| 565
| 2,039
|
import React, { useState } from "react";
import AutographaStore from "../../AutographaStore.js";
import { Observer } from "mobx-react";
import * as mobx from "mobx";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemIcon from "@material-ui/core/ListItemIcon";
import PlayCircleOutlineIcon from "@material-ui/icons/PlayCircleOutline";
import StopIcon from "@material-ui/icons/Stop";
import { makeStyles } from "@material-ui/core/styles";
import Paper from "@material-ui/core/Paper";
import JointVerse from "./JointVerse";
import { Zoom, Tooltip } from "@material-ui/core";
import { lastSavedtime, fetchAudio } from "./helpers.js";
const useStyles = makeStyles((theme) => ({
root: {
width: "100%",
backgroundColor: theme.palette.background.paper,
},
listItemIcon: {
minWidth: 20,
alignSelf: "self-start",
},
paper: {
position: "absolute",
},
list: {
paddingTop: 42,
},
listItemText: {
fontSize: "0.7em", //Insert your required size
},
listItemPlayIcon: {
alignSelf: "normal",
},
}));
const initialState = {
mouseX: null,
mouseY: null,
};
const TranslationPanel = (props) => {
const classes = useStyles();
const [selectedIndex, setSelectedIndex] = useState(1);
const [pointer, setPointer] = useState(initialState);
const [index, setIndex] = useState();
const tInsert = mobx.toJS(AutographaStore.tIns[0]);
const tDelete = mobx.toJS(AutographaStore.tDel[0]);
const handleListItemClick = (event, index) => {
let recordedVerse = mobx.toJS(AutographaStore.recVerse);
AutographaStore.vId = index;
setSelectedIndex(AutographaStore.vId);
if (
AutographaStore.recVerse !== null &&
AutographaStore.vId !== undefined
) {
if (recordedVerse.indexOf(AutographaStore.vId) !== -1) {
AutographaStore.isWarning = true;
AutographaStore.currentSession = false;
lastSavedtime();
}
if (recordedVerse.indexOf(AutographaStore.vId) === -1) {
AutographaStore.isWarning = false;
AutographaStore.currentSession = true;
}
}
};
const handleKeyUp = (e) => {
let timeout = 0;
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => {
if (!AutographaStore.setDiff) {
props.onSave();
}
}, 3000);
};
const handleJoint = (event, i) => {
setIndex(i);
setPointer({
mouseX: event.clientX - 2,
mouseY: event.clientY - 4,
});
};
const closeJoint = () => {
setPointer(initialState);
};
return (
<React.Fragment>
<Observer>
{() => (
<Paper>
<div
dir={AutographaStore.scriptDirection}
style={{
fontSize: `${AutographaStore.currentFontValue}px`,
}}
className={`col-12 col-ref verse-input ${AutographaStore.scriptDirection.toLowerCase()}`}
>
{AutographaStore.toggle && (tInsert || tDelete) ? (
<div style={{ textAlign: "center" }}>
<span style={{ color: "#27b97e", fontWeight: "bold" }}>
(+) {tInsert}
</span>{" "}
|{" "}
<span style={{ color: "#f50808", fontWeight: "bold" }}>
(-) {tDelete}
</span>
</div>
) : (
""
)}
<List className={classes.list}>
{props.chunkGroup &&
props.chunkGroup.map((value, index) => {
return (
<ListItem
dense
className={classes.root}
key={index}
selected={selectedIndex === index + 1}
id={`versediv${index + 1}`}
onClick={(event) =>
handleListItemClick(event, index + 1)
}
style={{
cursor: "text",
whiteSpace: "pre-wrap",
}}
>
{mobx.toJS(
AutographaStore.AudioMount &&
mobx.toJS(AutographaStore.recVerse)
) &&
mobx
.toJS(AutographaStore.recVerse)
.map((recVerse, recIndex) => {
if (recVerse - 1 === index)
return (
<ListItemIcon
className={classes.listItemPlayIcon}
onClick={fetchAudio}
>
{AutographaStore.isPlaying === false && (
<Tooltip
title="Play/Stop"
TransitionComponent={Zoom}
>
<PlayCircleOutlineIcon
edge="start"
tabIndex={-1}
style={{
color: "red",
cursor: "pointer",
}}
onClick={() =>
index + 1 === AutographaStore.vId
? (AutographaStore.isPlaying = true)
: (AutographaStore.isPlaying = false)
}
/>
</Tooltip>
)}
{index + 1 === AutographaStore.vId &&
AutographaStore.isPlaying === true ? (
<StopIcon
edge="start"
tabIndex={-1}
style={{ cursor: "pointer" }}
onClick={() =>
(AutographaStore.isPlaying = false)
}
/>
) : (
AutographaStore.isPlaying === true && (
<PlayCircleOutlineIcon
edge="start"
tabIndex={-1}
style={{
color: "red",
cursor: "pointer",
}}
onClick={() =>
(AutographaStore.isPlaying = true)
}
/>
)
)}
</ListItemIcon>
);
})}
<ListItemIcon className={classes.listItemIcon}>
{index + 1}
</ListItemIcon>
<span
id={`v${index + 1}`}
onKeyUp={handleKeyUp}
data-chunk-group={AutographaStore.chunkGroup[index]}
contentEditable={
AutographaStore.jointVerse[index] === undefined &&
AutographaStore.toggle !== true
? true
: false
}
className={classes.listItemText}
style={{
outline: "none",
marginLeft: "10px",
paddingRight: "50px ",
maxWidth: "-webkit-fill-available",
}}
onContextMenu={
index !== 0
? (event) => {
handleJoint(event, index);
}
: false
}
suppressContentEditableWarning={true}
>
{AutographaStore.jointVerse[index] === undefined
? AutographaStore.translationContent[index]
? AutographaStore.translationContent[index]
: ""
: "----- Joint with the preceding verse(s) -----"}
</span>
</ListItem>
);
})}
</List>
</div>
</Paper>
)}
</Observer>
<JointVerse show={pointer} index={index} close={closeJoint} />
</React.Fragment>
);
};
export default TranslationPanel;
| 36,995
|
https://github.com/madhubs/36-sluggram-frontend/blob/master/src/component/landing-container/index.js
|
Github Open Source
|
Open Source
|
MIT
| null |
36-sluggram-frontend
|
madhubs
|
JavaScript
|
Code
| 90
| 280
|
import React from 'react';
import AuthForm from '../auth-form';
import {connect} from 'react-redux';
import * as utils from '../../lib/utils';
import {signupRequest, loginRequest} from '../../action/auth-action';
class LandingContainer extends React.Component {
render() {
let {params} = this.props.match;
let handleComplete = params.auth === 'login' ?
this.props.login :
this.props.signup;
let redirect = path => this.props.history.replace(path);
return (
<div>
<h2>hello world from landing!</h2>
<AuthForm
auth={params.auth}
redirect={redirect}
onComplete={handleComplete}/>
</div>
);
}
}
let mapStateToProps = () => ({});
let mapDispatchToProps = dispatch => ({
signup: user => dispatch(signupRequest(user)),
login: user => dispatch(loginRequest(user)),
});
export default connect(mapStateToProps, mapDispatchToProps)(LandingContainer);
| 23,342
|
https://github.com/CloyMonisVMax/VMaxZeeAdsPlugin/blob/master/Example/Pods/VMaxZeeOMSDK/OMSDK_Zeedigitalesselgroup.xcframework/ios-arm64_i386_x86_64-simulator/OMSDK_Zeedigitalesselgroup.framework/Headers/OMIDSDK.h
|
Github Open Source
|
Open Source
|
MIT
| null |
VMaxZeeAdsPlugin
|
CloyMonisVMax
|
C
|
Code
| 194
| 356
|
//
// OMIDSDK.h
// AppVerificationLibrary
//
// Created by Daria on 05/06/2017.
//
#import <Foundation/Foundation.h>
/**
* This application level class will be called by all integration partners to ensure OM SDK has been activated before calling any other API methods.
* Any attempt to use other API methods prior to activation will result in an error.
*
* Note that OM SDK may only be used on the main UI thread.
* Make sure you are on the main thread when you initialize the SDK, create its
* objects, and invoke its methods.
*/
@interface OMIDZeedigitalesselgroupSDK : NSObject
/**
* The current semantic version of the integrated OMID library.
*/
+ (nonnull NSString *)versionString;
/**
* Shared OMIDSDK instance.
*/
@property(class, readonly, nonnull) OMIDZeedigitalesselgroupSDK *sharedInstance
NS_SWIFT_NAME(shared);
/**
* A Boolean value indicating whether the OMID library has been activated.
*
* The value of this property is YES if the OMID library has already been activated. Allows the integration partner to check that they are compatible with the running OMID library version.
*/
@property(atomic, readonly, getter = isActive) BOOL active;
/**
* Enables the integration partner to activate OMID.
*/
- (BOOL)activate;
@end
| 4,463
|
https://github.com/michaelbarber/algorithms/blob/master/src/main/java/datastructures/arrays/MyDynamicArray.java
|
Github Open Source
|
Open Source
|
MIT
| null |
algorithms
|
michaelbarber
|
Java
|
Code
| 270
| 576
|
package datastructures.arrays;
public class MyDynamicArray<T> {
private Object[] data;
private int INITIAL_SIZE = 16;
private int size = 0;
public MyDynamicArray() {
data = new Object[INITIAL_SIZE];
}
public void add(T object) {
if (size == INITIAL_SIZE) {
resize();
}
data[size] = object;
size++;
}
public void insert(int index, T object){
// size is 1
// just index 0
if (size == INITIAL_SIZE) {
resize();
}
// first i need to move everything up (push up) so start from end and work towards index
// REMEMBER 'int i = x' IS WHERE YOU ARE STARTING!!! AND THE MIDDLE BIT IS WHERE YOU WANT TO END!!!
// size will always be one more than the index. here it's ok just to say i > index
for(int i = size; i > index; i--){
data[i] = data[i-1];
}
data[index] = object;
size++;
}
public void delete(int index){
// first i need to move everything up (push up) so start from index and work towards end
// size will always be one more than the index. if we are working with int i = index AT THE START (on left side) then we need to subtract 1 from size
for(int i = index; i < size-1; i++){
data[i] = data[i+1];
}
data[size-1] = null;
size--;
}
public Object get(int index){
return data[index];
}
public void set(int index, Object obj){
data[index] = obj;
}
public int getSize(){
return size;
}
public void resize() {
Object[] newData = new Object[INITIAL_SIZE * 2];
for (int i = 0; i < size; i++) {
newData[i] = data[i];
}
INITIAL_SIZE = INITIAL_SIZE * 2;
data = newData;
}
}
| 29,606
|
https://github.com/iquesada/practice-skeletons/blob/master/C-SHARP/BusinessLogic/Sum.cs
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,019
|
practice-skeletons
|
iquesada
|
C#
|
Code
| 23
| 58
|
using System;
namespace BusinessLogic
{
public class Sum
{
public double SumOperators(double op1, double op2)
{
return op1 + op2;
}
}
}
| 28,236
|
https://github.com/bradlipovsky/antarctic-rift-catalog/blob/master/make_catalog.py
|
Github Open Source
|
Open Source
|
MIT
| null |
antarctic-rift-catalog
|
bradlipovsky
|
Python
|
Code
| 140
| 575
|
import numpy as np
import os
import arc
import importlib
importlib.reload(arc)
import json
import pandas as pd
import pickle
def main():
atl06_path = "/data/fast1/arc/atl06"
filelist_path = "/data/fast1/arc/filelists"
dataset_path = '/data/fast0/'
output_path = '/data/fast1/arc/rift_obs'
#shelf_names = ['brunt', 'fimbul', 'amery',
# 'ap', 'ross', 'ronne', 'amundsen', 'east']
# shelf_names = ['ross', 'ronne', 'amundsen', 'east']
shelf_names = ['brunt']
for shelf in shelf_names:
print(" ")
print('==================================')
print(' PROCESSING THE ATL06 DATA (%s)'%shelf)
print('==================================')
atl06_file_name = os.path.join(atl06_path, shelf + '.pkl')
atl06_filelist = os.path.join(filelist_path, shelf + '-list.json')
with open(atl06_filelist,'rb') as handle:
filelist = json.load(handle)
arc.ingest(filelist,atl06_file_name,dataset_path)
# Load data
with open(atl06_file_name, 'rb') as handle:
atl06_data = pickle.load(handle)
print('==================================')
print(' FINDING THE RIFTS (%s)'%shelf)
print('==================================')
# Find the rifts
rift_obs = arc.get_rifts(atl06_data)
# Store the rifts in a dataframe
rift_obs=pd.DataFrame(rift_obs)
rift_obs_output_file_name = os.path.join(output_path, shelf + '.pkl')
with open(rift_obs_output_file_name, 'wb') as handle:
pickle.dump(rift_obs, handle, protocol=pickle.HIGHEST_PROTOCOL)
if __name__ == "__main__":
main()
| 48,944
|
https://github.com/WebCuratorTool/webcurator-core/blob/master/src/main/java/org/webcurator/core/profiles/ProfileTimeUnit.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,020
|
webcurator-core
|
WebCuratorTool
|
Java
|
Code
| 50
| 152
|
package org.webcurator.core.profiles;
import java.util.ArrayList;
import java.util.List;
/**
* Enumeration containing time units.
*/
public enum ProfileTimeUnit {
SECOND, MINUTE, HOUR, DAY, WEEK;
public static ProfileTimeUnit DEFAULT = SECOND;
public static List<String> getProfileDataTimeNames() {
List<String> names = new ArrayList<String>();
for (ProfileTimeUnit profileTimeUnit : ProfileTimeUnit.values()) {
names.add(profileTimeUnit.name());
}
return names;
}
}
| 14,927
|
https://github.com/gparlakov/scuri/blob/master/src/common/get-spec-file-name.ts
|
Github Open Source
|
Open Source
|
MIT
| 2,023
|
scuri
|
gparlakov
|
TypeScript
|
Code
| 179
| 487
|
import { basename as ngBasename, Path } from '@angular-devkit/core';
import { join, normalize } from 'path';
import { applyPathTemplate, FileEntry, TEMPLATE_FILENAME_RE } from '@angular-devkit/schematics';
import { ClassTemplateData } from '../types';
import { getLogger } from './logger';
export function getSpecFilePathName(name: string) {
return name.replace('.ts', '.spec.ts');
}
export function getSpecFileCustomName(
classData: Omit<ClassTemplateData, 'levenshtein' | 'params' | 'publicMethods' | 'setupMethods'>,
templateName: string
): string | undefined {
const l = getLogger(getSpecFileCustomName.name)
l.debug(`entering for classData ${JSON.stringify(classData)} templateName ${templateName}`)
const templateFile: FileEntry = {
// it's all right to lie to FileEntry as it only uses it to get the file name and not the folder
// folder is added with folderfy below
path: ngBasename(<Path><unknown>templateName),
content: Buffer.from(''),
};
const fileResult = applyPathTemplate(classData)(templateFile);
l.debug(`looking for templateFile ${templateFile.path} result in ${fileResult}`)
const folderfyFn = folderfy(classData.folder);
const result = typeof fileResult?.path === 'string'
? folderfyFn(
fileResult.path
// remove template if any
.replace(TEMPLATE_FILENAME_RE, '')
)
: undefined;
l.debug(`returning ${result}`);
return result;
}
function folderfy(folder: string) {
return (fileName: string) => {
return join(
normalize(folder),
fileName
// remove the path as a possible duplicate
.replace(folder, '')
);
};
}
| 39,401
|
https://github.com/samuelfabel/Swashbuckle.AspNetCore.Yaml/blob/master/Swashbuckle.AspNetCore.Yaml/Application/SwaggerYamlBuilderExtensions.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
Swashbuckle.AspNetCore.Yaml
|
samuelfabel
|
C#
|
Code
| 35
| 136
|
using System;
using Swashbuckle.AspNetCore.Swagger.Yaml;
namespace Microsoft.AspNetCore.Builder
{
public static class SwaggerYamlBuilderExtensions
{
public static IApplicationBuilder UseSwaggerYaml(
this IApplicationBuilder app,
Action<SwaggerYamlOptions> setupAction = null)
{
var options = new SwaggerYamlOptions();
setupAction?.Invoke(options);
return app.UseMiddleware<SwaggerYamlMiddleware>(options);
}
}
}
| 19,892
|
https://github.com/N500/WindowsTemplateStudio/blob/master/templates/Uwp/_comp/MVVMLight/Project.SplitView.TabbedNav._VB/Helpers/NavHelper.vb
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
WindowsTemplateStudio
|
N500
|
Visual Basic
|
Code
| 87
| 278
|
Imports Microsoft.UI.Xaml.Controls
Namespace Helpers
Public Class NavHelper
' This helper class allows to specify the page that will be shown when you click on a NavigationViewItem
'
' Usage in xaml:
' <winui:NavigationViewItem x:Uid="Shell_Main" Icon="Document" helpers:NavHelper.NavigateTo="AppName.ViewModels.MainViewModel" />
'
' Usage in code:
' NavHelper.SetNavigateTo(navigationViewItem, GetType(MainViewModel).FullName)
Public Shared Function GetNavigateTo(item As NavigationViewItem) As String
Return TryCast(item.GetValue(NavigateToProperty), String)
End Function
Public Shared Sub SetNavigateTo(item As NavigationViewItem, value As String)
item.SetValue(NavigateToProperty, value)
End Sub
Public Shared ReadOnly NavigateToProperty As DependencyProperty =
DependencyProperty.RegisterAttached("NavigateTo", GetType(String), GetType(NavHelper), New PropertyMetadata(Nothing))
End Class
End Namespace
| 2,144
|
https://github.com/mullikine/RosettaCodeData/blob/master/Task/Unix-ls/Python/unix-ls.py
|
Github Open Source
|
Open Source
|
Info-ZIP
| 2,022
|
RosettaCodeData
|
mullikine
|
Python
|
Code
| 19
| 73
|
>>> import os
>>> print('\n'.join(sorted(os.listdir('.'))))
DLLs
Doc
LICENSE.txt
Lib
NEWS.txt
README.txt
Scripts
Tools
include
libs
python.exe
pythonw.exe
tcl
>>>
| 18,850
|
https://github.com/alinadk12/pets/blob/master/resources/views/requests/request.blade.php
|
Github Open Source
|
Open Source
|
MIT
| null |
pets
|
alinadk12
|
PHP
|
Code
| 234
| 978
|
@extends('layouts.app')
@section('title')
<h1>{!! __('requests.titles.puppy_request') !!}</h1>
@stop
@section('content')
{!! Form::open(['url' => '/request', 'class' => 'form-horizontal']) !!}
{{ csrf_field() }}
{!! Form::hidden('user_id', $user->id) !!}
<div class="form-group{{ $errors->has('breed_id') ? ' has-error' : '' }}">
{!! Form::label('breed_id', __('requests.fields.breed').' * ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
@foreach($breeds as $breed)
{{ Form::radio('breed_id', $breed->id) }} {{ App::isLocale('en') ? $breed->name_en : $breed->name_ru }}<br>
@endforeach
</div>
</div>
<div class="form-group{{ $errors->has('gender') ? ' has-error' : '' }}">
{!! Form::label('gender', __('requests.fields.gender').' * ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::radio('gender', '1') !!} {!! __('requests.fields.male') !!}<br>
{!! Form::radio('gender', '0') !!} {!! __('requests.fields.female') !!}
</div>
</div>
<div class="form-group{{ $errors->has('age_month') ? ' has-error' : '' }}">
{!! Form::label('age_month', __('requests.fields.age').' ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('age_month', old('age_month'), ['class' => 'form-control']) !!}
{!! $errors->has('age_month') ? $errors->first('age_month', '<p class="help-block">:message</p>') : '' !!}
</div>
</div>
<div class="form-group{{ $errors->has('max_price') ? ' has-error' : '' }}">
{!! Form::label('max_price', __('requests.fields.max_price').' ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::text('max_price', old('max_price'), ['class' => 'form-control']) !!}
{!! $errors->has('max_price') ? $errors->first('max_price', '<p class="help-block">:message</p>') : '' !!}
</div>
</div>
<div class="form-group{{ $errors->has('comments') ? ' has-error' : '' }}">
{!! Form::label('comments', __('requests.fields.comments').' ', ['class' => 'col-md-4 control-label']) !!}
<div class="col-md-6">
{!! Form::textarea('comments', old('comments'), ['class' => 'form-control', 'style' => 'resize: vertical', 'rows' => '4']) !!}
{!! $errors->has('comments') ? $errors->first('comments', '<p class="help-block">:message</p>') : '' !!}
</div>
</div>
<div class="form-group">
<div class="text-center">
{!! Form::submit(__('requests.buttons.send'), ['class' => 'button']) !!}
</div>
</div>
{!! Form::close() !!}
@stop
| 3,206
|
https://github.com/commonsensesoftware/More/blob/master/test/More.UI.Tests/ComponentModel/ExpandableItemTTest.cs
|
Github Open Source
|
Open Source
|
MIT
| 2,018
|
More
|
commonsensesoftware
|
C#
|
Code
| 535
| 1,671
|
namespace More.ComponentModel
{
using FluentAssertions;
using System;
using Xunit;
public class ExpandableItemTTest
{
[Fact]
public void item_should_be_collapsed_by_default()
{
// arrange
var item = new ExpandableItem<string>( "test" );
// act
// assert
item.IsExpanded.Should().BeFalse();
}
[Fact]
public void item_should_expand_using_property()
{
// arrange
var item = new ExpandableItem<string>( "test" );
item.MonitorEvents();
// act
item.IsExpanded = true;
// assert
item.ShouldRaisePropertyChangeFor( i => i.IsExpanded );
item.ShouldRaise( nameof( item.Expanded ) );
}
[Fact]
public void item_should_expand_using_command()
{
// arrange
var item = new ExpandableItem<string>( "test" );
item.MonitorEvents();
// act
item.Expand.Execute( null );
// assert
item.ShouldRaisePropertyChangeFor( i => i.IsExpanded );
item.ShouldRaise( nameof( item.Expanded ) );
}
[Fact]
public void item_should_collapse_using_command()
{
// arrange
var item = new ExpandableItem<string>( true, "test" );
item.MonitorEvents();
// act
item.Collapse.Execute( null );
// assert
item.ShouldRaisePropertyChangeFor( i => i.IsExpanded );
item.ShouldRaise( nameof( item.Collapsed ) );
}
[Fact]
public void X3DX3D_should_equate_equal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "test" );
// act
var result = item == other;
// assert
result.Should().BeTrue();
}
[Fact]
public void X3DX3D_should_equate_equal_caseX2Dinsensitive_items()
{
// arrange
var item = new ExpandableItem<string>( "test", StringComparer.OrdinalIgnoreCase );
var other = new ExpandableItem<string>( "TEST" );
// act
var result = item == other;
// assert
result.Should().BeTrue();
}
[Fact]
public void X3DX3D_should_not_equate_unequal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "abc" );
// act
var result = item == other;
// assert
result.Should().BeFalse();
}
[Fact]
public void ne_should_not_equate_equal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "test" );
// act
var result = item != other;
// assert
result.Should().BeFalse();
}
[Fact]
public void ne_should_not_equate_equal_caseX2Dinsensitive_items()
{
// arrange
var item = new ExpandableItem<string>( "test", StringComparer.OrdinalIgnoreCase );
var other = new ExpandableItem<string>( "TEST" );
// act
var result = item != other;
// assert
result.Should().BeFalse();
}
[Fact]
public void ne_should_equate_unequal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "abc" );
// act
var result = item != other;
// assert
result.Should().BeTrue();
}
[Fact]
public void equals_should_equate_equal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "test" );
// act
var result = item.Equals( other );
// assert
result.Should().BeTrue();
}
[Fact]
public void equals_should_equate_equal_caseX2Dinsensitive_items()
{
// arrange
var item = new ExpandableItem<string>( "test", StringComparer.OrdinalIgnoreCase );
var other = new ExpandableItem<string>( "TEST" );
// act
var result = item.Equals( other );
// assert
result.Should().BeTrue();
}
[Fact]
public void equals_should_not_equate_unequal_items()
{
// arrange
var item = new ExpandableItem<string>( "test" );
var other = new ExpandableItem<string>( "abc" );
// act
var result = item.Equals( other );
// assert
result.Should().BeFalse();
}
[Fact]
public void equals_should_equate_equal_objects()
{
// arrange
var item = new ExpandableItem<string>( "test" );
object other = new ExpandableItem<string>( "test" );
// act
var result = item.Equals( other );
// assert
result.Should().BeTrue();
}
[Fact]
public void equals_should_equate_equal_caseX2Dinsensitive_objects()
{
// arrange
var item = new ExpandableItem<string>( "test", StringComparer.OrdinalIgnoreCase );
object other = new ExpandableItem<string>( "TEST" );
// act
var result = item.Equals( other );
// assert
result.Should().BeTrue();
}
[Fact]
public void equals_should_not_equate_unequal_objects()
{
// arrange
var item = new ExpandableItem<string>( "test" );
object other = new ExpandableItem<string>( "abc" );
// act
var result = item.Equals( other );
// assert
result.Should().BeFalse();
}
}
}
| 39,100
|
https://github.com/ddechant/Gazelle/blob/master/templates/applicant/view.twig
|
Github Open Source
|
Open Source
|
Unlicense
| 2,022
|
Gazelle
|
ddechant
|
Twig
|
Code
| 484
| 1,626
|
{{ header('View Applications', {'js': 'apply'}) }}
<div class="thin">
<div class="linkbox">
<a href="/apply.php" class="brackets">Apply</a>
{% if id and not is_staff %}
<a href="/apply.php?action=view" class="brackets">View your applications</a>
{% endif %}
{% if is_staff %}
{% if resolved or (id and not resolved) %}
<a href="/apply.php?action=view" class="brackets">Current applications</a>
{% endif %}
{% if not resolved %}
<a href="/apply.php?action=view&status=resolved" class="brackets">Resolved applications</a>
{% endif %}
<a href="/apply.php?action=admin" class="brackets">Manage roles</a>
{% endif %}
</div>
{% if id %}
<div class="box">
<div class="head"{% if app.isResolved %} style="font-style: italic;"{% endif %}>{{ app.roleTitle }}
{% if is_staff %}
<div style="float: right;">
<form name="role_resolve" method="POST" action="/apply.php?action=view&id={{ id }}">
<input type="submit" name="resolve" value="{% if app.isResolved %}Reopen{% else %}Resolve{% endif %}" />
<input type="hidden" name="id" value="{{ id }}"/>
<input type="hidden" name="auth" value="{{ auth }}"/>
</form>
</div>
<br />Application received from {{ app.userId|user_full }} received {{ app.created|time_diff }}.
{% endif %}
</div>
<div class="pad">
<p>{{ app.body|bb_format }}</p>
{% if not app.isResolved %}
<form id="thread_note_reply" name="thread_note_replay" method="POST" action="/apply.php?action=view&id={{ id }}">
{% endif %}
<table class="forum_post wrap_overflow box vertical_margin">
{% for note in app.story(is_staff) %}
<tr class="colhead_dark">
<td colspan="2">
<div style="float: left; padding-top: 10px;">{{ note.user_id|user_url }} - {{ note.created|time_diff }}</div>
</td>
</tr>
<tr>
<td colspan="2" style="border: 2px solid
{%- if not is_staff -%}
#808080
{%- else -%}
{%- if note.visibility == 'staff' -%}
#FF8017
{%- else -%}
#347235
{%- endif -%}
{%- endif -%}
;">
<div style="margin: 5px 4px 20px 4px">
{{ note.body|bb_format }}
</div>
{% if is_staff and not app.isResolved %}
<div style="float: right; padding-top: 10px 0; margin-bottom: 6px;">
<input type="submit" name="note-delete-{{ note.id }}" value="delete" style="height: 20px; padding: 0 3px;"/>
</div>
{% endif %}
</td>
</tr>
{% endfor %}
{% if not app.isResolved %}
{% if is_staff %}
<tr>
<td class="label">Visibility</td>
<td>
<div>
<input type="radio" name="visibility" value="public" /><label for="public">public <span style="color: #347235">(member will see this reply)</span></label><br />
<input type="radio" name="visibility" value="staff" checked /><label for="staff">staff <span style="color: #FF8017">(only staff will see this reply)</span></label><br />
</div>
<td>
</tr>
{% endif %}
<tr>
<td class="label">Reply</td>
<td>
{{ note.preview|raw }}
{{ note.field|raw }}
</td>
</tr>
<tr>
<td colspan="2">
<div style="text-align: center;">
<input type="hidden" name="id" value="{{ id }}"/>
<input type="hidden" name="auth" value="{{ auth }}"/>
{{ note.button|raw }}
<input type="submit" id="submit" value="Save" />
</div>
</td>
</tr>
{% endif %}
</table>
</form>
</div>
</div>
{% else %}
<h3>{% if resolved %}Resolved{% else %}Current{% endif %} Applications</h3>
{% for a in list %}
{% if loop.first %}
<table>
<tr class="colhead">
<td>Role</td>
{% if is_staff %}
<td>Applicant</td>
{% endif %}
<td>Date Created</td>
<td>Comments</td>
<td>Last comment from</td>
<td>Last comment added</td>
</tr>
{% endif %}
<tr>
<td><a href="apply.php?action=view&id={{ a.ID }}">{{ a.Role }}</a></td>
{% if is_staff %}
<td><a href="user.php?id={{ a.UserID }}">{{ a.Username }}</a></td>
{% endif %}
<td>{{ a.Created|time_diff }}</td>
<td>{{ a.nr_notes|number_format }}</td>
<td><a href="user.php?id={{ a.last_UserID }}">{{ a.last_Username }}</a></td>
<td>{% if a.last_Created %}{{ a.last_Created|time_diff }}{% endif %}</td>
</tr>
{% if loop.last %}
</table>
{% endif %}
{% else %}
<div class="box pad">The cupboard is empty. There are no applications to show.</div>
{% endfor %}
{% endif %}
</div>
{{ footer() }}
| 22,359
|
https://github.com/Programmerino/webapi/blob/master/graphics/shapedetection/shapedetection_js.go
|
Github Open Source
|
Open Source
|
BSD-3-Clause
| 2,022
|
webapi
|
Programmerino
|
Go
|
Code
| 3,014
| 10,242
|
// Code generated by webidl-bind. DO NOT EDIT.
package shapedetection
import "syscall/js"
import (
"github.com/Programmerino/webapi/dom/geometry"
"github.com/Programmerino/webapi/javascript"
)
// using following types:
// geometry.DOMRectReadOnly
// javascript.FrozenArray
// javascript.PromiseFinally
// source idl files:
// promises.idl
// shape-detection-api.idl
// transform files:
// promises.go.md
// shape-detection-api.go.md
// workaround for compiler error
func unused(value interface{}) {
// TODO remove this method
}
type Union struct {
Value js.Value
}
func (u *Union) JSValue() js.Value {
return u.Value
}
func UnionFromJS(value js.Value) *Union {
return &Union{Value: value}
}
// enum: BarcodeFormat
type BarcodeFormat int
const (
AztecBarcodeFormat BarcodeFormat = iota
Code128BarcodeFormat
Code39BarcodeFormat
Code93BarcodeFormat
CodabarBarcodeFormat
DataMatrixBarcodeFormat
Ean13BarcodeFormat
Ean8BarcodeFormat
ItfBarcodeFormat
Pdf417BarcodeFormat
QrCodeBarcodeFormat
UnknownBarcodeFormat
UpcABarcodeFormat
UpcEBarcodeFormat
)
var barcodeFormatToWasmTable = []string{
"aztec", "code_128", "code_39", "code_93", "codabar", "data_matrix", "ean_13", "ean_8", "itf", "pdf417", "qr_code", "unknown", "upc_a", "upc_e",
}
var barcodeFormatFromWasmTable = map[string]BarcodeFormat{
"aztec": AztecBarcodeFormat, "code_128": Code128BarcodeFormat, "code_39": Code39BarcodeFormat, "code_93": Code93BarcodeFormat, "codabar": CodabarBarcodeFormat, "data_matrix": DataMatrixBarcodeFormat, "ean_13": Ean13BarcodeFormat, "ean_8": Ean8BarcodeFormat, "itf": ItfBarcodeFormat, "pdf417": Pdf417BarcodeFormat, "qr_code": QrCodeBarcodeFormat, "unknown": UnknownBarcodeFormat, "upc_a": UpcABarcodeFormat, "upc_e": UpcEBarcodeFormat,
}
// JSValue is converting this enum into a javascript object
func (this *BarcodeFormat) JSValue() js.Value {
return js.ValueOf(this.Value())
}
// Value is converting this into javascript defined
// string value
func (this BarcodeFormat) Value() string {
idx := int(this)
if idx >= 0 && idx < len(barcodeFormatToWasmTable) {
return barcodeFormatToWasmTable[idx]
}
panic("unknown input value")
}
// BarcodeFormatFromJS is converting a javascript value into
// a BarcodeFormat enum value.
func BarcodeFormatFromJS(value js.Value) BarcodeFormat {
key := value.String()
conv, ok := barcodeFormatFromWasmTable[key]
if !ok {
panic("unable to convert '" + key + "'")
}
return conv
}
// enum: LandmarkType
type LandmarkType int
const (
MouthLandmarkType LandmarkType = iota
EyeLandmarkType
NoseLandmarkType
)
var landmarkTypeToWasmTable = []string{
"mouth", "eye", "nose",
}
var landmarkTypeFromWasmTable = map[string]LandmarkType{
"mouth": MouthLandmarkType, "eye": EyeLandmarkType, "nose": NoseLandmarkType,
}
// JSValue is converting this enum into a javascript object
func (this *LandmarkType) JSValue() js.Value {
return js.ValueOf(this.Value())
}
// Value is converting this into javascript defined
// string value
func (this LandmarkType) Value() string {
idx := int(this)
if idx >= 0 && idx < len(landmarkTypeToWasmTable) {
return landmarkTypeToWasmTable[idx]
}
panic("unknown input value")
}
// LandmarkTypeFromJS is converting a javascript value into
// a LandmarkType enum value.
func LandmarkTypeFromJS(value js.Value) LandmarkType {
key := value.String()
conv, ok := landmarkTypeFromWasmTable[key]
if !ok {
panic("unable to convert '" + key + "'")
}
return conv
}
// callback: PromiseTemplateOnFulfilled
type PromiseSequenceBarcodeFormatOnFulfilledFunc func(value []BarcodeFormat)
// PromiseSequenceBarcodeFormatOnFulfilled is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceBarcodeFormatOnFulfilled js.Func
func PromiseSequenceBarcodeFormatOnFulfilledToJS(callback PromiseSequenceBarcodeFormatOnFulfilledFunc) *PromiseSequenceBarcodeFormatOnFulfilled {
if callback == nil {
return nil
}
ret := PromiseSequenceBarcodeFormatOnFulfilled(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 []BarcodeFormat // javascript: sequence<BarcodeFormat> value
)
__length0 := args[0].Length()
__array0 := make([]BarcodeFormat, __length0, __length0)
for __idx0 := 0; __idx0 < __length0; __idx0++ {
var __seq_out0 BarcodeFormat
__seq_in0 := args[0].Index(__idx0)
__seq_out0 = BarcodeFormatFromJS(__seq_in0)
__array0[__idx0] = __seq_out0
}
_p0 = __array0
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceBarcodeFormatOnFulfilledFromJS(_value js.Value) PromiseSequenceBarcodeFormatOnFulfilledFunc {
return func(value []BarcodeFormat) {
var (
_args [1]interface{}
_end int
)
_p0 := js.Global().Get("Array").New(len(value))
for __idx0, __seq_in0 := range value {
__seq_out0 := __seq_in0.JSValue()
_p0.SetIndex(__idx0, __seq_out0)
}
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// callback: PromiseTemplateOnRejected
type PromiseSequenceBarcodeFormatOnRejectedFunc func(reason js.Value)
// PromiseSequenceBarcodeFormatOnRejected is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceBarcodeFormatOnRejected js.Func
func PromiseSequenceBarcodeFormatOnRejectedToJS(callback PromiseSequenceBarcodeFormatOnRejectedFunc) *PromiseSequenceBarcodeFormatOnRejected {
if callback == nil {
return nil
}
ret := PromiseSequenceBarcodeFormatOnRejected(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 js.Value // javascript: any reason
)
_p0 = args[0]
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceBarcodeFormatOnRejectedFromJS(_value js.Value) PromiseSequenceBarcodeFormatOnRejectedFunc {
return func(reason js.Value) {
var (
_args [1]interface{}
_end int
)
_p0 := reason
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// callback: PromiseTemplateOnFulfilled
type PromiseSequenceDetectedBarcodeOnFulfilledFunc func(value []*DetectedBarcode)
// PromiseSequenceDetectedBarcodeOnFulfilled is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceDetectedBarcodeOnFulfilled js.Func
func PromiseSequenceDetectedBarcodeOnFulfilledToJS(callback PromiseSequenceDetectedBarcodeOnFulfilledFunc) *PromiseSequenceDetectedBarcodeOnFulfilled {
if callback == nil {
return nil
}
ret := PromiseSequenceDetectedBarcodeOnFulfilled(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 []*DetectedBarcode // javascript: sequence<DetectedBarcode> value
)
__length0 := args[0].Length()
__array0 := make([]*DetectedBarcode, __length0, __length0)
for __idx0 := 0; __idx0 < __length0; __idx0++ {
var __seq_out0 *DetectedBarcode
__seq_in0 := args[0].Index(__idx0)
__seq_out0 = DetectedBarcodeFromJS(__seq_in0)
__array0[__idx0] = __seq_out0
}
_p0 = __array0
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceDetectedBarcodeOnFulfilledFromJS(_value js.Value) PromiseSequenceDetectedBarcodeOnFulfilledFunc {
return func(value []*DetectedBarcode) {
var (
_args [1]interface{}
_end int
)
_p0 := js.Global().Get("Array").New(len(value))
for __idx0, __seq_in0 := range value {
__seq_out0 := __seq_in0.JSValue()
_p0.SetIndex(__idx0, __seq_out0)
}
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// callback: PromiseTemplateOnRejected
type PromiseSequenceDetectedBarcodeOnRejectedFunc func(reason js.Value)
// PromiseSequenceDetectedBarcodeOnRejected is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceDetectedBarcodeOnRejected js.Func
func PromiseSequenceDetectedBarcodeOnRejectedToJS(callback PromiseSequenceDetectedBarcodeOnRejectedFunc) *PromiseSequenceDetectedBarcodeOnRejected {
if callback == nil {
return nil
}
ret := PromiseSequenceDetectedBarcodeOnRejected(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 js.Value // javascript: any reason
)
_p0 = args[0]
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceDetectedBarcodeOnRejectedFromJS(_value js.Value) PromiseSequenceDetectedBarcodeOnRejectedFunc {
return func(reason js.Value) {
var (
_args [1]interface{}
_end int
)
_p0 := reason
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// callback: PromiseTemplateOnFulfilled
type PromiseSequenceDetectedFaceOnFulfilledFunc func(value []*DetectedFace)
// PromiseSequenceDetectedFaceOnFulfilled is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceDetectedFaceOnFulfilled js.Func
func PromiseSequenceDetectedFaceOnFulfilledToJS(callback PromiseSequenceDetectedFaceOnFulfilledFunc) *PromiseSequenceDetectedFaceOnFulfilled {
if callback == nil {
return nil
}
ret := PromiseSequenceDetectedFaceOnFulfilled(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 []*DetectedFace // javascript: sequence<DetectedFace> value
)
__length0 := args[0].Length()
__array0 := make([]*DetectedFace, __length0, __length0)
for __idx0 := 0; __idx0 < __length0; __idx0++ {
var __seq_out0 *DetectedFace
__seq_in0 := args[0].Index(__idx0)
__seq_out0 = DetectedFaceFromJS(__seq_in0)
__array0[__idx0] = __seq_out0
}
_p0 = __array0
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceDetectedFaceOnFulfilledFromJS(_value js.Value) PromiseSequenceDetectedFaceOnFulfilledFunc {
return func(value []*DetectedFace) {
var (
_args [1]interface{}
_end int
)
_p0 := js.Global().Get("Array").New(len(value))
for __idx0, __seq_in0 := range value {
__seq_out0 := __seq_in0.JSValue()
_p0.SetIndex(__idx0, __seq_out0)
}
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// callback: PromiseTemplateOnRejected
type PromiseSequenceDetectedFaceOnRejectedFunc func(reason js.Value)
// PromiseSequenceDetectedFaceOnRejected is a javascript function type.
//
// Call Release() when done to release resouces
// allocated to this type.
type PromiseSequenceDetectedFaceOnRejected js.Func
func PromiseSequenceDetectedFaceOnRejectedToJS(callback PromiseSequenceDetectedFaceOnRejectedFunc) *PromiseSequenceDetectedFaceOnRejected {
if callback == nil {
return nil
}
ret := PromiseSequenceDetectedFaceOnRejected(js.FuncOf(func(this js.Value, args []js.Value) interface{} {
var (
_p0 js.Value // javascript: any reason
)
_p0 = args[0]
callback(_p0)
// returning no return value
return nil
}))
return &ret
}
func PromiseSequenceDetectedFaceOnRejectedFromJS(_value js.Value) PromiseSequenceDetectedFaceOnRejectedFunc {
return func(reason js.Value) {
var (
_args [1]interface{}
_end int
)
_p0 := reason
_args[0] = _p0
_end++
_value.Invoke(_args[0:_end]...)
return
}
}
// dictionary: BarcodeDetectorOptions
type BarcodeDetectorOptions struct {
Formats []BarcodeFormat
}
// JSValue is allocating a new javasript object and copy
// all values
func (_this *BarcodeDetectorOptions) JSValue() js.Value {
out := js.Global().Get("Object").New()
value0 := js.Global().Get("Array").New(len(_this.Formats))
for __idx0, __seq_in0 := range _this.Formats {
__seq_out0 := __seq_in0.JSValue()
value0.SetIndex(__idx0, __seq_out0)
}
out.Set("formats", value0)
return out
}
// BarcodeDetectorOptionsFromJS is allocating a new
// BarcodeDetectorOptions object and copy all values from
// input javascript object
func BarcodeDetectorOptionsFromJS(value js.Wrapper) *BarcodeDetectorOptions {
input := value.JSValue()
var out BarcodeDetectorOptions
var (
value0 []BarcodeFormat // javascript: sequence<BarcodeFormat> {formats Formats formats}
)
__length0 := input.Get("formats").Length()
__array0 := make([]BarcodeFormat, __length0, __length0)
for __idx0 := 0; __idx0 < __length0; __idx0++ {
var __seq_out0 BarcodeFormat
__seq_in0 := input.Get("formats").Index(__idx0)
__seq_out0 = BarcodeFormatFromJS(__seq_in0)
__array0[__idx0] = __seq_out0
}
value0 = __array0
out.Formats = value0
return &out
}
// dictionary: FaceDetectorOptions
type FaceDetectorOptions struct {
MaxDetectedFaces int
FastMode bool
}
// JSValue is allocating a new javasript object and copy
// all values
func (_this *FaceDetectorOptions) JSValue() js.Value {
out := js.Global().Get("Object").New()
value0 := _this.MaxDetectedFaces
out.Set("maxDetectedFaces", value0)
value1 := _this.FastMode
out.Set("fastMode", value1)
return out
}
// FaceDetectorOptionsFromJS is allocating a new
// FaceDetectorOptions object and copy all values from
// input javascript object
func FaceDetectorOptionsFromJS(value js.Wrapper) *FaceDetectorOptions {
input := value.JSValue()
var out FaceDetectorOptions
var (
value0 int // javascript: unsigned short {maxDetectedFaces MaxDetectedFaces maxDetectedFaces}
value1 bool // javascript: boolean {fastMode FastMode fastMode}
)
value0 = (input.Get("maxDetectedFaces")).Int()
out.MaxDetectedFaces = value0
value1 = (input.Get("fastMode")).Bool()
out.FastMode = value1
return &out
}
// dictionary: Landmark
type Landmark struct {
Locations *javascript.FrozenArray
Type LandmarkType
}
// JSValue is allocating a new javasript object and copy
// all values
func (_this *Landmark) JSValue() js.Value {
out := js.Global().Get("Object").New()
value0 := _this.Locations.JSValue()
out.Set("locations", value0)
value1 := _this.Type.JSValue()
out.Set("type", value1)
return out
}
// LandmarkFromJS is allocating a new
// Landmark object and copy all values from
// input javascript object
func LandmarkFromJS(value js.Wrapper) *Landmark {
input := value.JSValue()
var out Landmark
var (
value0 *javascript.FrozenArray // javascript: FrozenArray {locations Locations locations}
value1 LandmarkType // javascript: LandmarkType {type Type _type}
)
value0 = javascript.FrozenArrayFromJS(input.Get("locations"))
out.Locations = value0
value1 = LandmarkTypeFromJS(input.Get("type"))
out.Type = value1
return &out
}
// class: BarcodeDetector
type BarcodeDetector struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *BarcodeDetector) JSValue() js.Value {
return _this.Value_JS
}
// BarcodeDetectorFromJS is casting a js.Wrapper into BarcodeDetector.
func BarcodeDetectorFromJS(value js.Wrapper) *BarcodeDetector {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &BarcodeDetector{}
ret.Value_JS = input
return ret
}
func GetSupportedFormats() (_result *PromiseSequenceBarcodeFormat) {
_klass := js.Global().Get("BarcodeDetector")
_method := _klass.Get("getSupportedFormats")
var (
_args [0]interface{}
_end int
)
_returned := _method.Invoke(_args[0:_end]...)
var (
_converted *PromiseSequenceBarcodeFormat // javascript: Promise _what_return_name
)
_converted = PromiseSequenceBarcodeFormatFromJS(_returned)
_result = _converted
return
}
func NewBarcodeDetector(barcodeDetectorOptions *BarcodeDetectorOptions) (_result *BarcodeDetector) {
_klass := js.Global().Get("BarcodeDetector")
var (
_args [1]interface{}
_end int
)
if barcodeDetectorOptions != nil {
_p0 := barcodeDetectorOptions.JSValue()
_args[0] = _p0
_end++
}
_returned := _klass.New(_args[0:_end]...)
var (
_converted *BarcodeDetector // javascript: BarcodeDetector _what_return_name
)
_converted = BarcodeDetectorFromJS(_returned)
_result = _converted
return
}
func (_this *BarcodeDetector) Detect(image *Union) (_result *PromiseSequenceDetectedBarcode) {
var (
_args [1]interface{}
_end int
)
_p0 := image.JSValue()
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("detect", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedBarcode // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedBarcodeFromJS(_returned)
_result = _converted
return
}
// class: DetectedBarcode
type DetectedBarcode struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *DetectedBarcode) JSValue() js.Value {
return _this.Value_JS
}
// DetectedBarcodeFromJS is casting a js.Wrapper into DetectedBarcode.
func DetectedBarcodeFromJS(value js.Wrapper) *DetectedBarcode {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &DetectedBarcode{}
ret.Value_JS = input
return ret
}
// BoundingBox returning attribute 'boundingBox' with
// type geometry.DOMRectReadOnly (idl: DOMRectReadOnly).
func (_this *DetectedBarcode) BoundingBox() *geometry.DOMRectReadOnly {
var ret *geometry.DOMRectReadOnly
value := _this.Value_JS.Get("boundingBox")
ret = geometry.DOMRectReadOnlyFromJS(value)
return ret
}
// RawValue returning attribute 'rawValue' with
// type string (idl: DOMString).
func (_this *DetectedBarcode) RawValue() string {
var ret string
value := _this.Value_JS.Get("rawValue")
ret = (value).String()
return ret
}
// Format returning attribute 'format' with
// type BarcodeFormat (idl: BarcodeFormat).
func (_this *DetectedBarcode) Format() BarcodeFormat {
var ret BarcodeFormat
value := _this.Value_JS.Get("format")
ret = BarcodeFormatFromJS(value)
return ret
}
// CornerPoints returning attribute 'cornerPoints' with
// type javascript.FrozenArray (idl: FrozenArray).
func (_this *DetectedBarcode) CornerPoints() *javascript.FrozenArray {
var ret *javascript.FrozenArray
value := _this.Value_JS.Get("cornerPoints")
ret = javascript.FrozenArrayFromJS(value)
return ret
}
// class: DetectedFace
type DetectedFace struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *DetectedFace) JSValue() js.Value {
return _this.Value_JS
}
// DetectedFaceFromJS is casting a js.Wrapper into DetectedFace.
func DetectedFaceFromJS(value js.Wrapper) *DetectedFace {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &DetectedFace{}
ret.Value_JS = input
return ret
}
// BoundingBox returning attribute 'boundingBox' with
// type geometry.DOMRectReadOnly (idl: DOMRectReadOnly).
func (_this *DetectedFace) BoundingBox() *geometry.DOMRectReadOnly {
var ret *geometry.DOMRectReadOnly
value := _this.Value_JS.Get("boundingBox")
ret = geometry.DOMRectReadOnlyFromJS(value)
return ret
}
// Landmarks returning attribute 'landmarks' with
// type javascript.FrozenArray (idl: FrozenArray).
func (_this *DetectedFace) Landmarks() *javascript.FrozenArray {
var ret *javascript.FrozenArray
value := _this.Value_JS.Get("landmarks")
if value.Type() != js.TypeNull && value.Type() != js.TypeUndefined {
ret = javascript.FrozenArrayFromJS(value)
}
return ret
}
// class: FaceDetector
type FaceDetector struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *FaceDetector) JSValue() js.Value {
return _this.Value_JS
}
// FaceDetectorFromJS is casting a js.Wrapper into FaceDetector.
func FaceDetectorFromJS(value js.Wrapper) *FaceDetector {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &FaceDetector{}
ret.Value_JS = input
return ret
}
func NewFaceDetector(faceDetectorOptions *FaceDetectorOptions) (_result *FaceDetector) {
_klass := js.Global().Get("FaceDetector")
var (
_args [1]interface{}
_end int
)
if faceDetectorOptions != nil {
_p0 := faceDetectorOptions.JSValue()
_args[0] = _p0
_end++
}
_returned := _klass.New(_args[0:_end]...)
var (
_converted *FaceDetector // javascript: FaceDetector _what_return_name
)
_converted = FaceDetectorFromJS(_returned)
_result = _converted
return
}
func (_this *FaceDetector) Detect(image *Union) (_result *PromiseSequenceDetectedFace) {
var (
_args [1]interface{}
_end int
)
_p0 := image.JSValue()
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("detect", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedFace // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedFaceFromJS(_returned)
_result = _converted
return
}
// class: Promise
type PromiseSequenceBarcodeFormat struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *PromiseSequenceBarcodeFormat) JSValue() js.Value {
return _this.Value_JS
}
// PromiseSequenceBarcodeFormatFromJS is casting a js.Wrapper into PromiseSequenceBarcodeFormat.
func PromiseSequenceBarcodeFormatFromJS(value js.Wrapper) *PromiseSequenceBarcodeFormat {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &PromiseSequenceBarcodeFormat{}
ret.Value_JS = input
return ret
}
func (_this *PromiseSequenceBarcodeFormat) Then(onFulfilled *PromiseSequenceBarcodeFormatOnFulfilled, onRejected *PromiseSequenceBarcodeFormatOnRejected) (_result *PromiseSequenceBarcodeFormat) {
var (
_args [2]interface{}
_end int
)
var __callback0 js.Value
if onFulfilled != nil {
__callback0 = (*onFulfilled).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
if onRejected != nil {
var __callback1 js.Value
if onRejected != nil {
__callback1 = (*onRejected).Value
} else {
__callback1 = js.Null()
}
_p1 := __callback1
_args[1] = _p1
_end++
}
_returned := _this.Value_JS.Call("then", _args[0:_end]...)
var (
_converted *PromiseSequenceBarcodeFormat // javascript: Promise _what_return_name
)
_converted = PromiseSequenceBarcodeFormatFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceBarcodeFormat) Catch(onRejected *PromiseSequenceBarcodeFormatOnRejected) (_result *PromiseSequenceBarcodeFormat) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onRejected != nil {
__callback0 = (*onRejected).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("catch", _args[0:_end]...)
var (
_converted *PromiseSequenceBarcodeFormat // javascript: Promise _what_return_name
)
_converted = PromiseSequenceBarcodeFormatFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceBarcodeFormat) Finally(onFinally *javascript.PromiseFinally) (_result *PromiseSequenceBarcodeFormat) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onFinally != nil {
__callback0 = (*onFinally).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("finally", _args[0:_end]...)
var (
_converted *PromiseSequenceBarcodeFormat // javascript: Promise _what_return_name
)
_converted = PromiseSequenceBarcodeFormatFromJS(_returned)
_result = _converted
return
}
// class: Promise
type PromiseSequenceDetectedBarcode struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *PromiseSequenceDetectedBarcode) JSValue() js.Value {
return _this.Value_JS
}
// PromiseSequenceDetectedBarcodeFromJS is casting a js.Wrapper into PromiseSequenceDetectedBarcode.
func PromiseSequenceDetectedBarcodeFromJS(value js.Wrapper) *PromiseSequenceDetectedBarcode {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &PromiseSequenceDetectedBarcode{}
ret.Value_JS = input
return ret
}
func (_this *PromiseSequenceDetectedBarcode) Then(onFulfilled *PromiseSequenceDetectedBarcodeOnFulfilled, onRejected *PromiseSequenceDetectedBarcodeOnRejected) (_result *PromiseSequenceDetectedBarcode) {
var (
_args [2]interface{}
_end int
)
var __callback0 js.Value
if onFulfilled != nil {
__callback0 = (*onFulfilled).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
if onRejected != nil {
var __callback1 js.Value
if onRejected != nil {
__callback1 = (*onRejected).Value
} else {
__callback1 = js.Null()
}
_p1 := __callback1
_args[1] = _p1
_end++
}
_returned := _this.Value_JS.Call("then", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedBarcode // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedBarcodeFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceDetectedBarcode) Catch(onRejected *PromiseSequenceDetectedBarcodeOnRejected) (_result *PromiseSequenceDetectedBarcode) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onRejected != nil {
__callback0 = (*onRejected).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("catch", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedBarcode // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedBarcodeFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceDetectedBarcode) Finally(onFinally *javascript.PromiseFinally) (_result *PromiseSequenceDetectedBarcode) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onFinally != nil {
__callback0 = (*onFinally).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("finally", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedBarcode // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedBarcodeFromJS(_returned)
_result = _converted
return
}
// class: Promise
type PromiseSequenceDetectedFace struct {
// Value_JS holds a reference to a javascript value
Value_JS js.Value
}
func (_this *PromiseSequenceDetectedFace) JSValue() js.Value {
return _this.Value_JS
}
// PromiseSequenceDetectedFaceFromJS is casting a js.Wrapper into PromiseSequenceDetectedFace.
func PromiseSequenceDetectedFaceFromJS(value js.Wrapper) *PromiseSequenceDetectedFace {
input := value.JSValue()
if typ := input.Type(); typ == js.TypeNull || typ == js.TypeUndefined {
return nil
}
ret := &PromiseSequenceDetectedFace{}
ret.Value_JS = input
return ret
}
func (_this *PromiseSequenceDetectedFace) Then(onFulfilled *PromiseSequenceDetectedFaceOnFulfilled, onRejected *PromiseSequenceDetectedFaceOnRejected) (_result *PromiseSequenceDetectedFace) {
var (
_args [2]interface{}
_end int
)
var __callback0 js.Value
if onFulfilled != nil {
__callback0 = (*onFulfilled).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
if onRejected != nil {
var __callback1 js.Value
if onRejected != nil {
__callback1 = (*onRejected).Value
} else {
__callback1 = js.Null()
}
_p1 := __callback1
_args[1] = _p1
_end++
}
_returned := _this.Value_JS.Call("then", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedFace // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedFaceFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceDetectedFace) Catch(onRejected *PromiseSequenceDetectedFaceOnRejected) (_result *PromiseSequenceDetectedFace) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onRejected != nil {
__callback0 = (*onRejected).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("catch", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedFace // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedFaceFromJS(_returned)
_result = _converted
return
}
func (_this *PromiseSequenceDetectedFace) Finally(onFinally *javascript.PromiseFinally) (_result *PromiseSequenceDetectedFace) {
var (
_args [1]interface{}
_end int
)
var __callback0 js.Value
if onFinally != nil {
__callback0 = (*onFinally).Value
} else {
__callback0 = js.Null()
}
_p0 := __callback0
_args[0] = _p0
_end++
_returned := _this.Value_JS.Call("finally", _args[0:_end]...)
var (
_converted *PromiseSequenceDetectedFace // javascript: Promise _what_return_name
)
_converted = PromiseSequenceDetectedFaceFromJS(_returned)
_result = _converted
return
}
| 35,567
|
https://github.com/misterhaan/track7.org/blob/master/pen/series.js
|
Github Open Source
|
Open Source
|
MIT
| null |
track7.org
|
misterhaan
|
JavaScript
|
Code
| 43
| 156
|
$(function() {
var serieslist = new Vue({
el: "#serieslist",
data: {
stories: [],
loading: false,
error: false
},
created: function() {
this.loading = true;
$.get("/api/stories/series", {id: $("h1").data("series-id")}, result => {
if(!result.fail)
this.stories = result.stories;
else
this.error = result.error;
}, "json");
}
});
});
| 45,028
|
https://github.com/home-assistant/core/blob/master/tests/components/unifiprotect/test_views.py
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
core
|
home-assistant
|
Python
|
Code
| 1,038
| 4,560
|
"""Test UniFi Protect views."""
from datetime import datetime, timedelta
from typing import Any, cast
from unittest.mock import AsyncMock, Mock
from aiohttp import ClientResponse
import pytest
from pyunifiprotect.data import Camera, Event, EventType
from pyunifiprotect.exceptions import ClientError
from homeassistant.components.unifiprotect.views import (
async_generate_event_video_url,
async_generate_thumbnail_url,
)
from homeassistant.core import HomeAssistant
from .utils import MockUFPFixture, init_entry
from tests.typing import ClientSessionGenerator
async def test_thumbnail_bad_nvr_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid NVR ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock()
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_not_called
@pytest.mark.parametrize(("width", "height"), [("test", None), (None, "test")])
async def test_thumbnail_bad_params(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
width: Any,
height: Any,
) -> None:
"""Test invalid bad query parameters."""
ufp.api.get_event_thumbnail = AsyncMock()
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url(
"test_id", ufp.api.bootstrap.nvr.id, width=width, height=height
)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 400
ufp.api.get_event_thumbnail.assert_not_called
async def test_thumbnail_bad_event(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid with error raised."""
ufp.api.get_event_thumbnail = AsyncMock(side_effect=ClientError())
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail_no_data(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test invalid no thumbnail returned."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=None)
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test NVR ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=b"testtest")
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.api.bootstrap.nvr.id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 200
assert response.content_type == "image/jpeg"
assert await response.content.read() == b"testtest"
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_thumbnail_entry_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
) -> None:
"""Test config entry ID in URL."""
ufp.api.get_event_thumbnail = AsyncMock(return_value=b"testtest")
await init_entry(hass, ufp, [camera])
url = async_generate_thumbnail_url("test_id", ufp.entry.entry_id)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 200
assert response.content_type == "image/jpeg"
assert await response.content.read() == b"testtest"
ufp.api.get_event_thumbnail.assert_called_with("test_id", width=None, height=None)
async def test_video_bad_event(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad camera ID."""
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id="test_id",
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(ValueError):
async_generate_event_video_url(event)
async def test_video_bad_event_ongoing(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad camera ID."""
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=None,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(ValueError):
async_generate_event_video_url(event)
async def test_video_bad_perms(
hass: HomeAssistant,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test generating event with bad user permissions."""
ufp.api.bootstrap.auth_user.all_permissions = []
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
with pytest.raises(PermissionError):
async_generate_event_video_url(event)
async def test_video_bad_nvr_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad NVR id."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(ufp.api.bootstrap.nvr.id, "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called
async def test_video_bad_camera_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad camera id."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(camera.id, "bad_id")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_not_called
async def test_video_bad_camera_perms(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with bad camera perms."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event = Event(
api=ufp.api,
camera_id=camera.id,
start=fixed_now - timedelta(seconds=30),
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
ufp.api.bootstrap.auth_user.all_permissions = []
ufp.api.bootstrap.auth_user._perm_cache = {}
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 403
ufp.api.request.assert_not_called
@pytest.mark.parametrize(("start", "end"), [("test", None), (None, "test")])
async def test_video_bad_params(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
start: Any,
end: Any,
) -> None:
"""Test video URL with bad start/end params."""
ufp.api.request = AsyncMock()
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
from_value = event_start if start is not None else fixed_now
to_value = start if start is not None else end
url = url.replace(from_value.replace(microsecond=0).isoformat(), to_value)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 400
ufp.api.request.assert_not_called
async def test_video_bad_video(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
ufp.api.request = AsyncMock(side_effect=ClientError)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert response.status == 404
ufp.api.request.assert_called_once
async def test_video(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
content = Mock()
content.__anext__ = AsyncMock(side_effect=[b"test", b"test", StopAsyncIteration()])
content.__aiter__ = Mock(return_value=content)
mock_response = Mock()
mock_response.content_length = 8
mock_response.content.iter_chunked = Mock(return_value=content)
ufp.api.request = AsyncMock(return_value=mock_response)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert await response.content.read() == b"testtest"
assert response.status == 200
ufp.api.request.assert_called_once
async def test_video_entity_id(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
ufp: MockUFPFixture,
camera: Camera,
fixed_now: datetime,
) -> None:
"""Test video URL with no video."""
content = Mock()
content.__anext__ = AsyncMock(side_effect=[b"test", b"test", StopAsyncIteration()])
content.__aiter__ = Mock(return_value=content)
mock_response = Mock()
mock_response.content_length = 8
mock_response.content.iter_chunked = Mock(return_value=content)
ufp.api.request = AsyncMock(return_value=mock_response)
await init_entry(hass, ufp, [camera])
event_start = fixed_now - timedelta(seconds=30)
event = Event(
api=ufp.api,
camera_id=camera.id,
start=event_start,
end=fixed_now,
id="test_id",
type=EventType.MOTION,
score=100,
smart_detect_types=[],
smart_detect_event_ids=[],
)
url = async_generate_event_video_url(event)
url = url.replace(camera.id, "camera.test_camera_high")
http_client = await hass_client()
response = cast(ClientResponse, await http_client.get(url))
assert await response.content.read() == b"testtest"
assert response.status == 200
ufp.api.request.assert_called_once
| 6,744
|
https://github.com/mattmccloskey/inView/blob/master/example/example.js
|
Github Open Source
|
Open Source
|
MIT
| 2,016
|
inView
|
mattmccloskey
|
JavaScript
|
Code
| 18
| 103
|
$(function($){
// $(".box").on("inView", function(){
// console.log($(this).attr("id"), arguments);
// });
$(".box").on("inViewBegin", function(){
$(this).addClass("inView");
});
$(".box").on("inViewEnd", function(){
$(this).removeClass("inView");
});
});
| 41,832
|
https://github.com/drpicox/git-analysis-tools/blob/master/github-api/src/components/IssuesTable.js
|
Github Open Source
|
Open Source
|
MIT
| null |
git-analysis-tools
|
drpicox
|
JavaScript
|
Code
| 172
| 846
|
import React from "react";
import NavButton from "./NavButton";
import RefNum from "./RefNum";
import getIssueCommit from "../reporters/getIssueCommit";
import getIssueColumn from "../reporters/getIssueColumn";
import getIssueWeight from "../reporters/getIssueWeight";
import getIssueAuthor from "../reporters/getIssueAuthor";
import getIssueDeveloper from "../reporters/getIssueDeveloper";
import getIssueBodyScore from "../reporters/getIssueBodyScore";
import getIssuePullRequest from "../reporters/getIssuePullRequest";
import getIssueReview from "../reporters/getIssueReview";
import getIssueMergedBy from "../reporters/getIssueMergedBy";
import isIssueMerged from "../reporters/isIssueMerged";
import getIssueRejectionCount from "../reporters/getIssueRejectionCount";
import getIssueBodyEdit from "../reporters/getIssueBodyEdit";
const IssueRow = ({ issue, className }) => (
<tr className={className}>
<td>
<RefNum {...issue} />
</td>
<td>{getIssueWeight(issue)}</td>
<td>{getIssueAuthor(issue)}</td>
<td>{issue.title}</td>
<td>
<NavButton view={{ main: "markdown", ...getIssueBodyEdit(issue) }}>
{getIssueBodyScore(issue)}
</NavButton>
</td>
<td>
<RefNum {...getIssuePullRequest(issue)} />
</td>
<td>{getIssueDeveloper(issue)}</td>
<td>{isIssueMerged(issue) && "merged"}</td>
<td>{getIssueMergedBy(issue)}</td>
<td>{getIssueReview(issue).state}</td>
<td>{getIssueReview(issue).author}</td>
<td>{getIssueRejectionCount(issue)}</td>
<td>{getIssueColumn(issue)}</td>
<td>{getIssueCommit(issue)}</td>
</tr>
);
const IssueTable = ({ issues = [] }) => (
<table>
<thead>
<tr>
<td colSpan={5}>Issue</td>
<td colSpan={2}>PR</td>
<td colSpan={2}>Merge</td>
<td colSpan={3}>Review</td>
<td colSpan={2}>Other</td>
</tr>
<tr>
<td>#is</td>
<td>W</td>
<td>Column</td>
<td>Author</td>
<td>Title</td>
<td>Scre</td>
<td>#pr</td>
<td>Developer</td>
<td>Merged</td>
<td>Merged By</td>
<td>State</td>
<td>Reviewer</td>
<td>RC</td>
<td>Column</td>
<td>Commit</td>
</tr>
</thead>
<tbody>
{issues.map((issue, index) => (
<IssueRow
issue={issue}
key={issue.number}
className={index % 2 ? "odd" : "even"}
/>
))}
</tbody>
</table>
);
export default IssueTable;
| 38,453
|
https://github.com/fixiki-in-wave/pomogator/blob/master/.gitignore
|
Github Open Source
|
Open Source
|
MIT
| 2,021
|
pomogator
|
fixiki-in-wave
|
Ignore List
|
Code
| 3
| 18
|
node_modules
packages/**/*.map
packages/**/*.js
| 22,828
|
https://github.com/cpatrick/calatk/blob/master/Code/Libraries/ObjectiveFunctions/CAtlasSubiterationUpdateObjectiveFunction.h
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,012
|
calatk
|
cpatrick
|
C++
|
Code
| 355
| 956
|
/*
*
* Copyright 2011, 2012 by the CALATK development team
*
* 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.
*
*
*/
#ifndef C_ATLAS_SUBITERATION_UPDATE_OBJECTIVE_FUNCTION_H
#define C_ATLAS_SUBITERATION_UPDATE_OBJECTIVE_FUNCTION_H
#include "CObjectiveFunction.h"
#include "CVelocityFieldObjectiveFunctionWithMomentum.h"
#include "CALATKCommon.h"
#include "LDDMMUtils.h"
#include "VectorImageUtils.h"
#include "CAtlasObjectiveFunction.h"
namespace CALATK
{
template < class TState >
/**
* @brief Objective function for atlas-building. Makes use of a multistate and manages multiple individual objective functions.
*
*/
class CAtlasSubiterationUpdateObjectiveFunction
: public CAtlasObjectiveFunction< TState >
{
public:
/** Standard class typedefs. */
typedef CAtlasSubiterationUpdateObjectiveFunction Self;
typedef CAtlasObjectiveFunction< TState > Superclass;
typedef itk::SmartPointer< Self > Pointer;
typedef itk::SmartPointer< const Self > ConstPointer;
/* Some useful typedefs */
typedef typename TState::FloatType FloatType;
typedef typename TState::IndividualStateType IndividualStateType;
typedef CAtlasSubiterationUpdateObjectiveFunction< TState > ObjectiveFunctionType;
typedef CVelocityFieldObjectiveFunctionWithMomentum< IndividualStateType > IndividualObjectiveFunctionType;
typedef LDDMMUtils< FloatType, TState::ImageDimension > LDDMMUtilsType;
typedef VectorImageUtils< FloatType, TState::ImageDimension > VectorImageUtilsType;
typedef typename Superclass::CEnergyValues CEnergyValues;
typedef typename Superclass::VectorIndividualObjectiveFunctionPointersType VectorIndividualObjectiveFunctionPointersType;
typedef typename Superclass::VectorImageType VectorImageType;
typedef typename Superclass::VectorFieldType VectorFieldType;
CAtlasSubiterationUpdateObjectiveFunction();
virtual ~CAtlasSubiterationUpdateObjectiveFunction();
void ComputeGradient();
/**
* @brief Assumes that the atlas image is the source image and updates it by a weighted average of the target images pulled back to the source
*
*/
void UpdateAtlasImageAsAverageOfTargetImages();
/**
* @brief Assumes that the atlas image is the target image and updates it by flowing the source images forward and averaging them.
*
*/
void UpdateAtlasImageAsAverageOfSourceImages();
// TODO: needs to be implemented
void GetSourceImage( VectorImageType* ptrIm );
void PreSubIterationSolve();
virtual void SetAutoConfiguration( CJSONConfiguration * combined, CJSONConfiguration * cleaned );
protected:
void InitializeState();
void InitializeState( TState * ptrState );
private:
// intentionally not implemented
CAtlasSubiterationUpdateObjectiveFunction( const CAtlasSubiterationUpdateObjectiveFunction & );
CAtlasSubiterationUpdateObjectiveFunction& operator=( const CAtlasSubiterationUpdateObjectiveFunction & );
};
#include "CAtlasSubiterationUpdateObjectiveFunction.txx"
} // end namespace
#endif // C_ATLAS_SUBITERATION_UPDATE_OBJECTIVE_FUNCTION_H
| 18,862
|
https://github.com/alipay/alipay-sdk-java-all/blob/master/v2/src/main/java/com/alipay/api/domain/DeviceApplyOrderDeviceModel.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,023
|
alipay-sdk-java-all
|
alipay
|
Java
|
Code
| 106
| 381
|
package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 设备申请单所关联的设备model
*
* @author auto create
* @since 1.0, 2019-08-21 12:16:28
*/
public class DeviceApplyOrderDeviceModel extends AlipayObject {
private static final long serialVersionUID = 3355875446831792136L;
/**
* 设备sn编号
*/
@ApiField("device_sn")
private String deviceSn;
/**
* itemId
*/
@ApiField("item_id")
private String itemId;
/**
* 厂商id
*/
@ApiField("supplier_id")
private String supplierId;
public String getDeviceSn() {
return this.deviceSn;
}
public void setDeviceSn(String deviceSn) {
this.deviceSn = deviceSn;
}
public String getItemId() {
return this.itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
public String getSupplierId() {
return this.supplierId;
}
public void setSupplierId(String supplierId) {
this.supplierId = supplierId;
}
}
| 40,879
|
https://github.com/SWP-Ubau-SoSe2014-Haskell/SWPSoSe14/blob/master/x-testing/neg_revisitDollar1.io
|
Github Open Source
|
Open Source
|
MIT
| 2,015
|
SWPSoSe14
|
SWP-Ubau-SoSe2014-Haskell
|
Io
|
Code
| 7
| 17
|
$0
---
#
%
RailCompiler: Invalid movement.
| 5,882
|
https://github.com/madosuki/script-collection-in-common-lisp/blob/master/combination.lisp
|
Github Open Source
|
Open Source
|
LicenseRef-scancode-public-domain
| 2,021
|
script-collection-in-common-lisp
|
madosuki
|
Common Lisp
|
Code
| 43
| 97
|
(defun fact (x &optional (y 1))
(if (<= x 1)
y
(fact (- x 1) (* x y))))
(defun combination (l r)
(if (or (< l 1) (< r 1))
nil
(let ((numerator (fact l))
(denominator (fact (- l r))))
(/ numerator denominator))))
| 35,454
|
https://github.com/isabella232/airavata-data-lake/blob/master/data-resource-management-service/drms-api/src/main/java/org/apache/airavata/drms/api/Client.java
|
Github Open Source
|
Open Source
|
Apache-2.0
| 2,021
|
airavata-data-lake
|
isabella232
|
Java
|
Code
| 713
| 3,571
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.airavata.drms.api;
import com.google.protobuf.Struct;
import com.google.protobuf.util.JsonFormat;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.apache.airavata.datalake.drms.DRMSServiceAuthToken;
import org.apache.airavata.datalake.drms.resource.GenericResource;
import org.apache.airavata.datalake.drms.storage.*;
import org.apache.airavata.datalake.drms.storage.ssh.SSHStorage;
import org.apache.custos.clients.CustosClientProvider;
import org.apache.custos.identity.management.client.IdentityManagementClient;
import org.json.JSONObject;
import org.json.JSONTokener;
import java.io.FileInputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.UUID;
public class Client {
public static void main(String ar[]) {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 7070).usePlaintext().build();
// ResourceServiceGrpc.ResourceServiceBlockingStub resourceClient = ResourceServiceGrpc.newBlockingStub(channel);
//
// DRMSServiceAuthToken authToken = DRMSServiceAuthToken.newBuilder().
// setAccessToken()
// .build();
// ResourceSearchRequest request = ResourceSearchRequest.newBuilder().setAuthToken(authToken).build();
StorageServiceGrpc.StorageServiceBlockingStub resourceClient = StorageServiceGrpc.newBlockingStub(channel);
String token = getAccessToken();
DRMSServiceAuthToken authToken = DRMSServiceAuthToken.newBuilder().
setAccessToken(token).build();
// StorageCreateRequest request = StorageCreateRequest.newBuilder().setAuthToken(authToken).
// setStorage(AnyStorage.newBuilder().setSshStorage(SSHStorage.newBuilder()
// .setStorageId("testing.com")
// .setHostName("localhost")
// .setPort(3565)
// .build())
// .build()).
// build();
// resourceClient.createStorage(request);
StorageSearchRequest storageSearchRequest = StorageSearchRequest
.newBuilder()
.setAuthToken(authToken)
.addQueries(StorageSearchQuery.newBuilder()
.setField("type")
.setValue("COLLECTION")
.build())
.build();
// resourceClient.searchStorage(storageSearchRequest);
StoragePreferenceServiceGrpc.StoragePreferenceServiceBlockingStub storagePreferenceServiceBlockingStub = StoragePreferenceServiceGrpc
.newBlockingStub(channel);
// StoragePreferenceSearchRequest storagePreferenceSearchRequest = StoragePreferenceSearchRequest
// .newBuilder()
// .setAuthToken(authToken)
// .addQueries(StoragePreferenceSearchQuery.newBuilder().build()).build();
// storagePreferenceServiceBlockingStub.searchStoragePreference(storagePreferenceSearchRequest);
// StoragePreferenceFetchRequest storagePreferenceSearchRequest = StoragePreferenceFetchRequest
// .newBuilder()
// .setAuthToken(authToken)
// .setStoragePreferenceId("storage-preference-id-one")
// .build();
// StoragePreferenceFetchResponse response = storagePreferenceServiceBlockingStub
// .fetchStoragePreference(storagePreferenceSearchRequest);
// System.out.println(response.getStoragePreference().getSshStoragePreference().getUserName());
// StoragePreferenceCreateRequest storagePreferenceCreateRequest = StoragePreferenceCreateRequest
// .newBuilder()
// .setAuthToken(authToken)
// .setStoragePreference(AnyStoragePreference.newBuilder()
// .setSshStoragePreference(SSHStoragePreference.newBuilder()
// .setStorage(SSHStorage
// .newBuilder()
// .setStorageId("test-storage-id-two")
// .setHostName("localhost")
// .setPort(3545).build()
// )
// .setStoragePreferenceId("storage-preference-id-two")
// .setUserName("test")
// .setCredentialToken("cred-token-3457-okmlp")
// .build())).build();
//
// storagePreferenceServiceBlockingStub.createStoragePreference(storagePreferenceCreateRequest);
TransferMapping transferMapping = TransferMapping.newBuilder()
.setUserId("isjarana@iu.edu")
.setTransferScope(TransferScope.GLOBAL)
.setSourceStorage(AnyStorage
.newBuilder()
.setSshStorage(SSHStorage.newBuilder().setStorageId("testing.com")
.build())
.build())
.setDestinationStorage(AnyStorage
.newBuilder()
.setSshStorage(SSHStorage.newBuilder().setStorageId("qwerft-rftgyhu-oplmnj")
.build())
.build())
.build();
//
CreateTransferMappingRequest request = CreateTransferMappingRequest.newBuilder()
.setAuthToken(authToken)
.setTransferMapping(transferMapping)
.build();
// resourceClient.createTransferMapping(request);
//
FindTransferMappingsRequest findTransferMappingsRequest = FindTransferMappingsRequest.newBuilder()
.setAuthToken(authToken)
.build();
// resourceClient.getTransferMappings(findTransferMappingsRequest);
//
DeleteTransferMappingRequest transferMappingRequest = DeleteTransferMappingRequest.newBuilder()
.setAuthToken(authToken)
.setId("testing.com_qwerft-rftgyhu-oplmnj")
.build();
resourceClient.deleteTransferMappings(transferMappingRequest);
// storagePreferenceServiceBlockingStub.deleteTransferMappings(transferMappingRequest);
// storagePreferenceServiceBlockingStub.createTransferMapping(request);
ResourceServiceGrpc.ResourceServiceBlockingStub resourceServiceBlockingStub = ResourceServiceGrpc.newBlockingStub(channel);
// ResourceSearchQuery query = ResourceSearchQuery.newBuilder().setField("type").setValue("COLLECTION").build();
//
// ResourceSearchRequest request = ResourceSearchRequest
// .newBuilder()
// .setAuthToken(authToken)
// .addQueries(query).build();
//
// ResourceSearchResponse response = resourceServiceBlockingStub.searchResource(request);
// response.getResourcesList();
// ChildResourceFetchRequest childResourceFetchRequest = ChildResourceFetchRequest
// .newBuilder()
// .setAuthToken(authToken)
// .setResourceId("COLLECTION_TWO_a1qeBCVSrpx8vLJ")
// .setDepth(1)
// .setType("COLLECTION")
// .build();
//
// resourceServiceBlockingStub.fetchChildResources(childResourceFetchRequest);
String id = UUID.randomUUID().toString();
GenericResource genericResource = GenericResource
.newBuilder()
.setResourceId(id)
.setType("COLLECTION")
.setResourceName("COLLECTION_SDK_TEST_TWO")
.build();
// DRMSServiceAuthToken drmsServiceAuthToken = DRMSServiceAuthToken.newBuilder()
// .setAccessToken(getServiceAccountToken())
// .setAuthenticatedUser(AuthenticatedUser.newBuilder().setUsername("isjarana@iu.edu")
// .setTenantId("custos-whedmgamitu357p4wuke-10002708"))
// .setAuthCredentialType(AuthCredentialType.AGENT_ACCOUNT_CREDENTIAL)
// .build();
// ResourceCreateRequest resourceCreateRequest = ResourceCreateRequest.newBuilder()
// .setAuthToken(authToken)
// .setResource(genericResource)
// .build();
// resourceServiceBlockingStub.createResource(resourceCreateRequest);
// System.out.println(authToken.getAccessToken());
// ResourceFetchRequest resourceFetchRequest = ResourceFetchRequest.newBuilder()
// .setAuthToken(authToken)
// .setResourceId("custos-whedmgamitu357p4wuke-10002708_29186.69999998808")
// .build();
//
// resourceServiceBlockingStub.fetchResource(resourceFetchRequest);
//
// GenericResource parentResource = GenericResource.newBuilder()
// .setResourceId("56cec8a2-a2c2-4669-9274-a5b5bdd97c11")
// .setType("COLLECTION")
// .build();
//
// GenericResource childResource = GenericResource.newBuilder()
// .setResourceId("b75b4cec-8df4-4f99-9d06-818db285cf02")
// .setType("COLLECTION")
// .build();
//
// GenericResource childResource1 = GenericResource.newBuilder()
// .setResourceId("b7ee2fd5-c4b8-4bb9-896b-4cb98d91ad24")
// .setType("COLLECTION")
// .build();
//
// List<GenericResource> genericResourceList = new ArrayList<>();
// genericResourceList.add(childResource);
// genericResourceList.add(childResource1);
// AddChildResourcesMembershipRequest addChildResourcesMembershipRequest = AddChildResourcesMembershipRequest
// .newBuilder()
// .setParentResource(parentResource)
// .addAllChildResources(genericResourceList)
// .setAuthToken(authToken)
// .build();
// resourceServiceBlockingStub.addChildMembership(addChildResourcesMembershipRequest);
// DeleteChildResourcesMembershipRequest deleteChildResourcesMembershipRequest = DeleteChildResourcesMembershipRequest
// .newBuilder()
// .setParentResource(parentResource)
// .addAllChildResources(genericResourceList)
// .setAuthToken(authToken)
// .build();
// resourceServiceBlockingStub.deleteChildMembership(deleteChildResourcesMembershipRequest);
// ParentResourcesFetchRequest parentResourcesFetchRequest = ParentResourcesFetchRequest
// .newBuilder()
// .setAuthToken(authToken)
// .setResourceId("FILE_ONE_bxZPopxbnPaAEq5")
// .setType("FILE")
// .setDepth(2)
// .build();
// resourceServiceBlockingStub.fetchParentResources(parentResourcesFetchRequest);
try {
FileInputStream fileInputStream =
new FileInputStream(
"/Users/isururanawaka/Documents/Airavata_Repository/airavata-data-lake" +
"/data-resource-management-service/drms-api/src/main/resources/sample.json");
JSONTokener tokener = new JSONTokener(fileInputStream);
JSONObject root = new JSONObject(tokener);
//
Struct.Builder structBuilder = Struct.newBuilder();
JsonFormat.parser().merge(root.toString(), structBuilder);
// AddResourceMetadataRequest addResourceMetadataRequest = AddResourceMetadataRequest
// .newBuilder()
// .setMetadata(structBuilder.build())
// .setAuthToken(authToken)
// .setResourceId("custos-whedmgamitu357p4wuke-10002708_132068.39999997616")
// .setType("FILE")
// .build();
//
// resourceServiceBlockingStub.addResourceMetadata(addResourceMetadataRequest);
// FetchResourceMetadataRequest addResourceMetadataRequest = FetchResourceMetadataRequest
// .newBuilder()
// .setAuthToken(authToken)
// .setResourceId("custos-whedmgamitu357p4wuke-10002708_132068.39999997616")
// .setType("FILE")
// .build();
//
// resourceServiceBlockingStub.fetchResourceMetadata(addResourceMetadataRequest);
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getAccessToken() {
try {
CustosClientProvider custosClientProvider = new CustosClientProvider.Builder().setServerHost("custos.scigap.org")
.setServerPort(31499)
.setClientId("custos-whedmgamitu357p4wuke-10002708")
.setClientSec("mrMdl86Ia1H94cikW7CvHoh7L0ASNXQVt2aRzSIj").build();
IdentityManagementClient identityManagementClient = custosClientProvider.getIdentityManagementClient();
Struct struct = identityManagementClient.getToken(null, null, "isjarana@iu.edu", "IJR@circ@1", null, "password");
return struct.getFieldsMap().get("access_token").getStringValue();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static String getServiceAccountToken() {
try {
return Base64.getEncoder().encodeToString(("file-listener-service-account" + ":" + "yyvQs3bKk2xp6W9YwuRQO3PvZrXruwRh0e0nR5kR")
.getBytes(StandardCharsets.UTF_8));
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
}
| 48,576
|
https://github.com/BitYog/emmet/blob/master/lib/assets/tokenIterator.js
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
emmet
|
BitYog
|
JavaScript
|
Code
| 203
| 612
|
/**
* Helper class for convenient token iteration
*/
if (typeof module === 'object' && typeof define !== 'function') {
var define = function (factory) {
module.exports = factory(require, exports, module);
};
}
define(function(require, exports, module) {
/**
* @type TokenIterator
* @param {Array} tokens
* @type TokenIterator
* @constructor
*/
function TokenIterator(tokens) {
/** @type Array */
this.tokens = tokens;
this._position = 0;
this.reset();
}
TokenIterator.prototype = {
next: function() {
if (this.hasNext()) {
var token = this.tokens[++this._i];
this._position = token.start;
return token;
} else {
this._i = this._il;
}
return null;
},
current: function() {
return this.tokens[this._i];
},
peek: function() {
return this.tokens[this._i + i];
},
position: function() {
return this._position;
},
hasNext: function() {
return this._i < this._il - 1;
},
reset: function() {
this._i = 0;
this._il = this.tokens.length;
},
item: function() {
return this.tokens[this._i];
},
itemNext: function() {
return this.tokens[this._i + 1];
},
itemPrev: function() {
return this.tokens[this._i - 1];
},
nextUntil: function(type, callback) {
var token;
var test = typeof type == 'string'
? function(t){return t.type == type;}
: type;
while ((token = this.next())) {
if (callback)
callback.call(this, token);
if (test.call(this, token))
break;
}
}
};
return {
create: function(tokens) {
return new TokenIterator(tokens);
}
};
});
| 33,648
|
https://github.com/ganboing/pintool/blob/master/source/tools/ToolUnitTests/memalign.cpp
|
Github Open Source
|
Open Source
|
Intel
| 2,017
|
pintool
|
ganboing
|
C++
|
Code
| 635
| 1,317
|
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2016 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
/*
* This test verifies that the memalign() function returns correctly aligned pointers. It also
* verifies that the memory returned by memalign() can be freed by Pin's free() function.
*/
#include <iostream>
#include <vector>
#include <stdlib.h>
#include "pin.H"
extern "C" void *memalign(size_t, size_t);
static BOOL TestAlign(size_t, size_t);
typedef std::vector<void *> POINTER_CONTAINER;
POINTER_CONTAINER Pointers;
int main(int argc, char * argv[])
{
PIN_Init(argc, argv);
// Test alignment of "small chunks"
for (int i = 0; i < 10; i++)
{
for (size_t align = 1; align <= 8192; align <<= 1)
{
if (!TestAlign(align, 4))
return 1;
}
}
// Test alignment of "big chunks" that are larger than 1 page but smaller than 2 pages
for (int i = 0; i < 10; i++)
{
for (size_t align = 1; align <= 8192; align <<= 1)
{
if (!TestAlign(align, 1700))
return 1;
}
}
// Pointers.clear();
// Test alignment of "big chunks" larger than one page in size and alignment larger than one page
for (int i = 0; i < 10; i++)
{
for (size_t align = 1024; align < 16*1024; align <<= 1)
{
if (!TestAlign(align, (i+1)*100000))
return 1;
}
}
for (POINTER_CONTAINER::iterator it = Pointers.begin(); it != Pointers.end(); ++it)
free(*it);
// Test realloc to larger and smaller sizes
void * ptr = malloc(20);
if (ptr == NULL)
{
std::cerr << "Malloc failed\n";
exit(-1);
}
std::cerr << "Malloc : " << hex << ptr << dec << std::endl;
void * tmp = realloc(ptr, 21000);
if (tmp == NULL)
{
std::cerr << "Realloc to larger size failed\n";
exit(-1);
}
ptr = tmp;
std::cerr << "Realloc to larger size : " << hex << ptr << dec << std::endl;
tmp = realloc(ptr, 500);
if (tmp == NULL)
{
std::cerr << "Realloc to smaller size failed\n";
exit(-1);
}
ptr = tmp;
std::cerr << "Realloc to smaller size : " << hex << ptr << dec << std::endl;
free(ptr);
// Never returns
PIN_StartProgram();
return 0;
}
static BOOL TestAlign(size_t align, size_t size)
{
void *p = memalign(align, size);
if (!p)
{
std::cerr << "Returned NULL for alignment " << align << std::endl;
return FALSE;
}
Pointers.push_back(p);
ADDRINT addr = reinterpret_cast<ADDRINT>(p);
if (addr & (align-1))
{
std::cerr << "Incorrect alignment for " << align << " (p=" << p << ")" << std::endl;
return FALSE;
}
std::cout << "Alignment " << align << " : Size : " << size << " " << p << std::endl;
return TRUE;
}
| 9,636
|
https://github.com/benzkji/django-separate-users/blob/master/separate_users/tests/test_permissions.py
|
Github Open Source
|
Open Source
|
MIT
| 2,022
|
django-separate-users
|
benzkji
|
Python
|
Code
| 109
| 394
|
# -*- coding: utf-8 -*-
from django.contrib.auth.models import Permission
# from django.test import Client
from django.test import TestCase
# compat
import django
if django.VERSION[:2] < (1, 10):
from django.core.urlresolvers import reverse
else:
from django.urls import reverse
class PermissionsTestCase(TestCase):
"""
check if permissions are there, after management command was run.
"""
def setUp(self):
pass
def tearDown(self):
pass
def test_no_permissions_initially(self):
"""
check if not there initially - this will fail if django fixes the bug! nice to know.
"""
self.assertEqual(self.permission_count('separate_users', 'add_frontenduser'), 0)
self.assertEqual(self.permission_count('separate_users', 'add_editor'), 0)
def test_permission_management_command(self):
from django.core.management import call_command
call_command('fix_proxy_permissions', )
self.assertEqual(self.permission_count('separate_users', 'add_frontenduser'), 1)
self.assertEqual(self.permission_count('separate_users', 'add_editor'), 1)
def permission_count(self, app_label, codename):
count = Permission.objects.filter(
content_type__app_label=app_label,
codename=codename,
).count()
return count
| 45,972
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.