Sunday, April 2, 2017

Displaying Youtube within an Ionic 2 app

Leave a Comment

I am trying to display Youtube videos within an Ionic 2 application, with the URLs pulled in from a JSON data feed.

Individual videos can be displayed when the Youtube url is set in the constructor on the detail page, but I need the detail page to display videos for each of the videos in the JSON feed.

Here is how an individual Youtube video is able to display in Ionic 2 within detail.ts and detail.html:

1

import {SafeResourceUrl, DomSanitizer} from '@angular/platform-browser'; 

2

videoUrl: SafeResourceUrl;  constructor(private domSanitizer: DomSanitizer, public navCtrl: NavController) { this.videoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/DuwXCFyo4-w') } 

3

<iframe width="100%" height="315" [src]="data.youtube" frameborder="0" allowfullscreen></iframe> 

ios tweak

<allow-navigation href="https://*youtube.com/*"/> 

What I need is some code tweaking in detail.ts to allow any Youtube url?

Here is the Youtube displayed in a Plunker on the detail page http://plnkr.co/edit/Ar2whVFCmBAbE7fxA3nf?p=preview

enter image description here

One solution I have seen is below, but can't seem to get it working:

transform(videoId: string): SafeResourceUrl { return this.domSanitizer.bypassSecurityTrustResourceUrl( https://www.youtube.com/embed/${videoId}); } 

1 Answers

Answers 1

You are doing it wrong. You shouldn't be using embedded youtube frames on your ionic app.

You must use the Ionic Youtube Plugin

To install it, go to your Ionic project in the command line:

ionic plugin add https://github.com/Glitchbone/CordovaYoutubeVideoPlayer.git npm install --save @ionic-native/youtube-video-player 

Basic Usage:

import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';  constructor(private youtube: YoutubeVideoPlayer) { }  this.youtube.openVideo('myvideoid'); 

Of course 'myvideoid' is your youtube video ID passed as a string.

Read More

ANDROID: email client receiver email id empty in android-parse

Leave a Comment

I'm using android- parse server in app. below is parse db screenshot of email column . the email column is after the hidden password column in database .

parse database screenshot

my problem is


when i retrieve email ids to email client, email is null even if the email column has emails .


note : in the app in another place (another table) i'm pulling email ids to email client in same manner, but there mail is showing well .. only here the problem occurs.

if anyone knows please help ?

this is email column in parse database

 try{                         JSONObject jsonObject = parseObjectToJson(object);                         Log.d("Object", jsonObject.toString());                         Log.d("Email", "+" + object.get("email"));                         personNumber = jsonObject.getString("telephone");                         personEmail = jsonObject.getString("email");                     }catch (JSONException je){                      }catch (ParseException pe){                      } 

this is email button

  emailPerson = (Button)findViewById(R.id.individualEmail);             emailPerson.setOnClickListener(new View.OnClickListener() {                 @Override                 public void onClick(View v) {                     Intent i = new Intent(Intent.ACTION_SEND);                     i.setData(Uri.parse("mailto:"));                     i.setType("plain/text");                     i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] {personEmail});                     startActivity(i);                 }             });             if(personEmail==null || personEmail.equals("")  || personEmail.equals(" ")){                 emailPerson.setClickable(false);                 emailPerson.setEnabled(false);                 emailPerson.setVisibility(View.GONE);             }             else{                 emailPerson.setEnabled(true);                 emailPerson.setClickable(true);                 emailPerson.setVisibility(View.VISIBLE);             } 

here it is working fine but this is a different table in same database . >in this table there is no hidden password field

try{                             corporateEmail = jsonObject.getString("email");                             if(corporateEmail == null || corporateEmail.equals("")){                                 emailCorporate.setVisibility(View.GONE);                                 emailCorporate.setEnabled(false);                                 emailCorporate.setClickable(false);                             } 

emailCorporate = (Button) findViewById(R.id.corporateEmail);         emailCorporate.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View v) {                 Intent i = new Intent(Intent.ACTION_SEND);                 i.setData(Uri.parse("mailto:"));                 i.setType("plain/text");                 i.putExtra(Intent.EXTRA_EMAIL, new String[] {corporateEmail});                 startActivity(i);             }         }); 

 private JSONObject parseObjectToJson(ParseObject parseObject) throws ParseException, JSONException, com.parse.ParseException {         JSONObject jsonObject = new JSONObject();         parseObject.fetchIfNeeded();         Set<String> keys = parseObject.keySet();         for (String key : keys) {             Object objectValue = parseObject.get(key);             if (objectValue instanceof ParseObject) {                 jsonObject.put(key, parseObjectToJson(parseObject.getParseObject(key)));             } else if (objectValue instanceof ParseRelation) {             } else {                 jsonObject.put(key, objectValue.toString());             }         }         return jsonObject;     } 

1 Answers

Answers 1

if jsonObject is not null check to see if the parse database you are pulling your data from has the the "email" tag

Read More

Three.js Scene Switching Performance Issue

Leave a Comment

I have created a game in three.js which exists of 3 scenes the GameScene, MenuScene and the HighScoreScene. The user can switch between those scenes - When the player is changing the Scene e.g. from the MenuScene to the HighScoreScene I'm trying to clean up the resources from the old Scene.

But cleaning up the resources seems not to work. So here is my code which is getting executed when the user is switching between scenes:

So in the old Scene I have this animation loop:

 function cancelAnimation() {     cancelAnimationFrame(animationFrameId); // EXECUTING WHEN SWITCHING SCENE!!!  }  function animate() {     animationFrameId = requestAnimationFrame(animate); // Saving id     render(); }  function render() {     renderer.clear();     renderer.render(scene, camera); } 

So when switching the scene I unset all click listeners and I'm calling cancelAnimation.

Because I'm storing that code for each Scene in an object like var menuScene = new MenuScene() I'm also doing this menuScene = undefined when switching the scene.

I'm also passing the same instance of var renderer = new THREE.WebGLRenderer(); to the scenes.

This all seems not to help the game is executing more slowly.

What is the proper way to switch between those scenes and clearing up the resources? What am I doing wrong here?

0 Answers

Read More

Saturday, April 1, 2017

Declaration file for class-module (TypeScript)

Leave a Comment

I use a node module that's not found by typings and doesn't exist in definelytyped.

the basic use of the module is:

import * as SomeClass from 'some-module';  var someObject = new SomeClass("some string"); someObject.someMethod(); 

As you can see, this module exports a class as its default. I haven't figured out how to write the declaration file for it.

This is the best I managed to do:

declare module 'some-module' {     export default class SomeClass {         constructor (someArg: string);         someMethod(): void;     } } 

BTW it does work JavaScriptly. It's only the TypeScript bothers me.

Any ideas how to solve that?

2 Answers

Answers 1

For the declaration, you need to do this:

declare module 'some-module' {     class SomeClass {         constructor (someArg: string);         someMethod(): void;     }     export = SomeClass; } 

But I'll add more to this answer if you are tranpiling to ES5 (the right way).

Answers 2

If you just want to avoid TypeScript error and do not worry about ItelliSense just declare your class library like that in the begining of you file for example:

declare var SomeClass: any; 
Read More

How can I create a DataFrame slice object piece by piece?

Leave a Comment

I have a DataFrame, and I want to select certain rows and columns from it. I know how to do this using loc. However, I want to be able to specify each criteria individually, rather than in one go.

import numpy as np import pandas as pd idx = pd.IndexSlice  index = [np.array(['foo', 'foo', 'qux', 'qux']),          np.array(['a', 'b', 'a', 'b'])] columns = ["A",  "B"] df = pd.DataFrame(np.random.randn(4, 2), index=index, columns=columns) print df print df.loc[idx['foo', :], idx['A':'B']]                A         B foo a  0.676649 -1.638399     b -0.417915  0.587260 qux a  0.294555 -0.573041     b  1.592056  0.237868                 A         B foo a -0.470195 -0.455713     b  1.750171 -0.409216 

Requirement

I want to be able to achieve the same result with something like the following bit of code, where I specify each criteria one by one. It's also important that I'm able to use a slice_list to allow dynamic behaviour [i.e. the syntax should work whether there are two, three or ten different criteria in the slice_list].

slice_1 = 'foo' slice_2 = ':' slice_list = [slice_1, slice_2]  column_slice = "'A':'B'" print df.loc[idx[slice_list], idx[column_slice]] 

2 Answers

Answers 1

You can achieve this using the slice built-in function. You can't build slices with strings as ':' is a literal character and not a syntatical one.

slice_1 = 'foo' slice_2 = slice(None) column_slice = slice('A', 'B') df.loc[idx[slice_1, slice_2], idx[column_slice]] 

Answers 2

You might have to build your "slice lists" a little differently than you intended, but here's a relatively compact method using df.merge() and df.ix[]:

# Build a "query" dataframe slice_df = pd.DataFrame(index=[['foo','qux','qux'],['a','a','b']]) # Explicitly name columns column_slice = ['A','B']  slice_df.merge(df, left_index=True, right_index=True, how='inner').ix[:,column_slice]  Out[]:                A         B foo a  0.442302 -0.949298 qux a  0.425645 -0.233174     b -0.041416  0.229281 

This method also requires you to be explicit about your second index and columns, unfortunately. But computers are great at making long tedious lists for you if you ask nicely.

Read More

RecyclerView Items are not changing

Leave a Comment

I have a RecyclerView in a fragment which is repeating in TabLayout. I am having the problem of unchanged view in RecyclerView. I have a spinner on each tab. I want to change the data when spinner items get selected.

My cases:

  1. when switching between tabs - items changed
  2. when selecting another value in the spinner in the first tab -items not changed. (but data is changing in adapter class.Ie. First, it is not null then null during selection. But the first not nulled data is not appearing, its replacing with null. Found it using breakpoints).

    Note: In this case, when switching the tab, the items get changed to the spinner selected items in the previous tab. And then it disappears and displaying the current items in the tab.

  3. when selecting another value in the spinner in the last tab -items changed.

My view pager adapter class


public class StudentViewPagerAdapter extends FragmentStatePagerAdapter {     private final List<StudentList> mFragmentList = new ArrayList<>();     private final List<Clazz> mFragmentTitleList = new ArrayList<>();     public StudentViewPagerAdapter(FragmentManager fm) {         super(fm);     }     public void addFragment(StudentList fragment,Clazz clazz){         mFragmentList.add(fragment);         mFragmentTitleList.add(clazz);     }     @Override     public Fragment getItem(int position) {         return mFragmentList.get(position).newInstance(mFragmentTitleList.get(position));     }      @Override     public int getCount() {         return mFragmentList.size();     }      @Override     public CharSequence getPageTitle(int position) {         return mFragmentTitleList.get(position).getName();     } } 

my RecyclerView adapter class

public class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.MyViewHolder> implements View.OnClickListener {     private List<Student> dataList;     private Context context;     private Clicker clicker;     public PeopleAdapter(List<Student> data, Context context, Clicker clicker) {         this.dataList = data;         this.context = context;         this.clicker = clicker;     }      @Override     public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {         View itemView = LayoutInflater.from(parent.getContext())                 .inflate(R.layout.people_list_item, parent, false);          return new MyViewHolder(itemView);     }      @Override     public void onBindViewHolder(MyViewHolder holder, int position) {         Student data=dataList.get(position);         holder.email.setText(data.getEmail());         holder.name.setText(data.getName());         holder.phone.setText(data.getPhone());         Glide.with(context).load(Method.getImageUrl(MyConfiguration.STUDENT_IMAGE_URL,                 data.getStudentId())).asBitmap().into(holder.profilePic);         holder.edit.setOnClickListener(this);         holder.edit.setTag(position);     }      @Override     public int getItemCount() {         return dataList.size();     }      @Override     public void onClick(View v) {         clicker.OnItemClicked((int) v.getTag(),null);     }       static class MyViewHolder extends RecyclerView.ViewHolder {     @BindView(R.id.name)         TextView name;         @BindView(R.id.email)         TextView email;         @BindView(R.id.phone)         TextView phone;         @BindView(R.id.image)         ImageView profilePic;         @BindView(R.id.imageedit)         ImageView edit;     MyViewHolder(View view) {         super(view);         ButterKnife.bind(this,view);     } }  } 

tab fragments

    public class StudentList extends Fragment implements SectionChanger {         @BindView(R.id.studentlist)         RecyclerView mRecyclerview;         CompositeDisposable disposable;         private Unbinder unbinder;         private Clazz clazz;         private Requester requester;          public StudentList() {             StudentInformation.bindSectionChangeListener(this);         }         public static StudentList newInstance(Clazz clazz) {             StudentList fragment=new StudentList();             Bundle args = new Bundle();             args.putSerializable(MyConfiguration.SECTIONS, clazz);             fragment.setArguments(args);             return fragment;         }         @Override         public void onDestroyView() {             super.onDestroyView();             unbinder.unbind();             disposable.clear();         }          @Override         public View onCreateView(LayoutInflater inflater, ViewGroup container,                                  Bundle savedInstanceState) {             // Inflate the layout for this fragment             View view = inflater.inflate(R.layout.fragment_student_list, container, false);             unbinder = ButterKnife.bind(this, view);             LinearLayoutManager mLayoutManager = new LinearLayoutManager(getActivity());             mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);             mRecyclerview.setLayoutManager(mLayoutManager);             initializeRetrofit();             if (getArguments() != null) {                 clazz = (Clazz) getArguments().getSerializable(MyConfiguration.SECTIONS);                 loadStudentJson(clazz != null ? clazz.getClassId() : null,                         clazz != null ? clazz.getSections().get(0).getSectionId() : null);             }             return view;         }          /**          * Load students list          */         public void loadStudentJson(String class_id,String section_id) {               disposable = new CompositeDisposable(requester.getStudentsInSection(class_id,section_id)                     .observeOn(AndroidSchedulers.mainThread())                     .subscribeOn(Schedulers.io())                     .subscribe(                             this::handleResponse,                             this::handleError                     )             );         }          private void handleResponse(List<Student> list) {             PeopleAdapter adapter=new PeopleAdapter(list, getActivity(),                     (position, name) -> Toast.makeText(getActivity(), position, Toast.LENGTH_LONG).show());             mRecyclerview.setAdapter(adapter);             adapter.notifyDataSetChanged();         }          private void handleError(Throwable error) {             Toast.makeText(getActivity(), "Error " + error.getLocalizedMessage(), Toast.LENGTH_SHORT).show();         }          @Override         public void ChangeData(Section section) {             loadStudentJson(section.getClassId(),section.getSectionId());         }         public void initializeRetrofit(){             HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();             interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);             CookieHandler handler=new Cookies(getActivity());             //ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));             OkHttpClient client = new OkHttpClient.Builder()                     .addInterceptor(interceptor)                     .cookieJar(new JavaNetCookieJar(handler))                     .build();              requester = new Retrofit.Builder()                     .baseUrl(MyConfiguration.BASE_URL)                     .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                     .addConverterFactory(JacksonConverterFactory.create())                     .client(client)                     .build().create(Requester.class);         }     } 

Viewpager setup fragment

public class StudentInformation extends Fragment implements TabLayout.OnTabSelectedListener, AdapterView.OnItemSelectedListener {     // TODO: Rename parameter arguments, choose names that match     // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER     private static final String ARG_PARAM1 = "param1";     private static final String ARG_PARAM2 = "param2";     private Unbinder unbinder;     // TODO: Rename and change types of parameters     private String mParam1;     private String mParam2;     CompositeDisposable disposable;     List<Section> sectionsList=new ArrayList<>();     private OnConnectingFragments mListener;     @BindView(R.id.tabs)     TabLayout mTabLayout;     @BindView(R.id.viewpager)     ViewPager viewPager;     @BindView(R.id.secSelector)     Spinner spinner;     @BindView(R.id.className)     TextView className;     private static SectionChanger sectionChanger;     public StudentInformation() {         // Required empty public constructor     }      /**      * Use this factory method to create a new instance of      * this fragment using the provided parameters.      *      * @param param1 Parameter 1.      * @param param2 Parameter 2.      * @return A new instance of fragment StudentInformation.      */     // TODO: Rename and change types and number of parameters     public static StudentInformation newInstance(String param1, String param2) {         StudentInformation fragment = new StudentInformation();         Bundle args = new Bundle();         args.putString(ARG_PARAM1, param1);         args.putString(ARG_PARAM2, param2);         fragment.setArguments(args);         return fragment;     }      @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         if (getArguments() != null) {             mParam1 = getArguments().getString(ARG_PARAM1);             mParam2 = getArguments().getString(ARG_PARAM2);         }     }     @Override     public void onDestroyView() {         super.onDestroyView();         unbinder.unbind();         disposable.clear();     }     @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {         View view=inflater.inflate(R.layout.fragment_student_information, container, false);         unbinder = ButterKnife.bind(this, view);         LoadDataAndSetupViewPager();         //setupViewPager(viewPager);         mTabLayout.setupWithViewPager(viewPager);         mTabLayout.addOnTabSelectedListener(this);         spinner.setOnItemSelectedListener(this); //        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, MyConfiguration.CLASS_SECTIONS); //        spinner.setAdapter(arrayAdapter);          return view;     }      // TODO: Rename method, update argument and hook method into UI event     public void onButtonPressed(Fragment fragment,String tag) {         if (mListener != null) {             mListener.onClickedMenu(fragment,tag);         }     }      @Override     public void onAttach(Context context) {         super.onAttach(context);         if (context instanceof OnConnectingFragments) {             mListener = (OnConnectingFragments) context;         } else {             throw new RuntimeException(context.toString()                     + " must implement OnFragmentInteractionListener");         }     }      @Override     public void onDetach() {         super.onDetach();         mListener = null;     }     /**      * This interface must be implemented by activities that contain this      * fragment to allow an interaction in this fragment to be communicated      * to the activity and potentially other fragments contained in that      * activity.      * <p>      * See the Android Training lesson <a href=      * "http://developer.android.com/training/basics/fragments/communicating.html"      * >Communicating with Other Fragments</a> for more information.      */     /*private void setupViewPager(ViewPager viewPager) {         StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());         //adapter.addFragment(new StudentList(),"exam");          for (String claz: MyConfiguration.CLASS)             adapter.addFragment(new StudentList(), claz);         viewPager.setAdapter(adapter);     }*/     @OnClick(R.id.add)     public void OnClicked(LinearLayout view){         onButtonPressed(new AddStudent(),"addStudent");     }      @Override     public void onTabSelected(TabLayout.Tab tab) {         className.setText(String.format(getString(R.string.class_name), tab.getPosition()+1));     }      @Override     public void onTabUnselected(TabLayout.Tab tab) {      }      @Override     public void onTabReselected(TabLayout.Tab tab) {      }     public void LoadDataAndSetupViewPager() {         HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();         interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);         ClearableCookieJar cookieJar =                 new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getActivity()));         OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();          Requester requester=new Retrofit.Builder()                 .baseUrl(MyConfiguration.BASE_URL)                 .addCallAdapterFactory(RxJava2CallAdapterFactory.create())                 .addConverterFactory(JacksonConverterFactory.create())                 .client(client)                 .build().create(Requester.class);         disposable=new CompositeDisposable(requester.getClasses()    ////GETTING CLASSES////                 .observeOn(AndroidSchedulers.mainThread())                 .subscribeOn(Schedulers.io())                 .flatMapIterable(clazzs -> clazzs)                 .flatMap(clazz -> requester.getDivision(clazz.getClassId())  ////GETTING SECTIONS////                         .observeOn(AndroidSchedulers.mainThread())                         .subscribeOn(Schedulers.io())                         .flatMapIterable(sections -> sections)                         .doOnNext(section -> {sectionsList.add(section);                             Log.v("section_id",section.getSectionId());})                         .takeLast(1)                         .map(section -> clazz)                 )                 .doOnNext(clazz -> {clazz.setSections(sectionsList);                     Log.v("List Size",sectionsList.size()+"");                     sectionsList=new ArrayList<>();                 })                 .toList()                 .subscribe(this::SetupViewPager, throwable -> Log.e("retroerror",throwable.toString())));      }     public void SetupViewPager(List<Clazz> classList){         StudentViewPagerAdapter adapter = new StudentViewPagerAdapter(getFragmentManager());         //adapter.addFragment(new StudentList(),"exam");          for (Clazz claz: classList){             adapter.addFragment(new StudentList(), claz);         }          viewPager.setAdapter(adapter);         viewPager.setOffscreenPageLimit(3);         viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {             @Override             public void onPageSelected(int position) {                 super.onPageSelected(position);                 List<Section>sections=classList.get(position).getSections();                 ArrayAdapter<Section> arrayAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_spinner_dropdown_item, sections);                 spinner.setAdapter(arrayAdapter);             }         });     }      @Override     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                 Section section= (Section) parent.getItemAtPosition(position);                 sectionChanger.ChangeData(section);     }      @Override     public void onNothingSelected(AdapterView<?> parent) {      }     public static void bindSectionChangeListener(SectionChanger changer){         sectionChanger=changer;     } } 

The question is: Why the data get unchanged when selecting options in the spinner sometimes? (look my cases)

3 Answers

Answers 1

try using getChildFragmentManager() instead of getFragmentManager() will solve your issue

Answers 2

The problem is mainly here:

 public StudentList() {             StudentInformation.bindSectionChangeListener(this);         } 

This doesn't assure that the fragment visible to the user is the last bound. You set viewPager.setOffscreenPageLimit(3); meaning that three fragments per time can be instantiated, so when you are on a fragment also the right and the left one are created.

This explain why the last one works well, because there isn't a right fragment, and probably is the last one to be instantiated and bound.

Personally I would change the implementation handling the spinner inside the page fragment, since it acts only on the page fragment.

Solution with a setUserVisibleHint

Bind the page fragment to the main one when the fragment become visble to the user. Pay attention to memory leak and release the static reference

 @Override   public void setUserVisibleHint(boolean isVisibleToUser) {     super.setUserVisibleHint(isVisibleToUser);     if(isVisibleToUser){       StudentInformation.bindSectionChangeListener(this);     }   } 

Solution with a bus

Another quick solution could be to use a bus like this: http://square.github.io/otto/ In this way every fragment will subscribe to an event SelectedItemChanged and refresh them-self. The main fragment will post the updates every time the spinner selection is changed.

However the example is pretty big, so I'm not super sure that there aren't other problems. Try to share a complete project to receive more specific help.

Answers 3

When you work with recycleview rely only on your model class filed values. Do all the changes to model class and create row views based on this model class fields.

i.e, you have to create or change values or view state based on the value of the model class fields.

For ex: if you want to make a row (position 30) invisible, then i will set a flag in model class called visibility and set it to false.

in this case whenever view redraws in UI, we will have to check for the flag and set the visibility based on that model class field value.

Like this you can create flags, content values, serialized params from API etc in model class. This method will make your reclycleview more consistent through out user interactions and API changes.

Read More

tensorflow.python.framework.errors_impl.NotFoundError while creating a custom inception

Leave a Comment

Im using the following code to create a custom inception using tensorflow.

import tensorflow as tf import sys  interesting_class = sys.argv[1:] print("Interesting class: ", interesting_class)  # Read in the image_data  from os import listdir from shutil import copyfile from os.path import isfile, join varPath = 'toScan/' destDir = "scanned/" imgFiles = [f for f in listdir(varPath) if isfile(join(varPath, f))]   # Loads label file, strips off carriage return label_lines = [line.rstrip() for line                     in tf.gfile.GFile("/tf_files/retrained_labels.txt")]  # Unpersists graph from file with tf.gfile.FastGFile("/tf_files/retrained_graph.pb", 'rb') as f:     graph_def = tf.GraphDef()     graph_def.ParseFromString(f.read())     _ = tf.import_graph_def(graph_def, name='')  with tf.Session() as sess:     # Feed the image_data as input to the graph and get first prediction     softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')      file_count = len(imgFiles)     i = 0      for imageFile in imgFiles:         print("File ", i, " of ",  file_count)         i = i+1         image_data =  tf.gfile.FastGFile(varPath+"/"+imageFile, 'rb').read()                 print (varPath+"/"+imageFile)         predictions = sess.run(softmax_tensor, \                  {'DecodeJpeg/contents:0': image_data})          # Sort to show labels of first prediction in order of confidence         top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]         firstElt = top_k[0];          newFileName = label_lines[firstElt] +"--"+ str(predictions[0][firstElt])[2:7]+".jpg"         print(interesting_class, label_lines[firstElt])         if interesting_class == label_lines[firstElt]:             print(newFileName)             copyfile(varPath+"/"+imageFile, destDir+"/"+newFileName)          for node_id in top_k:             human_string = label_lines[node_id]             score = predictions[0][node_id]             print (node_id)             print('%s (score = %.5f)' % (human_string, score)) 

Im getting the following error while executing this

('Interesting class: ', []) Traceback (most recent call last): File "/Users/Downloads/imagenet_train-master/label_dir.py", line 22, in in tf.gfile.GFile("/tf_files/retrained_labels.txt")] File "/Users/tensorflow/lib/python2.7/site-packages/tensorflow/python/lib/io/file_io.py", line 156, in next retval = self.readline() File "/Users/tensorflow/lib/python2.7/site-packages/tensorflow/python/lib/io/file_io.py", line 123, in readline self._preread_check() File "/Users/tensorflow/lib/python2.7/site-packages/tensorflow/python/lib/io/file_io.py", line 73, in _preread_check compat.as_bytes(self.name), 1024 * 512, status) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/contextlib.py", line 24, in __exit self.gen.next() File "/Users/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status pywrap_tensorflow.TF_GetCode(status)) tensorflow.python.framework.errors_impl.NotFoundError: /tf_files/retrained_labels.txt

Why am I getting this error?

Following is my folder structure:

tensorflow_try |- new_pics |  |- class1 |  |- class2 |  |- ... |- toScan |- scanned 

1 Answers

Answers 1

The problem comes from this line:

label_lines = [line.rstrip() for line                     in tf.gfile.GFile("/tf_files/retrained_labels.txt")] 

Please check:

  1. The existence of the folder tf_files in the root of the file system -- you can run ls /tf_files to check this;
  2. (if item 1 is ok) if you have reading/writing permission on /tf_files/retrained_labels.txt.
Read More