问:
Typescript Cannot write file would overwrite input file. Error when compiling Ionic 3 app
I've been trying to use a given .js api in an ionic 3 project. With some help I was able to get the api into to the project without any errors and am now able to use the functions it has. However the API uses JQuery 2.1.0 and now when compiling the project I get the following error: Cannot write file '.../src/assets/jquery-2.1.0.min.js' because it would overwrite input file. I have no idea on how to fix this.. I've tried to import the jquery file as a module but that gives me some errors as well. Both the api.ts and jquery-2.1.0.min.js are in the src/assets/ folder and then the api is imported in my src/pages/home/home.ts file.

This is the api.ts:

```<code>import * as $ from './jquery-2.1.0.min.js';

export class API {
  ServerUrl = '';

  Type = {
    Day: 'day',
    Night: 'night'
  };

  Days = {
    Monday: 'Monday',
    Tuesday: 'Tuesday',
    Wednesday: 'Wednesday',
    Thursday: 'Thursday',
    Friday: 'Friday',
    Saturday: 'Saturday',
    Sunday: 'Sunday'
  };

  MinTemperature = parseFloat('5.0');
  MaxTemperature = parseFloat('30.0');
  MaxSwitches = 5;

  Time;
  CurrentDay;
  DayTemperature;
  NightTemperature;
  CurrentTemperature;
  TargetTemperature;
  ProgramState;

  Program:any = {};

  constructor() {
    this.Program[this.Days.Monday]    = [];
    this.Program[this.Days.Tuesday]   = [];
    this.Program[this.Days.Wednesday] = [];
    this.Program[this.Days.Thursday]  = [];
    this.Program[this.Days.Friday]    = [];
    this.Program[this.Days.Saturday]  = [];
    this.Program[this.Days.Sunday]    = [];
  }

  /* Retrieve day program
   */
  getProgram(day) {
    return this.Program[day];
  }

  /* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
   */
  sortMergeProgram(day) {
    let program = this.getProgram(day);
    program.sort(function(a, b) {
      return this.parseTime(a[0]) - this.parseTime(b[0])
    });
    for (let i = 0; i < program.length - 1; i++) {
      if (this.parseTime(program[i][1]) >= this.parseTime(program[i + 1][0])) {
        let start = (program[i][0]);
        let end = (this.parseTime(program[i][1]) > this.parseTime(program[i + 1][1])) ? program[i][1] : program[i + 1][1];
        program.splice(i, 2);
        program.push([start, end]);
        this.sortMergeProgram(day);
        break;
      }
    }
  }

  /* Retrieves all data from the server except for weekProgram
   */
  get(attribute_name, xml_tag) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).find(xml_tag).text();
      }
    );
  }

  /* Retrieves the week program
   */
  getWeekProgram() {
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          this.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == this.Type.Day) {
                this.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                this.getProgram(day)[this.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return this.Program;
      }
    );
  }

  /* Uploads all data to the server except for currentTemperature and weekProgram
   */
  put(attribute_name, xml_tag, value) {
    this.uploadData("/" + attribute_name, "<" + xml_tag + ">" + value + "</" + xml_tag + ">");
  }

  requestData(address, func) {
    let result;
    (<any>$).ajax({
      type: "get",
      url: this.ServerUrl + address,
      dataType: "xml",
      async: false,
      success: function(data) {
        result = func(data);
      }
    });
    return result;
  }

  /* Uploads the week program
   */
  setWeekProgram() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;
      let periods = this.getProgram(key);
      for (i = 0; i < periods.length; i++) {
        daySwitches.push(periods[i][0]);
        nightSwitches.push(periods[i][1]);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);

        if (i < daySwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(daySwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);

        if (i < nightSwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(nightSwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }
      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  /* Creates the default week program
   */
  setDefault() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  uploadData(address, xml) {
    (<any>$).ajax({
      type: "put",
      url: this.ServerUrl + address,
      contentType: 'application/xml',
      data: xml,
      async: false
    });
  }

  parseTime(t) {
    return parseFloat(t.substr(0, 2)) + parseFloat(t.substr(3, 2)) / 60;
  }

  /* Adds a heating period for a specific day
   */
  addPeriod(day, start, end) {
    let program = this.getWeekProgram()[day];
    program.push([start, end]);
    this.sortMergeProgram(day);
    this.setWeekProgram();
  }

  /* Removes a heating period from a specific day.
     idx is the idex of the period with values from 0 to 4
  */
  removePeriod(day, idx) {
    let program = this.getWeekProgram()[day];
    let start = program[idx][0];
    let end = program[idx][1];
    program.splice(idx, 1);
    this.setWeekProgram();
  }

  /* Checks whether the temperature is within the range [5.0,30.0]
   */
  inTemperatureBoundaries(temp) {
    temp = parseFloat(temp);
    return (temp >= this.MinTemperature && temp <= this.MaxTemperature);
  }
}
</code>```

And this is the jquery-2.1.0.js that was provided (pastebin link since the file is too large, it is very large).

I have already edited my tsconfig.json to also have "allowJs"= true, in there.

Is there anyone who know how I could possibly fix this?

Thanks in advance!!

答:
Looks like an issue with the Typescript declaration (.d.ts) files that is confusing the compiler.

First run this command to delete all old declaration files the tsc has generated:

```<code>find . -type f -name "*.d.ts" -delete
</code>```

Then change your tsconfig.json to have

"compilerOptions": {
    "declaration": false,
    ...
}
```

Body:
I've been trying to use a given .js api in an ionic 3 project. With some help I was able to get the api into to the project without any errors and am now able to use the functions it has. However the API uses JQuery 2.1.0 and now when compiling the project I get the following error: Cannot write file '.../src/assets/jquery-2.1.0.min.js' because it would overwrite input file. I have no idea on how to fix this.. I've tried to import the jquery file as a module but that gives me some errors as well. Both the api.ts and jquery-2.1.0.min.js are in the src/assets/ folder and then the api is imported in my src/pages/home/home.ts file.

This is the api.ts:

import * as $ from './jquery-2.1.0.min.js';

export class API {
  ServerUrl = '';

  Type = {
    Day: 'day',
    Night: 'night'
  };

  Days = {
    Monday: 'Monday',
    Tuesday: 'Tuesday',
    Wednesday: 'Wednesday',
    Thursday: 'Thursday',
    Friday: 'Friday',
    Saturday: 'Saturday',
    Sunday: 'Sunday'
  };

  MinTemperature = parseFloat('5.0');
  MaxTemperature = parseFloat('30.0');
  MaxSwitches = 5;

  Time;
  CurrentDay;
  DayTemperature;
  NightTemperature;
  CurrentTemperature;
  TargetTemperature;
  ProgramState;

  Program:any = {};

  constructor() {
    this.Program[this.Days.Monday]    = [];
    this.Program[this.Days.Tuesday]   = [];
    this.Program[this.Days.Wednesday] = [];
    this.Program[this.Days.Thursday]  = [];
    this.Program[this.Days.Friday]    = [];
    this.Program[this.Days.Saturday]  = [];
    this.Program[this.Days.Sunday]    = [];
  }

  /* Retrieve day program
   */
  getProgram(day) {
    return this.Program[day];
  }

  /* Sorts the heating periods (the periods when the heating is on) and merges overlapping ones
   */
  sortMergeProgram(day) {
    let program = this.getProgram(day);
    program.sort(function(a, b) {
      return this.parseTime(a[0]) - this.parseTime(b[0])
    });
    for (let i = 0; i < program.length - 1; i++) {
      if (this.parseTime(program[i][1]) >= this.parseTime(program[i + 1][0])) {
        let start = (program[i][0]);
        let end = (this.parseTime(program[i][1]) > this.parseTime(program[i + 1][1])) ? program[i][1] : program[i + 1][1];
        program.splice(i, 2);
        program.push([start, end]);
        this.sortMergeProgram(day);
        break;
      }
    }
  }

  /* Retrieves all data from the server except for weekProgram
   */
  get(attribute_name, xml_tag) {
    return this.requestData(
      "/" + attribute_name,
      function(data) {
        return $(data).find(xml_tag).text();
      }
    );
  }

  /* Retrieves the week program
   */
  getWeekProgram() {
    return this.requestData(
      '/weekProgram',
      function(data) {
        $(data).find('day').each(function() {
          let day = (<any>$(this)).attr('name');
          this.Program[day] = [];
          $(this).find('switch').each(function() {
            if ((<any>$(this)).attr('state') == 'on') {
              if ((<any>$(this)).attr('type') == this.Type.Day) {
                this.getProgram(day).push([$(this).text(), '00:00']);
              } else {
                this.getProgram(day)[this.getProgram(day).length - 1][1] = $(this).text();
              }
            }
          })
        });
        return this.Program;
      }
    );
  }

  /* Uploads all data to the server except for currentTemperature and weekProgram
   */
  put(attribute_name, xml_tag, value) {
    this.uploadData("/" + attribute_name, "<" + xml_tag + ">" + value + "</" + xml_tag + ">");
  }

  requestData(address, func) {
    let result;
    (<any>$).ajax({
      type: "get",
      url: this.ServerUrl + address,
      dataType: "xml",
      async: false,
      success: function(data) {
        result = func(data);
      }
    });
    return result;
  }

  /* Uploads the week program
   */
  setWeekProgram() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;
      let periods = this.getProgram(key);
      for (i = 0; i < periods.length; i++) {
        daySwitches.push(periods[i][0]);
        nightSwitches.push(periods[i][1]);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);

        if (i < daySwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(daySwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);

        if (i < nightSwitches.length) {
          sw.setAttribute('state', 'on');
          text = doc.createTextNode(nightSwitches[i]);
        } else {
          sw.setAttribute('state', 'off');
          text = doc.createTextNode('00:00');
        }
        sw.appendChild(text);
        day.appendChild(sw);
      }
      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  /* Creates the default week program
   */
  setDefault() {
    let doc = document.implementation.createDocument(null, null, null);
    let program = doc.createElement('week_program');
    program.setAttribute('state', this.ProgramState ? 'on' : 'off');
    for (let key in this.Program) {
      let day = doc.createElement('day');
      day.setAttribute('name', key);

      let daySwitches = [];
      let nightSwitches = [];

      let i, text, sw;

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Night);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      for (i = 0; i < this.MaxSwitches; i++) {
        sw = doc.createElement('switch');
        sw.setAttribute('type', this.Type.Day);
        sw.setAttribute('state', 'off');
        text = doc.createTextNode('00:00');
        sw.appendChild(text);
        day.appendChild(sw);
      }

      program.appendChild(day);
    }
    doc.appendChild(program);
    this.uploadData('/weekProgram', (new XMLSerializer()).serializeToString(doc));
  }

  uploadData(address, xml) {
    (<any>$).ajax({
      type: "put",
      url: this.ServerUrl + address,
      contentType: 'application/xml',
      data: xml,
      async: false
    });
  }

  parseTime(t) {
    return parseFloat(t.substr(0, 2)) + parseFloat(t.substr(3, 2)) / 60;
  }

  /* Adds a heating period for a specific day
   */
  addPeriod(day, start, end) {
    let program = this.getWeekProgram()[day];
    program.push([start, end]);
    this.sortMergeProgram(day);
    this.setWeekProgram();
  }

  /* Removes a heating period from a specific day.
     idx is the idex of the period with values from 0 to 4
  */
  removePeriod(day, idx) {
    let program = this.getWeekProgram()[day];
    let start = program[idx][0];
    let end = program[idx][1];
    program.splice(idx, 1);
    this.setWeekProgram();
  }

  /* Checks whether the temperature is within the range [5.0,30.0]
   */
  inTemperatureBoundaries(temp) {
    temp = parseFloat(temp);
    return (temp >= this.MinTemperature && temp <= this.MaxTemperature);
  }
}

And this is the jquery-2.1.0.js that was provided (pastebin link since the file is too large, it is very large).

I have already edited my tsconfig.json to also have "allowJs"= true, in there.

Is there anyone who know how I could possibly fix this?

Thanks in advance!!

Body:
Looks like an issue with the Typescript declaration (.d.ts) files that is confusing the compiler.

First run this command to delete all old declaration files the tsc has generated:

find . -type f -name "*.d.ts" -delete

Then change your tsconfig.json to have

"compilerOptions": {
    "declaration": false,
    ...
}


来源: stackexchange

问:
Convert array in json javascript - same key
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)
```

<p>And I'd like my JSON structured like this:</p>

<pre class="lang-js prettyprint-override"><code>{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}
</code>```

I tried using json_encode but this alone doesn't give me what I want.

答:
It makes sense to tackle the problem at the source if you're using PHP to create the data:

$arr = ['teste3.pdf', 'teste2.pdf', 'teste.pdf'];

$map = array_map(function($name){
    return ['NameDoc' => $name];
}, $arr);

echo json_encode([
    'Documents' => $map
]);
```

» Fiddle

ContentLicense: CC BY-SA 3.0

Body:
I have a PHP file where I have the name of the files of one folder and my objective now is to output this array as JSON.

My array looks like this:

Array (
    [0] => teste3.pdf
    [1] => teste2.pdf
    [2] => teste.pdf
    [3] => ..
    [4] => .
)

And I'd like my JSON structured like this:

{
    "Documents": [
        {
            "NameDoc": "teste3.pdf"
        },
        {
            "NameDoc": "teste2.pdf"
        },
        {
            "NameDoc": "teste.pdf"
        },
     ]
}

I tried using json_encode but this alone doesn't give me what I want.

Body:
It makes sense to tackle the problem at the source if you're using PHP to create the data:

$arr = ['teste3.pdf', 'teste2.pdf', 'teste.pdf'];

$map = array_map(function($name){
    return ['NameDoc' => $name];
}, $arr);

echo json_encode([
    'Documents' => $map
]);

» Fiddle


问:
Reading PNG files using Tensorflow
I want to build a conVNN based on my own image dataset. for that I first   I need to read the files here's what I've done :

```<code>import tensorflow as tf
# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(tf.train.match_filenames_once("test_png/*.png"))
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
tf.global_variables_initializer()
with tf.Session() as sess:
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)
</code>```

to make things easy: the test folder contains 10 png files named 1.png 2.png .... 10.png

when I run the code I get  the following :

```<code>    INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.FailedPreconditionError'>, Attempting to use uninitialized value matching_filenames
     [[Node: matching_filenames/read = Identity[T=DT_STRING, _class=["loc:@matching_filenames"], _device="/job:localhost/replica:0/task:0/cpu:0"](matching_filenames)]]

Caused by op 'matching_filenames/read', defined at:
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-110a62c88def>", line 3, in <module>
    filename_queue  = tf.train.string_input_producer(tf.train.match_filenames_once("test_png/*.png"))
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\training\input.py", line 68, in match_filenames_once
    collections=[ops.GraphKeys.LOCAL_VARIABLES])
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value matching_filenames
     [[Node: matching_filenames/read = Identity[T=DT_STRING, _class=["loc:@matching_filenames"], _device="/job:localhost/replica:0/task:0/cpu:0"](matching_filenames)]]

---------------------------------------------------------------------------
OutOfRangeError                           Traceback (most recent call last)
c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1038     try:
-> 1039       return fn(*args)
   1040     except errors.OpError as e:

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1020                                  feed_dict, fetch_list, target_list,
-> 1021                                  status, run_metadata)
   1022

c:\users\engine\appdata\local\programs\python\python35\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

OutOfRangeError: FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

During handling of the above exception, another exception occurred:

OutOfRangeError                           Traceback (most recent call last)
<ipython-input-1-110a62c88def> in <module>()
     16
     17     # Get an image tensor and print its value.
---> 18     image_tensor = sess.run([image])
     19     print(image_tensor)
     20

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053
   1054   def _extend_graph(self):

OutOfRangeError: FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

Caused by op 'ReaderReadV2', defined at:
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-110a62c88def>", line 9, in <module>
    imageName,imagefile= image_reader.read(filename_queue)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\io_ops.py", line 193, in read
    return gen_io_ops._reader_read_v2(self._reader_ref, queue_ref, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 411, in _reader_read_v2
    queue_handle=queue_handle, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

OutOfRangeError (see above for traceback): FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]
</code>```

To be honest I have no clew how I'm suppose to solve this ?
thanks in advance for any hint

Update

After  Ujjwal  answer I've the the parameter for tf.train.string_input_producer as followed :

```<code>import tensorflow as tf
import os
files = os.listdir('test_png')

# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(files)
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
#tf.global_variables_initializer()
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)
</code>```

Now it seem that TF can  find the files but still can't read them, here's  the actual  error message :

```<code>    [Command: python -u D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py]
2017-06-08 15:12:31.845015: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845384: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845662: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845949: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.846859: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847174: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847464: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847754: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Traceback (most recent call last):
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
    return fn(*args)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
    status, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\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: Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py", line 22, in <module>
    image_tensor = sess.run([image])
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

Caused by op 'ReaderReadV2', defined at:
  File "D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py", line 12, in <module>
    imageName,imagefile= image_reader.read(filename_queue)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\io_ops.py", line 193, in read
    return gen_io_ops._reader_read_v2(self._reader_ref, queue_ref, name=name)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 411, in _reader_read_v2
    queue_handle=queue_handle, name=name)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

[Finished in 1.972s]
</code>```

Update

Based on Ujjwal  answer is the code that I'm using now, hopefully it may help someone out there :

```<code>import tensorflow as tf
import os

# list files name
files = os.listdir("Test_PNG")
files = ["Test_PNG/" + s for s in files]
files = [os.path.abspath(s) for s in files ]

# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(files)
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
#tf.global_variables_initializer()
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)
</code>```

答: You have to initialize the variables. Try moving tf.global_variables_initializer() inside tf.Session() as sess: block and run it as tf.global_variables_initializer().run()

Title: Reading PNG files using Tensorflow

Body:
I want to build a conVNN based on my own image dataset. for that I first   I need to read the files here's what I've done :

import tensorflow as tf
# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(tf.train.match_filenames_once("test_png/*.png"))
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
tf.global_variables_initializer()
with tf.Session() as sess:
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)

to make things easy: the test folder contains 10 png files named 1.png 2.png .... 10.png

when I run the code I get  the following :

    INFO:tensorflow:Error reported to Coordinator: <class 'tensorflow.python.framework.errors_impl.FailedPreconditionError'>, Attempting to use uninitialized value matching_filenames
     [[Node: matching_filenames/read = Identity[T=DT_STRING, _class=["loc:@matching_filenames"], _device="/job:localhost/replica:0/task:0/cpu:0"](matching_filenames)]]

Caused by op 'matching_filenames/read', defined at:
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-110a62c88def>", line 3, in <module>
    filename_queue  = tf.train.string_input_producer(tf.train.match_filenames_once("test_png/*.png"))
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\training\input.py", line 68, in match_filenames_once
    collections=[ops.GraphKeys.LOCAL_VARIABLES])
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\variables.py", line 197, in __init__
    expected_shape=expected_shape)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\variables.py", line 316, in _init_from_args
    self._snapshot = array_ops.identity(self._variable, name="read")
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\gen_array_ops.py", line 1338, in identity
    result = _op_def_lib.apply_op("Identity", input=input, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

FailedPreconditionError (see above for traceback): Attempting to use uninitialized value matching_filenames
     [[Node: matching_filenames/read = Identity[T=DT_STRING, _class=["loc:@matching_filenames"], _device="/job:localhost/replica:0/task:0/cpu:0"](matching_filenames)]]

---------------------------------------------------------------------------
OutOfRangeError                           Traceback (most recent call last)
c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1038     try:
-> 1039       return fn(*args)
   1040     except errors.OpError as e:

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1020                                  feed_dict, fetch_list, target_list,
-> 1021                                  status, run_metadata)
   1022

c:\users\engine\appdata\local\programs\python\python35\lib\contextlib.py in __exit__(self, type, value, traceback)
     65             try:
---> 66                 next(self.gen)
     67             except StopIteration:

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\errors_impl.py in raise_exception_on_not_ok_status()
    465           compat.as_text(pywrap_tensorflow.TF_Message(status)),
--> 466           pywrap_tensorflow.TF_GetCode(status))
    467   finally:

OutOfRangeError: FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

During handling of the above exception, another exception occurred:

OutOfRangeError                           Traceback (most recent call last)
<ipython-input-1-110a62c88def> in <module>()
     16
     17     # Get an image tensor and print its value.
---> 18     image_tensor = sess.run([image])
     19     print(image_tensor)
     20

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    980     if final_fetches or final_targets:
    981       results = self._do_run(handle, final_targets, final_fetches,
--> 982                              feed_dict_string, options, run_metadata)
    983     else:
    984       results = []

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1030     if handle is None:
   1031       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1032                            target_list, options, run_metadata)
   1033     else:
   1034       return self._do_call(_prun_fn, self._session, handle, feed_dict,

c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
   1050         except KeyError:
   1051           pass
-> 1052       raise type(e)(node_def, op, message)
   1053
   1054   def _extend_graph(self):

OutOfRangeError: FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

Caused by op 'ReaderReadV2', defined at:
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 184, in _run_module_as_main
    "__main__", mod_spec)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\__main__.py", line 3, in <module>
    app.launch_new_instance()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
    app.start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\ioloop.py", line 887, in start
    handler_func(fd_obj, events)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
    self._handle_recv()
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tornado\stack_context.py", line 275, in null_wrapper
    return fn(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\ipykernel\zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2821, in run_ast_nodes
    if self.run_code(code, result):
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\IPython\core\interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-1-110a62c88def>", line 9, in <module>
    imageName,imagefile= image_reader.read(filename_queue)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\io_ops.py", line 193, in read
    return gen_io_ops._reader_read_v2(self._reader_ref, queue_ref, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 411, in _reader_read_v2
    queue_handle=queue_handle, name=name)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "c:\users\engine\appdata\local\programs\python\python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

OutOfRangeError (see above for traceback): FIFOQueue '_0_input_producer' is closed and has insufficient elements (requested 1, current size 0)
     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

To be honest I have no clew how I'm suppose to solve this ?
thanks in advance for any hint

Update

After  Ujjwal  answer I've the the parameter for tf.train.string_input_producer as followed :

import tensorflow as tf
import os
files = os.listdir('test_png')

# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(files)
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
#tf.global_variables_initializer()
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)

Now it seem that TF can  find the files but still can't read them, here's  the actual  error message :

    [Command: python -u D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py]
2017-06-08 15:12:31.845015: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845384: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845662: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE3 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.845949: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.846859: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847174: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847464: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX2 instructions, but these are available on your machine and could speed up CPU computations.
2017-06-08 15:12:31.847754: W c:\tf_jenkins\home\workspace\release-win\device\cpu\os\windows\tensorflow\core\platform\cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use FMA instructions, but these are available on your machine and could speed up CPU computations.
Traceback (most recent call last):
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1039, in _do_call
    return fn(*args)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1021, in _run_fn
    status, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\contextlib.py", line 66, in __exit__
    next(self.gen)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\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: Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py", line 22, in <module>
    image_tensor = sess.run([image])
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 778, in run
    run_metadata_ptr)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 982, in _run
    feed_dict_string, options, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1032, in _do_run
    target_list, options, run_metadata)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1052, in _do_call
    raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.NotFoundError: Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

Caused by op 'ReaderReadV2', defined at:
  File "D:\Masterarbeit\Tensorflow\Main\convNN\own_DATA.py", line 12, in <module>
    imageName,imagefile= image_reader.read(filename_queue)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\io_ops.py", line 193, in read
    return gen_io_ops._reader_read_v2(self._reader_ref, queue_ref, name=name)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\gen_io_ops.py", line 411, in _reader_read_v2
    queue_handle=queue_handle, name=name)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 768, in apply_op
    op_def=op_def)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2336, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "C:\Users\Engine\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1228, in __init__
    self._traceback = _extract_stack()

NotFoundError (see above for traceback): Can not get size for: 4.png : The system cannot find the file specified.

     [[Node: ReaderReadV2 = ReaderReadV2[_device="/job:localhost/replica:0/task:0/cpu:0"](WholeFileReaderV2, input_producer)]]

[Finished in 1.972s]

Update

Based on Ujjwal  answer is the code that I'm using now, hopefully it may help someone out there :

import tensorflow as tf
import os

# list files name
files = os.listdir("Test_PNG")
files = ["Test_PNG/" + s for s in files]
files = [os.path.abspath(s) for s in files ]

# Here generating a tensor of type string that include all the filename with png extention
filename_queue  = tf.train.string_input_producer(files)
# Initializing a file Reader
image_reader = tf.WholeFileReader()

# Here the file all the files mentioned ie filename queue and
# returns the  the file name and the pixelvalue in form of a tensor !
imageName,imagefile= image_reader.read(filename_queue)
image = tf.image.decode_png(imagefile)
#tf.global_variables_initializer()
with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    image_tensor = sess.run([image])
    print(image_tensor)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)


问:
Permission dialogs
In my AndroidManifest.xml:

```<code><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

答:
I use the following code to get the permission in my app
string

```<code> <string name="permissions_title">Permissions</string>
<string name="draw_over_permissions_message">To display Audio Widget app needs the permission to draw over another apps.</string>
<string name="read_ext_permissions_message">To load list of music app needs access to your media files.</string>
<string name="btn_continue">Continue</string>
<string name="btn_cancel">Cancel</string>
<string name="toast_permissions_not_granted">Permissions not granted.</string>
</code>```

java

```<code> @TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {

                        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);

                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        onPermissionsNotGranted();

                    }
                    dialog.dismiss();
                    finish();
                    startActivity(getIntent());
                }
            };
            new AlertDialog.Builder(this)
                    .setTitle(R.string.permissions_title)
                    .setMessage(R.string.read_ext_permissions_message)
                    .setPositiveButton(R.string.btn_continue, onClickListener)
                    .setNegativeButton(R.string.btn_cancel, onClickListener)
                    .setCancelable(false)
                    .show();
            return;
        }
        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
        return;
    }

}

private void onPermissionsNotGranted() {
    Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
    Log.v("tom", "JERRY");
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void checkwriteStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {

                        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
                        Log.v("tom", "TOM");
                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        onPermissionsNotGranted();
                        Log.v("tom", "JERRY");
                    }
                    dialog.dismiss();
                }
            };
            new AlertDialog.Builder(this)
                    .setTitle(R.string.permissions_title)
                    .setMessage(R.string.read_ext_permissions_message)
                    .setPositiveButton(R.string.btn_continue, onClickListener)
                    .setNegativeButton(R.string.btn_cancel, onClickListener)
                    .setCancelable(false)
                    .show();
            return;
        }
        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
        return;
    }

}
</code>```

with

```<code> private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;
</code>```

and you can call the method where ever you want.

Title: Permission dialogs

Body:
In my AndroidManifest.xml:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

But when I have installed my App-APK, I must setting up the permissions in my Android OS in the settings manually (Settings > Apps > myApp > Permissions > Storage).

How can I get that the permissions setting up automatically. Or the user of my App must confirm it in a dialog?

Body:
I use the following code to get the permission in my app
string

 <string name="permissions_title">Permissions</string>
<string name="draw_over_permissions_message">To display Audio Widget app needs the permission to draw over another apps.</string>
<string name="read_ext_permissions_message">To load list of music app needs access to your media files.</string>
<string name="btn_continue">Continue</string>
<string name="btn_cancel">Cancel</string>
<string name="toast_permissions_not_granted">Permissions not granted.</string>

java

 @TargetApi(Build.VERSION_CODES.M)
private void checkReadStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {
            DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {

                        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, EXT_STORAGE_PERMISSION_REQ_CODE);

                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        onPermissionsNotGranted();

                    }
                    dialog.dismiss();
                    finish();
                    startActivity(getIntent());
                }
            };
            new AlertDialog.Builder(this)
                    .setTitle(R.string.permissions_title)
                    .setMessage(R.string.read_ext_permissions_message)
                    .setPositiveButton(R.string.btn_continue, onClickListener)
                    .setNegativeButton(R.string.btn_cancel, onClickListener)
                    .setCancelable(false)
                    .show();
            return;
        }
        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.READ_PHONE_STATE}, EXT_STORAGE_PERMISSION_REQ_CODE);
        return;
    }

}

private void onPermissionsNotGranted() {
    Toast.makeText(this, R.string.toast_permissions_not_granted, Toast.LENGTH_SHORT).show();
    Log.v("tom", "JERRY");
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void checkwriteStoragePermission() {
    if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == DialogInterface.BUTTON_POSITIVE) {

                        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
                        Log.v("tom", "TOM");
                    } else if (which == DialogInterface.BUTTON_NEGATIVE) {
                        onPermissionsNotGranted();
                        Log.v("tom", "JERRY");
                    }
                    dialog.dismiss();
                }
            };
            new AlertDialog.Builder(this)
                    .setTitle(R.string.permissions_title)
                    .setMessage(R.string.read_ext_permissions_message)
                    .setPositiveButton(R.string.btn_continue, onClickListener)
                    .setNegativeButton(R.string.btn_cancel, onClickListener)
                    .setCancelable(false)
                    .show();
            return;
        }
        ActivityCompat.requestPermissions(ParentActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE);
        return;
    }

}

with

 private static final int WRITE_EXTERNAL_STORAGE = 4;
private static final int READ_PHONE_STATE = 3;

and you can call the method where ever you want.


问:
Logging to JSON
I'm wondering if there's an implementation of slf4j that logs into a JSON format.  Where each log messages would be a JSON object, 1 per row.

e.g. each line of the log file would look like something this:

```<code>{"severity":"WARN", "ts":12345678, "host":"myhostname.com", "message":"Failed to do something"}
</code>```

答:
Ok, this thread needs to be updated a bit since most of the answers are quite old. All modern java log liibraries support json layout out of the box. With log4j2 you don't even need any additional libs, just jackson in your classpath, which you most likely already have.

Of course, you do need to use json layout and specify it explicitly.
See example for log4j2 here.
Note that default layout might not work as expected with your log collectors of choice. For example, I used FileBeat and it required for logs to be produced one per line. Log4j2 has a tuple of parameters for that:

Use with eventEol=true and compact=true to get one record per line.

My appenders look like this:

```<code><Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
        <JsonLayout complete="false" compact="true" eventEol="true"/>
    </Console>
    <Console name="STDERR" target="SYSTEM_ERR">
        <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
        <JsonLayout complete="false" compact="true" eventEol="true"/>
    </Console>
</Appenders>
</code>```

If this is not enough, you can also take a look at this repo: https://github.com/savoirtech/slf4j-json-logger

Title: Logging to JSON

Body:
I'm wondering if there's an implementation of slf4j that logs into a JSON format.  Where each log messages would be a JSON object, 1 per row.

e.g. each line of the log file would look like something this:

{"severity":"WARN", "ts":12345678, "host":"myhostname.com", "message":"Failed to do something"}

Body:
Ok, this thread needs to be updated a bit since most of the answers are quite old. All modern java log liibraries support json layout out of the box. With log4j2 you don't even need any additional libs, just jackson in your classpath, which you most likely already have.

Of course, you do need to use json layout and specify it explicitly.
See example for log4j2 here.
Note that default layout might not work as expected with your log collectors of choice. For example, I used FileBeat and it required for logs to be produced one per line. Log4j2 has a tuple of parameters for that:

Use with eventEol=true and compact=true to get one record per line.

My appenders look like this:

<Appenders>
    <Console name="STDOUT" target="SYSTEM_OUT">
        <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="ACCEPT"/>
        <JsonLayout complete="false" compact="true" eventEol="true"/>
    </Console>
    <Console name="STDERR" target="SYSTEM_ERR">
        <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY"/>
        <JsonLayout complete="false" compact="true" eventEol="true"/>
    </Console>
</Appenders>

If this is not enough, you can also take a look at this repo: https://github.com/savoirtech/slf4j-json-logger

ContentLicense: CC BY-SA 4.0


问:
Split string by first white space
I want to split string in array based just on first white space in string.

Like this:

```<code>var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];
</code>```

答:
Simple.

```<code>function splitFirst(s) {
  var firstW = s.indexOf(" ");
  if (firstW < 0) {
    return s;
  }
  var array = [];
  array.push(s.substring(0, firstW));
  array.push(s.substring(firstW, s.length - 1));
  return array;
}
</code>```

Note: Javascript coding convention says variables have to start with lowercase.

Title: Split string by first white space

Body:
I want to split string in array based just on first white space in string.

Like this:

var name = "Jone Doe Doone";
var res = ["Jone", "Doe Doone"];

Body:
Simple.

function splitFirst(s) {
  var firstW = s.indexOf(" ");
  if (firstW < 0) {
    return s;
  }
  var array = [];
  array.push(s.substring(0, firstW));
  array.push(s.substring(firstW, s.length - 1));
  return array;
}

Note: Javascript coding convention says variables have to start with lowercase.


问:
Display attributed text in textview in swift 3?
I want to display text in Italic ,bold which is received from server .

   hello   world
 so,

```<code>responseObj!["text"] = "<p><b><i>hello</i></b><i>world</></p>"
     if let postText:String = responseObj!["text"] as? String{
          let str = try NSAttributedString(data: postText.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
      self.textView.attributedText = str
    }
</code>```

when i am adding like this means my text displays normal without applying bold & italic . I want text to be displayed in bold ,italic .

答:
EDIT: Updated Swift 4

Create an extension for String:

```<code>extension String {
    func htmlAttributedString(fontSize: CGFloat = 17.0) -> NSAttributedString? {
        let fontName = UIFont.systemFont(ofSize: fontSize).fontName
        let string = self.appending(String(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", fontName, fontSize))
        guard let data = string.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

        guard let html = try? NSMutableAttributedString (
             data: data,
             options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
             documentAttributes: nil) else { return nil }
        return html
    }
}
</code>```

Invoke it anywhere in your project:

```<code>text.htmlAttributedString() // will set fontSize with 17.0 which is the default value

text.htmlAttributedString(fontSize: 14.0) // pass your required fontSize
</code>```

Note, that let string = self.appending(String(format: "", fontName, fontSize)) is used to keep the string font as same as the font used in default iOS platform.

To set the string on UITextView use:

```<code>textView.attributedText = textToBeConverted.htmlAttributedString() ?? ""
</code>```

RESULT:

Body:
I want to display text in Italic ,bold which is received from server .

   hello   world
 so,

responseObj!["text"] = "
helloworld</>
"
     if let postText:String = responseObj!["text"] as? String{
          let str = try NSAttributedString(data: postText.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
      self.textView.attributedText = str
    }

when i am adding like this means my text displays normal without applying bold & italic . I want text to be displayed in bold ,italic .

Body:
EDIT: Updated Swift 4

Create an extension for String:

extension String {
    func htmlAttributedString(fontSize: CGFloat = 17.0) -> NSAttributedString? {
        let fontName = UIFont.systemFont(ofSize: fontSize).fontName
        let string = self.appending(String(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", fontName, fontSize))
        guard let data = string.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }

        guard let html = try? NSMutableAttributedString (
             data: data,
             options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
             documentAttributes: nil) else { return nil }
        return html
    }
}

Invoke it anywhere in your project:

text.htmlAttributedString() // will set fontSize with 17.0 which is the default value

text.htmlAttributedString(fontSize: 14.0) // pass your required fontSize

Note, that let string = self.appending(String(format: "<style>body{font-family: '%@'; font-size:%fpx;}</style>", fontName, fontSize)) is used to keep the string font as same as the font used in default iOS platform.

To set the string on UITextView use:

textView.attributedText = textToBeConverted.htmlAttributedString() ?? ""

RESULT:


问:
kdb5_util dump gives Server error
I have been trying to dump my Kerberos database (ldap backend) using kdb5_util dump (filename), but I get:

```<code>kdb5_util load_dump version 6
kdb5_util: error performing Kerberos version 5 release 1.8 dump (Server error)
policy  default    0       0       1       1       1       0       0       0       0
</code>```

Kerberos KDC and Kadmin log has nothing, ldap.log gives
    May 31 12:40:17 kdc slapd[28020]: connection_input: conn=1091 deferring operation: binding

Everything else works fine, creating, deleting, authentication of principals, no problem. Just dumping the DB fails. As far as I understand, the backend should not have any influence on the dump.

Any ideas how I can debug or fix this? What am I missing?

/etc/krb5.conf

```<code>[libdefaults]
        default_realm   = REALM.EXAMPLE.COM
        kdc_timesync    = 1
        ccache_type     = 4
        forwardable     = true
        proxiable       = true

[realms]
        REALM.EXAMPLE.COM = {
                kdc             = kdc.realm.example.com
                admin_server    = kdc.realm.example.com
                kpasswd_server  = kdc.realm.example.com
        }

[domain_realm]
        .realm.example.com  = REALM.EXAMPLE.COM
</code>```

/etc/krb5kdc/kdc.conf

```<code>[realms]
    REALM.EXAMPLE.COM = {
        default_domain  = realm.example.com
        database_module = ldapconf

        acl_file        = /etc/krb5kdc/kadm5.acl
        key_stash_file  = /etc/krb5kdc/.master

       max_life        = 10h 0m 0s
       max_renewable_life = 7d 0h 0m 0s

        master_key_type         = aes256-cts
        supported_enctypes      = aes256-cts-hmac-sha1-96:normal
#aes128-cts-hmac-sha1-96:normal arcfour-hmac:normal
        default_principal_flags = +preauth

        pkinit_identity = FILE:/etc/krb5kdc/kdc-cert.pem,/etc/krb5kdc/.kdc-key.pem
        pkinit_anchors  = FILE:/etc/krb5kdc/ca-cert.pem

        dict_file       = /root/bad_passwords.dict
    }

[dbmodules]
        ldapconf = {
                db_library                 = kldap
                ldap_kerberos_container_dn = "cn=kerberos,dc=realm,dc=example,dc=com"
                ldap_kdc_dn                = "cn=kerberos-kdc,dc=realm,dc=example,dc=com"
                ldap_kadmind_dn            = "cn=kerberos-admin,dc=realm,dc=example,dc=com"
                ldap_servers               = ldapi:///
                ldap_service_password_file = /etc/krb5kdc/.service
    }
[logging]
kdc          = FILE:/var/log/kerberos/kdc.log
admin_server = FILE:/var/log/kerberos/kadmin.log
default      = FILE:/var/log/kerberos/kerberos.log
</code>```

答:
Found the Problem after debugging at last:

The LDAP backend has a hard Size limit of 500 for search requests. With 501 Users that bit me in the backside!

Fix:

```<code>#
# remove sizelimit for ldap search
#
# apply with ldapmodify -Y EXTERNAL -H ldapi:/// -f sizelimit.ldif
#
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcLimits
olcLimits:  dn.exact="cn=kerberos-admin,dc=realm,dc=example,dc=com" size=unlimited
</code>```

Apply, restart slapd, and dump happily away

Title: kdb5_util dump gives Server error

Body:
I have been trying to dump my Kerberos database (ldap backend) using kdb5_util dump (filename), but I get:

kdb5_util load_dump version 6
kdb5_util: error performing Kerberos version 5 release 1.8 dump (Server error)
policy  default    0       0       1       1       1       0       0       0       0

Kerberos KDC and Kadmin log has nothing, ldap.log gives
    May 31 12:40:17 kdc slapd[28020]: connection_input: conn=1091 deferring operation: binding

Everything else works fine, creating, deleting, authentication of principals, no problem. Just dumping the DB fails. As far as I understand, the backend should not have any influence on the dump.

Any ideas how I can debug or fix this? What am I missing?

/etc/krb5.conf

[libdefaults]
        default_realm   = REALM.EXAMPLE.COM
        kdc_timesync    = 1
        ccache_type     = 4
        forwardable     = true
        proxiable       = true

[realms]
        REALM.EXAMPLE.COM = {
                kdc             = kdc.realm.example.com
                admin_server    = kdc.realm.example.com
                kpasswd_server  = kdc.realm.example.com
        }

[domain_realm]
        .realm.example.com  = REALM.EXAMPLE.COM

/etc/krb5kdc/kdc.conf

[realms]
    REALM.EXAMPLE.COM = {
        default_domain  = realm.example.com
        database_module = ldapconf

        acl_file        = /etc/krb5kdc/kadm5.acl
        key_stash_file  = /etc/krb5kdc/.master

       max_life        = 10h 0m 0s
       max_renewable_life = 7d 0h 0m 0s

        master_key_type         = aes256-cts
        supported_enctypes      = aes256-cts-hmac-sha1-96:normal
#aes128-cts-hmac-sha1-96:normal arcfour-hmac:normal
        default_principal_flags = +preauth

        pkinit_identity = FILE:/etc/krb5kdc/kdc-cert.pem,/etc/krb5kdc/.kdc-key.pem
        pkinit_anchors  = FILE:/etc/krb5kdc/ca-cert.pem

        dict_file       = /root/bad_passwords.dict
    }

[dbmodules]
        ldapconf = {
                db_library                 = kldap
                ldap_kerberos_container_dn = "cn=kerberos,dc=realm,dc=example,dc=com"
                ldap_kdc_dn                = "cn=kerberos-kdc,dc=realm,dc=example,dc=com"
                ldap_kadmind_dn            = "cn=kerberos-admin,dc=realm,dc=example,dc=com"
                ldap_servers               = ldapi:///
                ldap_service_password_file = /etc/krb5kdc/.service
    }
[logging]
kdc          = FILE:/var/log/kerberos/kdc.log
admin_server = FILE:/var/log/kerberos/kadmin.log
default      = FILE:/var/log/kerberos/kerberos.log

Body:
Found the Problem after debugging at last:

The LDAP backend has a hard Size limit of 500 for search requests. With 501 Users that bit me in the backside!

Fix:

#
# remove sizelimit for ldap search
#
# apply with ldapmodify -Y EXTERNAL -H ldapi:/// -f sizelimit.ldif
#
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcLimits
olcLimits:  dn.exact="cn=kerberos-admin,dc=realm,dc=example,dc=com" size=unlimited

Apply, restart slapd, and dump happily away


问:
Julia: Abstract and Concrete Types Integer versus Int8 versus Int64
Suppose I have an integer n that will only ever take values in [0, 10]. Should I declare it as n::Integer to be general about it, as n::Int8 or n::UInt8 to be parsimonious or n::Int64 for a 64 bit system?

Please clarify the reasons for a newbie, e.g. style, performance.

Reference: https://docs.julialang.org/en/release-0.5/manual/integers-and-floating-point-numbers/

Updated Reference (2021): https://docs.julialang.org/en/v1/manual/types/#man-abstract-types

答:
EDIT: refer to Stefan's accepted answer. I meant this is a response to the use of types in function dispatch, but in fact contradicted myself (as I do say explicitly that function dispatch should actually be Integer).

I'd always use Int, just for the generality of it, but it depends how performance-critical your application is. Never Int64 unless you explicitly need it. Many functions dispatch on Int rather than Integer(though the advice is to dispatch on abstract types), which means that they will fail when passed a UInt8 (because Int is a subtype of Signed and UInt isn't) so being overzealous with types will cause problems.
As a general rule-of-thumb you should never be more specific with types than you have to.


答:
Try the following answer.</p>

```<code>var Name = "Jone Doe Doone";
var result = [Name.split(" ")[0]];
result.push(Name.substr(Name.split(" ")[0].length).trim());
console.log(result);
</code>```

Title: Split string by first white space

Body:
Try the following answer.

var Name = "Jone Doe Doone";
var result = [Name.split(" ")[0]];
result.push(Name.substr(Name.split(" ")[0].length).trim());
console.log(result);


问:
Handlebars math expressions when looping through array
I'm practicing node, and I ran to a little problem. I'm using handlebars as a templating engine, and mongoose for interaction with my database. In my .hbs template I am looping through each record from the database, and of course I passed the records to my view with

```<code>router.get('/', function(req, res, next) {
Exam.find(function(err, predmeti) {
if (err) {
  console.log(err);
}
  res.render('index',{
    predmeti: predmeti
  })
})

});
</code>```

Now when im looping through predmeti with #each, engine throws an error when I try doing math expressions such as

```<code>{{#each predmeti}}
 <h1>{{100/(brKolokvijuma/finished)}}</h1>
{{/each}}
</code>```

brKolokvijuma and finished both have a number value, but for some reason I get a error Expecting ID got OPEN_SEXPR

So I'm assuming handlebars won't let me do math expressions when I'm looping through an array. How can I solve this?

答:
There are plugins for Handlebars to enable you to do the things they think you shouldn't do in views, but everyone still wants to.

For example the Assemble.io maths helpers and nested expressions would enable you to do something like:

```<code>{{#each predmeti}}
   <h1>{{divide 100 (divide brKolokvijuma finished)}}</h1>
{{/each}}
</code>```

A second method, if your maths expressions are not so varied and reused around your views (common calculations e.g. tax or rounding), you could write your own simpler/lighter plugin:

```<code>Handlebars.registerHelper("divideMyThings", function(thing1, thing2, thing3) {
  return thing1 / thing2 / thing3;
});
</code>```

Called in your template:

```<code>{{divideMyThings 100 brKolokvijuma finished}}
</code>```

Thirdly you can often precompute data-tables until you only have one variable, and then use the builtin lookup feature. This requires no additional plugins. This is probably not helpful to this specific question, but I thought I'd mention it as a tool.

Body:
I'm practicing node, and I ran to a little problem. I'm using handlebars as a templating engine, and mongoose for interaction with my database. In my .hbs template I am looping through each record from the database, and of course I passed the records to my view with

router.get('/', function(req, res, next) {
Exam.find(function(err, predmeti) {
if (err) {
  console.log(err);
}
  res.render('index',{
    predmeti: predmeti
  })
})

});

Now when im looping through predmeti with #each, engine throws an error when I try doing math expressions such as

{{#each predmeti}}

{{100/(brKolokvijuma/finished)}}

{{/each}}

brKolokvijuma and finished both have a number value, but for some reason I get a error Expecting ID got OPEN_SEXPR

So I'm assuming handlebars won't let me do math expressions when I'm looping through an array. How can I solve this?

Body:
There are plugins for Handlebars to enable you to do the things they think you shouldn't do in views, but everyone still wants to.

For example the Assemble.io maths helpers and nested expressions would enable you to do something like:

{{#each predmeti}}
   <h1>{{divide 100 (divide brKolokvijuma finished)}}</h1>
{{/each}}

A second method, if your maths expressions are not so varied and reused around your views (common calculations e.g. tax or rounding), you could write your own simpler/lighter plugin:

Handlebars.registerHelper("divideMyThings", function(thing1, thing2, thing3) {
  return thing1 / thing2 / thing3;
});

Called in your template:

{{divideMyThings 100 brKolokvijuma finished}}

Thirdly you can often precompute data-tables until you only have one variable, and then use the builtin lookup feature. This requires no additional plugins. This is probably not helpful to this specific question, but I thought I'd mention it as a tool.


问:
Vue router redirect from a service?
Using vuejs 2 and the official vue-router.

How can I access the Router instance from a service that has not been given the instance?

We have an class that listens to a socket, on one particular event heard I need to use the vue-router to redirect to another page but I cannot see anywhere how to do this?

答:
The answer I found is:

First initialize the app into the window obj.:

```<code>window.vm = new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: {App}
})
</code>```

Now you access the router anywhere with ease:

```<code>window.vm.$route
</code>```

or

```<code>window.vm.$router
</code>```

Title: Vue router redirect from a service?

Body:
The answer I found is:

First initialize the app into the window obj.:

window.vm = new Vue({
  el: '#app',
  store,
  router,
  template: '<App/>',
  components: {App}
})

Now you access the router anywhere with ease:

window.vm.$route

or

window.vm.$router