问:
Request for the permission of type 'System.Data.Odbc.OdbcPermission.. help needed
I'm getting the following error when trying to connect to a remote mysql server.

```<code>Request for the permission of type 'System.Data.Odbc.OdbcPermission,
System.Data, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.
</code>```

I've installed the odbc 5.1 driver, and can connect to the database using the Data Sources (ODBC) tool in Control Panel.

However when I try and run my C# scrip to connect, I get the above error.

I've read its something to do with trust levels or something?  I don't quite understand what people were talking about though.  I went to C:... Framework/v2.0.50727/CONFIG and added  <IPermission class="OdbcPermission" version="1" Unrestricted="true"/>  to the medium and high trust.config files, but that didn't help..

Can someone help me out here please?

My connection string is

```<code>MyConString = "DRIVER={MySQL ODBC 5.1 Driver};" +
                "SERVER=" + m_strHost + ";" +
                "PORT=3306;" +
                "DATABASE=" + m_strDatabase + ";" +
                "UID=" + m_strUserName + ";" +
                "PWD=" + m_strPassword + ";" +
                "OPTION=3;";
</code>```

答: I would recommend using the .NET Connector instead of the ODBC driver.  I only use the ODBC driver for VBA/Microsoft Access connections.  With the .NET connector I have not had any connection issues similar to what you describe.</p>

Body:
I'm getting the following error when trying to connect to a remote mysql server.

Request for the permission of type 'System.Data.Odbc.OdbcPermission,
System.Data, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.

I've installed the odbc 5.1 driver, and can connect to the database using the Data Sources (ODBC) tool in Control Panel.

However when I try and run my C# scrip to connect, I get the above error.

I've read its something to do with trust levels or something?  I don't quite understand what people were talking about though.  I went to C:... Framework/v2.0.50727/CONFIG and added  <IPermission class="OdbcPermission" version="1" Unrestricted="true"/>  to the medium and high trust.config files, but that didn't help..

Can someone help me out here please?

My connection string is

MyConString = "DRIVER={MySQL ODBC 5.1 Driver};" +
                "SERVER=" + m_strHost + ";" +
                "PORT=3306;" +
                "DATABASE=" + m_strDatabase + ";" +
                "UID=" + m_strUserName + ";" +
                "PWD=" + m_strPassword + ";" +
                "OPTION=3;";


来源: stackexchange

问:
Component Interaction Angular 2
Hi I have two components, a list component, and an edit component and service.
part of my Svc:

```<code>.....

    // Observable string sources
    private _updatedArray = new Subject<string>();

      // Service message commands
    setColDefs(columns: any) {
       this._updatedArray.next(columns);
       console.log(columns);
    }

getColDef(): Observable<any> {
    return this._updatedArray.asObservable();
}
</code>```

And am calling my service in my list as below,

```<code>import { Svc } from '../services/mySvc.svc'

.....

this._listCompSvc.setColDefs(columns);
</code>```

Until here its working perfect. I set the column values and the console.log in my svc showing the columns I want. but the issue comes in the edit component, when am getting the values(subscribing). my edit component code:

```<code>import { Svc } from '../services/mySvc.svc';
..

export class EditComponent implements OnInit{
    private _colDefs: any;
    constructor(
        private _editCompSvc: Svc
        ){}

    ngOnInit() {
        this._editCompSvc.getColDef().subscribe(
          columns => {
              console.log(columns);
        });
    }
</code>```

....

But somehow my console.log in edit, not displaying any data. I want to return my columns value here as per i set in my list component. Any idea guys? Thanks in advance.

Module:

```<code>import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }
</code>```

答:
You have added Svc as a provider of your EditComponent. So each edit component gets its own instance of the service, which is different from the one used by the list component.

To be shared, the service must be provided by a common parent component, or by a common parent module.

ContentLicense: CC BY-SA 3.0

Title: Component Interaction Angular 2

Body:
Hi I have two components, a list component, and an edit component and service.
part of my Svc:

.....

    // Observable string sources
    private _updatedArray = new Subject<string>();

      // Service message commands
    setColDefs(columns: any) {
       this._updatedArray.next(columns);
       console.log(columns);
    }

getColDef(): Observable<any> {
    return this._updatedArray.asObservable();
}

And am calling my service in my list as below,

import { Svc } from '../services/mySvc.svc'

.....

this._listCompSvc.setColDefs(columns);

Until here its working perfect. I set the column values and the console.log in my svc showing the columns I want. but the issue comes in the edit component, when am getting the values(subscribing). my edit component code:

import { Svc } from '../services/mySvc.svc';
..

export class EditComponent implements OnInit{
    private _colDefs: any;
    constructor(
        private _editCompSvc: Svc
        ){}

    ngOnInit() {
        this._editCompSvc.getColDef().subscribe(
          columns => {
              console.log(columns);
        });
    }

....

But somehow my console.log in edit, not displaying any data. I want to return my columns value here as per i set in my list component. Any idea guys? Thanks in advance.

Module:

import { NgModule } from '@angular/core';
import { routing } from './routes/myroute.route';
import { Svc } from './services/mySvc.svc'

import { ListComponent } from './actions/list.comp';
import { EditComponent } from './actions/edit.comp';

@NgModule({
    imports:
    [
        routing
    ],

    declarations:
    [
        ListComponent,
        EditComponent
    ],

    providers:
    [Svc]
})

export class Module { }


问:
Unable to delete mysql record through PHP
i want to delete the record in mysql database by just clicking on a link but i am unable to accomplish it, i am unable to understand the error.
Here is my code

HTML

```<code><a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete</a>
</code>```

processCategory.php

```<code>    <?php
    require_once '../library/config.php';
    require_once '../library/functions.php';

    checkUser();

    $action = isset($_GET['action']) ? $_GET['action'] : '';
    switch ($action) {

        case 'add' :
            addCategory();
            break;

        case 'delete' :
            deleteCategory();
            break;

        default :
            // if action is not defined or unknown
            // move to main category page
            header('Location: index.php');
    }

 function deleteCategory()
    {
        if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
            $id = (int)$_GET['id'];
        } else {
            header('Location: index.php');
        }

        // delete the products
        $sql = "DELETE FROM tbl_vendors
                WHERE id = $id";
        dbQuery($sql);

        header('Location: ../vendor');
    }

    ?>
</code>```

答:
;">Delete
delete "()" maybe in php get the "($id)"</p>

Body:
i want to delete the record in mysql database by just clicking on a link but i am unable to accomplish it, i am unable to understand the error.
Here is my code

HTML

<a href="processCategory.php?action=delete?id=(<?php echo $id; ?>);">Delete

processCategory.php

    <?php
    require_once '../library/config.php';
    require_once '../library/functions.php';

    checkUser();

    $action = isset($_GET['action']) ? $_GET['action'] : '';
    switch ($action) {

        case 'add' :
            addCategory();
            break;

        case 'delete' :
            deleteCategory();
            break;

        default :
            // if action is not defined or unknown
            // move to main category page
            header('Location: index.php');
    }

 function deleteCategory()
    {
        if (isset($_GET['id']) && (int)$_GET['id'] > 0) {
            $id = (int)$_GET['id'];
        } else {
            header('Location: index.php');
        }

        // delete the products
        $sql = "DELETE FROM tbl_vendors
                WHERE id = $id";
        dbQuery($sql);

        header('Location: ../vendor');
    }

    ?>


问:
Two Class member mapping into new Final class
Note this is not multi-threading case Old value is saved in cache, new value is getting from server and final value is updated-one which will save again in cache.

Their two object of class name

obj->Old values,

obj1-> New values.

Recquried

obj3-> Final Output.

Old Values

```<code>class A{
 String name="abc";
String email="x@gmail.com";
String phone="123456789";
}
</code>```

New Values

```<code>class A{
 String name="xyz";
String email="";
}
</code>```

Want to update old values with new values only when their is some updated content in new values.

As in above case

name is accepted as it changes

email is not accepted as it is empty.

Phone has no value so rejected.

Final output is:

```<code>class A
{
  String name="xyz";
    String email="x@gmail.com";
    String phone="123456789";
}
</code>```

Is their any easy solution to make it simple

答:
```<code>You can make a get property to return the final class like so:

class A {
    String name  ="abc";
    String email ="x@gmail.com";
    String phone ="123456789";

   public A getFinalA(A a){
      if(a.name != null )  name  = (name == a.name ? name : a.name);
      if(a.email != null )  email= (email == a.email ? email : a.email);
      if(a.phone!= null )  phone= (phone== a.phone? phone: a.phone);

      A finalA = new A();
      A.name  = name;
      A.email = email;
      A.phone = phone;
   }
}
</code>```

Body:
Note this is not multi-threading case Old value is saved in cache, new value is getting from server and final value is updated-one which will save again in cache.

Their two object of class name

obj->Old values,

obj1-> New values.

Recquried

obj3-> Final Output.

Old Values

class A{
 String name="abc";
String email="x@gmail.com";
String phone="123456789";
}

New Values

class A{
 String name="xyz";
String email="";
}

Want to update old values with new values only when their is some updated content in new values.

As in above case

name is accepted as it changes

email is not accepted as it is empty.

Phone has no value so rejected.

Final output is:

class A
{
  String name="xyz";
    String email="x@gmail.com";
    String phone="123456789";
}

Is their any easy solution to make it simple


问:
NanoHTTPD How to save uploaded file to sdcard folder
How to save uploaded file to sdcard folder , currently it stores to /data/data/cache folder with filename like "NanoHTTPD-some random number".

I am not able to copy it to any folder location in sdcard.

I would like to save the file to a pre-mentioned folder location in sdcard with the same name as the original file name was uploaded from my html page.

I have tried all sort of codes .But file copy fails all the time.
1)Not able to get correct location of temp file.
2)Not getting original filename that the form was posted with

Here is my implementation .

Please help i am stuck.

```<code>    public class HttpMultimediaServer extends NanoHTTPD {
    private static final String TAG = "HttpMultimediaServer";
    private FileInputStream fileInputStream;

    public HttpMultimediaServer() {
        super(12345);
        this.setTempFileManagerFactory(new ExampleManagerFactory());
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();

        Log.e("handle", "url>>" + uri);

        if (uri.contains(filesOnly)) {
            isfilesOnly = true;
            uri = "/";
        } else
            isfilesOnly = false;

        uri = uri.replace("%20", " ");

        try {
            uri=new String (uri.getBytes ("iso-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }

        File filePathServer = new File(uri);

        if (method==Method.POST) {

            try {

                Map<String, String> hdrs=session.getHeaders();
                Map<String, String> params=session.getParms();

                Map<String, String> files = new HashMap<String, String>();
                session.parseBody(files);

                Set<String> keys = files.keySet();
                for(String key: keys){
                    String name = key;
                    String loaction = files.get(key);

                    File tempfile = new File(loaction);

                String tempFileName = files.get(loaction).toString();
                File fileToMove = new File(tempFileName);

    // temp file path returned by NanoHTTPD

                String p =Environment.getExternalStorageDirectory().getPath();
                String newFile = p + "/LICENSE.txt";
                File nf = new File(newFile); // I want to move file here

                if (fileToMove.canWrite()) {
                    boolean success = fileToMove.renameTo(nf);
                    if (success == true) {
                        // LOG to console
                        Log.i("FILE_MOVED_TO", newFile);
                    } else {
                        Log.e("FILE_MOVE_ERROR", tempFileName);
                    }
                } else {
                    Log.e("PERMISSION_ERROR_TEMP_FILE", tempFileName);
                }

                }
                uploadstatus = UPLOAD_SUCESS;

                return new Response("UPLOAD_SUCESS");

            } catch (Exception e) {
                e.printStackTrace();
                uploadstatus = UPLOAD_FAIL;

                return new Response("UPLOAD_FAIL");

            }

        }

    }

    public static void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

    public static void copyFile(File src, File dst) throws IOException
    {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try
        {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        }
        finally
        {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }

    private Response getFullResponse(String mimeType,String filePath) throws FileNotFoundException {
    //        cleanupStreams();
        fileInputStream = new FileInputStream(filePath);
        return new Response(Response.Status.OK, mimeType, fileInputStream);
    }

    private Response getPartialResponse(String mimeType, String rangeHeader,String filePath) throws IOException {
        File file = new File(filePath);
        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        long fileLength = file.length();
        long start, end;
        if (rangeValue.startsWith("-")) {
            end = fileLength - 1;
            start = fileLength - 1
                    - Long.parseLong(rangeValue.substring("-".length()));
        } else {
            String[] range = rangeValue.split("-");
            start = Long.parseLong(range[0]);
            end = range.length > 1 ? Long.parseLong(range[1])
                    : fileLength - 1;
        }
        if (end > fileLength - 1) {
            end = fileLength - 1;
        }
        if (start <= end) {
            long contentLength = end - start + 1;
    //            cleanupStreams();
            fileInputStream = new FileInputStream(file);
                //noinspection ResultOfMethodCallIgnored
            fileInputStream.skip(start);
            Response response = new Response(Response.Status.PARTIAL_CONTENT, mimeType, fileInputStream);
            response.addHeader("Content-Length", contentLength + "");
            response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            response.addHeader("Content-Type", mimeType);
            return response;
        } else {
            return new Response(Response.Status.RANGE_NOT_SATISFIABLE, "text/html", rangeHeader);
        }
    }
    int UPLOAD_SUCESS = 1;
    int UPLOAD_FAIL = -1;
    int UPLOAD_NO = 0;
    int uploadstatus;
    boolean isfilesOnly;
    String filesOnly = "?filesOnly=1";
    ArrayList<CLocalFile> list;
    StringBuilder sb;

    public void walkdir(File dir) {

        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                // checking if it is a directory
                if (listFile[i].isDirectory()) {
                    if (isfilesOnly)
                        walkdir(listFile[i]);
                    else {
                        CLocalFile f = new CLocalFile();
                        f.setName(listFile[i].getName());
                        f.setData(listFile[i].getAbsolutePath());
                        f.setSize("Folder");
                        list.add(f);
                        continue;
                    }
                }
                    // checking the file extension if it is a file
                String fileName = listFile[i].getName();

                String extension = "";

                int e = fileName.lastIndexOf('.');
                if (e > 0) {
                    extension = fileName.substring(e + 1);
                }
                if (!isfilesOnly
                        || CollabUtility.video_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))
                        || CollabUtility.document_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))
                        || CollabUtility.audio_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))) {
                    CLocalFile f = new CLocalFile();
                    f.setName(fileName);
                    String mb = "Bytes";
                    double size = listFile[i].length();
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "KB";
                    }
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "MB";
                    }
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "GB";
                    }
                    size = Math.floor(size * 100 + 0.5) / 100;
                    f.setSize(size + " " + mb);
                    f.setData(listFile[i].getAbsolutePath());
                    list.add(f);
                }
            }
        }
    }

    void listofMedia(File file) {
        list = new ArrayList<CLocalFile>();
        walkdir(file);
        // now create the html page
        String style = "<style>" + "html {background-color:#eeeeee;} "
                + "body { background-color:#FFFFFF; "
                + "font-family:Tahoma,Arial,Helvetica,sans-serif; "
                + "font-size:18x; " + "border:3px " + "groove #006600; "
                + "padding:15px; } " + "</style>";

        String script = "<script language='javascript'>"
                + "function clickit(state) {"
                + "if(state==true){document.getElementById('filesonly').checked="
                + "! document.getElementById('filesonly').checked}"
                + "if ( document.getElementById('filesonly').checked == false ){"
                + "var l=window.location.href;" + "l=l.replace('" + filesOnly
                + "', '');" + "window.location=l;" + "}"
                + "else{var l=window.location.href;"
                + "window.location=String.concat(l,'" + filesOnly + "')" + "}"
                + "}</script>";
        Log.d("check", script);

        sb = new StringBuilder();
        sb.append("<html>");
        sb.append("<head>");
        sb.append("<title>Files from device</title>");
        sb.append(style);
            // sb.append("<script language='javascript'>"
            // + "function clickit() {"
            // + "if ( document.getElementById('filesonly').checked == false ){"
            // + "var l=window.location.href;" + "l=l.replace('" + filesOnly
            // + "', '');" + "window.location=l;" + "}"
            // + "else{var l=window.location.href;"
            // + "window.location=String.concat(l,'" + filesOnly + "')" + "}"
            // + "}</script>");
        sb.append(script);
        sb.append("</head>");

        sb.append("<body alink=\"blue\" vlink=\"blue\">");

        Log.d("check", sb.toString());

            // if(true)
            // return;
            // form upload
        sb.append("<h3>File Upload:</h3>");
        sb.append("Select a file to upload: <br/>");
        sb.append("<form action=\"\" method=\"post\"  enctype=\"multipart/form-data\">");
        sb.append("<input type=\"file\" name=\"uploadfile\" size=\"50\" />");
        sb.append("<input type=\"submit\" value=\"Upload File\" />");
        sb.append("</form>");

        if (uploadstatus == UPLOAD_FAIL)
            sb.append("<h3><font color='red'>The upload was failed</font></h3>");
        else if (uploadstatus == UPLOAD_SUCESS)
            sb.append("<h3><font color='red'>The upload was successfull</font></h3>");

        // if files are there or not
        if (list != null && list.size() != 0) {
            sb.append("<h3>The following files are hosted live from ");
            if (!isfilesOnly)
                sb.append("<font color='blue'>" + file.getName()
                        + "</font> folder of ");
            sb.append("the device</h3>");
        } else {
            sb.append("<h3>Couldn't find any file from <font color='blue'>"
                    + file.getName() + "</font> folder of the device</h3>");
        }

        // checkbox
        if (isfilesOnly)
            sb.append("<input type=\"checkbox\" onchange='clickit(false);' checked='true' id=\"filesonly\" />"
                    + "<asd onclick='clickit(true);' style=\"cursor:default;\">"
                    + "Show only relevant Files (Audio, Video and Documents)</asd>");
        else
            sb.append("<input type=\"checkbox\" onchange='clickit(false);' id=\"filesonly\" />"
                    + "<asd onclick='clickit(true);' style=\"cursor:default;\">"
                    + "Show only relevant Files (Audio, Video and Documents)</asd>");

            // table of files
        sb.append("<table cellpadding='5px' align=''>");

           // showing path URLs if not only files
        if (!isfilesOnly) {
            ArrayList<File> href = new ArrayList<File>();
            File parent = new File(file.getPath());
            while (parent != null) {
                href.add(parent);
                    // pointing to the next parent
                parent = parent.getParentFile();
            }

            sb.append("<tr>");
            sb.append("<td colspan=2><b>");
            sb.append("<a href='" + file.getParent() + "'>");
            sb.append("UP");
            sb.append("</a>");

                // printing the whole structure
            String path = "";
            for (int i = href.size() - 2; i >= 0; --i) {
                path = href.get(i).getPath();
                if (isfilesOnly)
                    path += filesOnly;
                sb.append("  =>  <a href='" + path + "'>");
                sb.append(href.get(i).getName());
                sb.append("</a>");
            }
            sb.append("</b></td>");
            sb.append("</tr>");
        }

        sb.append("<tr>");

        sb.append("<td>");
        sb.append("<b>File Name</b>");
        sb.append("</td>");

        sb.append("<td>");
        sb.append("<b>Size / Type</b>");
        sb.append("</td>");

        sb.append("<tr>");

            // sorting the list
        Collections.sort(list);

            // showing the list of files
        for (CLocalFile f : list) {
            String data = f.getData();
            if (isfilesOnly)
                data += filesOnly;
            sb.append("<tr>");

            sb.append("<td>");
            sb.append("<a href='" + data + "'>");
            sb.append(f.getName());
            sb.append("</a>");
            sb.append("</td>");

            sb.append("<td align=\"right\">");
            sb.append(f.getSize());
            sb.append("</td>");

            sb.append("</tr>");
        }
        sb.append("</table>");
        sb.append("</body>");
        sb.append("</html>");
    }

    private static class ExampleManagerFactory implements TempFileManagerFactory {
        @Override
        public TempFileManager create() {
            return new ExampleManager();
        }
    }

    private static class ExampleManager implements TempFileManager {
        private final String tmpdir;
        private final List<TempFile> tempFiles;

        private ExampleManager() {
            tmpdir = System.getProperty("java.io.tmpdir");
    //             tmpdir = System.getProperty("/sdcard");

            tempFiles = new ArrayList<TempFile>();
        }

        @Override
        public TempFile createTempFile() throws Exception {
            DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
            tempFiles.add(tempFile);
            System.out.println("Created tempFile: " + tempFile.getName());
            return tempFile;
        }

        @Override
        public void clear() {
            if (!tempFiles.isEmpty()) {
                System.out.println("Cleaning up:");
            }
            for (TempFile file : tempFiles) {
                try {
                    System.out.println("   "+file.getName());
                    file.delete();
                } catch (Exception ignored) {}
            }
            tempFiles.clear();
        }
    }

}
</code>```

答:
Maybe late, but just for latecommers just like me.

Explained before, the client use okhttp upload a file just like the follow code：

```<code>RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
    //sourceFile is a File as you know
            .addFormDataPart("image_file_1", "logo-square1.png", RequestBody.create(MediaType.parse("image/png"), sourceFile))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = client.newCall(request).execute();
</code>```

The follow code is what you want

```<code>@Override
public Response serve(IHTTPSession session) {

    Method method = session.getMethod();
    // ▼ 1、parse post body ▼
    Map<String, String> files = new HashMap<>();
    if (Method.POST.equals(method) || Method.PUT.equals(method)) {
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            return getResponse("Internal Error IO Exception: " + ioe.getMessage());
        } catch (ResponseException re) {
            return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        }
    }
    //after the body parsed, by default nanoHTTPD will save the file to cache and put it into params( "image_file_1" as key and the value is "logo-square1.png");
    //files key is just like "image_file_1", and the value is nanoHTTPD's template file path in cache
    // ▲ 1、parse post body ▲

    // ▼ 2、copy file to target path xiaoyee ▼
    Map<String, String> params = session.getParms();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        final String paramsKey = entry.getKey();
        if (paramsKey.contains("image_file_1")) {
            final String tmpFilePath = files.get(paramsKey);
            final String fileName = paramsKey;
            final File tmpFile = new File(tmpFilePath);
            final File targetFile = new File(mCurrentDir + fileName);
            LogUtil.log("copy file now, source file path: %s,target file path:%s", tmpFile.getAbsoluteFile(), targetFile.getAbsoluteFile());
            //a copy file method just what you like
            copyFile(tmpFile, targetFile);

            //maybe you should put the follow code out
            return getResponse("Success");
        }
    }
    // ▲ 2、copy file to target path xiaoyee ▲

    return getResponse("Error 404: File not found");
}
</code>```

Body:
How to save uploaded file to sdcard folder , currently it stores to /data/data/cache folder with filename like "NanoHTTPD-some random number".

I am not able to copy it to any folder location in sdcard.

I would like to save the file to a pre-mentioned folder location in sdcard with the same name as the original file name was uploaded from my html page.

I have tried all sort of codes .But file copy fails all the time.
1)Not able to get correct location of temp file.
2)Not getting original filename that the form was posted with

Here is my implementation .

Please help i am stuck.

    public class HttpMultimediaServer extends NanoHTTPD {
    private static final String TAG = "HttpMultimediaServer";
    private FileInputStream fileInputStream;

    public HttpMultimediaServer() {
        super(12345);
        this.setTempFileManagerFactory(new ExampleManagerFactory());
    }

    @Override
    public Response serve(IHTTPSession session) {
        Method method = session.getMethod();
        String uri = session.getUri();

        Log.e("handle", "url>>" + uri);

        if (uri.contains(filesOnly)) {
            isfilesOnly = true;
            uri = "/";
        } else
            isfilesOnly = false;

        uri = uri.replace("%20", " ");

        try {
            uri=new String (uri.getBytes ("iso-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e2) {
            e2.printStackTrace();
        }

        File filePathServer = new File(uri);

        if (method==Method.POST) {

            try {

                Map<String, String> hdrs=session.getHeaders();
                Map<String, String> params=session.getParms();

                Map<String, String> files = new HashMap<String, String>();
                session.parseBody(files);

                Set<String> keys = files.keySet();
                for(String key: keys){
                    String name = key;
                    String loaction = files.get(key);

                    File tempfile = new File(loaction);

                String tempFileName = files.get(loaction).toString();
                File fileToMove = new File(tempFileName);

    // temp file path returned by NanoHTTPD

                String p =Environment.getExternalStorageDirectory().getPath();
                String newFile = p + "/LICENSE.txt";
                File nf = new File(newFile); // I want to move file here

                if (fileToMove.canWrite()) {
                    boolean success = fileToMove.renameTo(nf);
                    if (success == true) {
                        // LOG to console
                        Log.i("FILE_MOVED_TO", newFile);
                    } else {
                        Log.e("FILE_MOVE_ERROR", tempFileName);
                    }
                } else {
                    Log.e("PERMISSION_ERROR_TEMP_FILE", tempFileName);
                }

                }
                uploadstatus = UPLOAD_SUCESS;

                return new Response("UPLOAD_SUCESS");

            } catch (Exception e) {
                e.printStackTrace();
                uploadstatus = UPLOAD_FAIL;

                return new Response("UPLOAD_FAIL");

            }

        }

    }

    public static void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }

    public static void copyFile(File src, File dst) throws IOException
    {
        FileChannel inChannel = new FileInputStream(src).getChannel();
        FileChannel outChannel = new FileOutputStream(dst).getChannel();
        try
        {
            inChannel.transferTo(0, inChannel.size(), outChannel);
        }
        finally
        {
            if (inChannel != null)
                inChannel.close();
            if (outChannel != null)
                outChannel.close();
        }
    }

    private Response getFullResponse(String mimeType,String filePath) throws FileNotFoundException {
    //        cleanupStreams();
        fileInputStream = new FileInputStream(filePath);
        return new Response(Response.Status.OK, mimeType, fileInputStream);
    }

    private Response getPartialResponse(String mimeType, String rangeHeader,String filePath) throws IOException {
        File file = new File(filePath);
        String rangeValue = rangeHeader.trim().substring("bytes=".length());
        long fileLength = file.length();
        long start, end;
        if (rangeValue.startsWith("-")) {
            end = fileLength - 1;
            start = fileLength - 1
                    - Long.parseLong(rangeValue.substring("-".length()));
        } else {
            String[] range = rangeValue.split("-");
            start = Long.parseLong(range[0]);
            end = range.length > 1 ? Long.parseLong(range[1])
                    : fileLength - 1;
        }
        if (end > fileLength - 1) {
            end = fileLength - 1;
        }
        if (start <= end) {
            long contentLength = end - start + 1;
    //            cleanupStreams();
            fileInputStream = new FileInputStream(file);
                //noinspection ResultOfMethodCallIgnored
            fileInputStream.skip(start);
            Response response = new Response(Response.Status.PARTIAL_CONTENT, mimeType, fileInputStream);
            response.addHeader("Content-Length", contentLength + "");
            response.addHeader("Content-Range", "bytes " + start + "-" + end + "/" + fileLength);
            response.addHeader("Content-Type", mimeType);
            return response;
        } else {
            return new Response(Response.Status.RANGE_NOT_SATISFIABLE, "text/html", rangeHeader);
        }
    }
    int UPLOAD_SUCESS = 1;
    int UPLOAD_FAIL = -1;
    int UPLOAD_NO = 0;
    int uploadstatus;
    boolean isfilesOnly;
    String filesOnly = "?filesOnly=1";
    ArrayList<CLocalFile> list;
    StringBuilder sb;

    public void walkdir(File dir) {

        File listFile[] = dir.listFiles();
        if (listFile != null) {
            for (int i = 0; i < listFile.length; i++) {
                // checking if it is a directory
                if (listFile[i].isDirectory()) {
                    if (isfilesOnly)
                        walkdir(listFile[i]);
                    else {
                        CLocalFile f = new CLocalFile();
                        f.setName(listFile[i].getName());
                        f.setData(listFile[i].getAbsolutePath());
                        f.setSize("Folder");
                        list.add(f);
                        continue;
                    }
                }
                    // checking the file extension if it is a file
                String fileName = listFile[i].getName();

                String extension = "";

                int e = fileName.lastIndexOf('.');
                if (e > 0) {
                    extension = fileName.substring(e + 1);
                }
                if (!isfilesOnly
                        || CollabUtility.video_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))
                        || CollabUtility.document_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))
                        || CollabUtility.audio_pattern.contains(extension
                                .toLowerCase(Locale.ENGLISH))) {
                    CLocalFile f = new CLocalFile();
                    f.setName(fileName);
                    String mb = "Bytes";
                    double size = listFile[i].length();
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "KB";
                    }
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "MB";
                    }
                    if (size > 1024) {
                        size = size / 1024;
                        mb = "GB";
                    }
                    size = Math.floor(size * 100 + 0.5) / 100;
                    f.setSize(size + " " + mb);
                    f.setData(listFile[i].getAbsolutePath());
                    list.add(f);
                }
            }
        }
    }

    void listofMedia(File file) {
        list = new ArrayList<CLocalFile>();
        walkdir(file);
        // now create the html page
        String style = "";

        String script = "";
        Log.d("check", script);

        sb = new StringBuilder();
        sb.append("");
        sb.append("");
        sb.append("<title>Files from device</title>");
        sb.append(style);
            // sb.append("");
        sb.append(script);
        sb.append("");

        sb.append("");

        Log.d("check", sb.toString());

            // if(true)
            // return;
            // form upload
        sb.append("
File Upload:
");
        sb.append("Select a file to upload:
");
        sb.append("<form action=\"\" method=\"post\"  enctype=\"multipart/form-data\">");
        sb.append("<input type=\"file\" name=\"uploadfile\" size=\"50\" />");
        sb.append("<input type=\"submit\" value=\"Upload File\" />");
        sb.append("</form>");

        if (uploadstatus == UPLOAD_FAIL)
            sb.append("
The upload was failed
");
        else if (uploadstatus == UPLOAD_SUCESS)
            sb.append("
The upload was successfull
");

        // if files are there or not
        if (list != null && list.size() != 0) {
            sb.append("
The following files are hosted live from ");
            if (!isfilesOnly)
                sb.append("" + file.getName()
                        + " folder of ");
            sb.append("the device
");
        } else {
            sb.append("
Couldn't find any file from "
                    + file.getName() + " folder of the device
");
        }

        // checkbox
        if (isfilesOnly)
            sb.append("<input type=\"checkbox\" onchange='clickit(false);' checked='true' id=\"filesonly\" />"
                    + "<asd onclick='clickit(true);' style=\"cursor:default;\">"
                    + "Show only relevant Files (Audio, Video and Documents)</asd>");
        else
            sb.append("<input type=\"checkbox\" onchange='clickit(false);' id=\"filesonly\" />"
                    + "<asd onclick='clickit(true);' style=\"cursor:default;\">"
                    + "Show only relevant Files (Audio, Video and Documents)</asd>");

            // table of files
        sb.append("
");

           // showing path URLs if not only files
        if (!isfilesOnly) {
            ArrayList<File> href = new ArrayList<File>();
            File parent = new File(file.getPath());
            while (parent != null) {
                href.add(parent);
                    // pointing to the next parent
                parent = parent.getParentFile();
            }

            sb.append("
");
            sb.append("");
            sb.append("");
            sb.append("UP");
            sb.append("");

                // printing the whole structure
            String path = "";
            for (int i = href.size() - 2; i >= 0; --i) {
                path = href.get(i).getPath();
                if (isfilesOnly)
                    path += filesOnly;
                sb.append("  =>  ");
                sb.append(href.get(i).getName());
                sb.append("");
            }
            sb.append("	");
            sb.append("
");
        }

        sb.append("
");

        sb.append("");
        sb.append("File Name");
        sb.append("	");

        sb.append("");
        sb.append("Size / Type");
        sb.append("	");

        sb.append("
");

            // sorting the list
        Collections.sort(list);

            // showing the list of files
        for (CLocalFile f : list) {
            String data = f.getData();
            if (isfilesOnly)
                data += filesOnly;
            sb.append("
");

            sb.append("");
            sb.append("");
            sb.append(f.getName());
            sb.append("");
            sb.append("	");

            sb.append("");
            sb.append(f.getSize());
            sb.append("	");

            sb.append("
");
        }
        sb.append("
");
        sb.append("");
        sb.append("");
    }

    private static class ExampleManagerFactory implements TempFileManagerFactory {
        @Override
        public TempFileManager create() {
            return new ExampleManager();
        }
    }

    private static class ExampleManager implements TempFileManager {
        private final String tmpdir;
        private final List<TempFile> tempFiles;

        private ExampleManager() {
            tmpdir = System.getProperty("java.io.tmpdir");
    //             tmpdir = System.getProperty("/sdcard");

            tempFiles = new ArrayList<TempFile>();
        }

        @Override
        public TempFile createTempFile() throws Exception {
            DefaultTempFile tempFile = new DefaultTempFile(tmpdir);
            tempFiles.add(tempFile);
            System.out.println("Created tempFile: " + tempFile.getName());
            return tempFile;
        }

        @Override
        public void clear() {
            if (!tempFiles.isEmpty()) {
                System.out.println("Cleaning up:");
            }
            for (TempFile file : tempFiles) {
                try {
                    System.out.println("   "+file.getName());
                    file.delete();
                } catch (Exception ignored) {}
            }
            tempFiles.clear();
        }
    }

}

Body:
Maybe late, but just for latecommers just like me.

Explained before, the client use okhttp upload a file just like the follow code：

RequestBody requestBody = new MultipartBody.Builder()
            .setType(MultipartBody.FORM)
    //sourceFile is a File as you know
            .addFormDataPart("image_file_1", "logo-square1.png", RequestBody.create(MediaType.parse("image/png"), sourceFile))
            .build();

    Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Response response = client.newCall(request).execute();

The follow code is what you want

@Override
public Response serve(IHTTPSession session) {

    Method method = session.getMethod();
    // ▼ 1、parse post body ▼
    Map<String, String> files = new HashMap<>();
    if (Method.POST.equals(method) || Method.PUT.equals(method)) {
        try {
            session.parseBody(files);
        } catch (IOException ioe) {
            return getResponse("Internal Error IO Exception: " + ioe.getMessage());
        } catch (ResponseException re) {
            return newFixedLengthResponse(re.getStatus(), MIME_PLAINTEXT, re.getMessage());
        }
    }
    //after the body parsed, by default nanoHTTPD will save the file to cache and put it into params( "image_file_1" as key and the value is "logo-square1.png");
    //files key is just like "image_file_1", and the value is nanoHTTPD's template file path in cache
    // ▲ 1、parse post body ▲

    // ▼ 2、copy file to target path xiaoyee ▼
    Map<String, String> params = session.getParms();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        final String paramsKey = entry.getKey();
        if (paramsKey.contains("image_file_1")) {
            final String tmpFilePath = files.get(paramsKey);
            final String fileName = paramsKey;
            final File tmpFile = new File(tmpFilePath);
            final File targetFile = new File(mCurrentDir + fileName);
            LogUtil.log("copy file now, source file path: %s,target file path:%s", tmpFile.getAbsoluteFile(), targetFile.getAbsoluteFile());
            //a copy file method just what you like
            copyFile(tmpFile, targetFile);

            //maybe you should put the follow code out
            return getResponse("Success");
        }
    }
    // ▲ 2、copy file to target path xiaoyee ▲

    return getResponse("Error 404: File not found");
}


问:
JSON and struct composition in Go
I have hierarchical structure similar to this Network -> Serie -> Season -> Episodes. This is a simplified version my real hierarchy is 7 levels deep.

I need to decode/encode these objects with the following JSON:

```<code>Network:
{
  id: 1,
  name: 'Fox'
}

Series:
{
   id: 2,
   name: 'The Simpsons',
   network: {
      id: 1,
      name: 'Fox'
   }
}

Season:
{
   id: 3,
   name: 'Season 3',
   network: {
      id: 1,
      name: 'Fox'

   },
   series: {
      id: 2,
      name: 'The Simpsons'
   }
}

Episode:
{
   id: 4,
   name: 'Pilot',
   network: {
      id: 1,
      name: 'Fox'
   },
   series: {
      id: 2,
      name: 'The Simpsons'
   },
   season: {
      id: 3,
      name: 'Season 3'
   }
}
</code>```

I tried composing my objects like these:

```<code>type Base struct {
  ID   string `json:"id"`
  Name string `json:"name"`
}

type Network struct {
  Base
}

type Series struct {
  Network // Flatten out all Network properties (ID + Name)
  Network Base `json:"network"`
}

type Season struct {
  Series  // Flatten out all Series properties (ID + Name + Network)
  Series Base `json:"series"`
}

type Episode struct {
  Season  // Flatten out all Season properties (ID + Name + Network + Series)
  Season Season `json:"season"`
}
</code>```

Of course it doesn't work due "duplicate field error". In addition the JSON result would be deeply nested.
In classic OOP this is fairly easy using normal inheritance, in prototype languages it's also doable (Object.create/Mixins)

Is there an elegant way of do this with golang? I would prefer to keep code DRY.

答:
Why not rename the propriety? But keep the json tags, and go will marshal/unmarshal based on that tag </p>

```<code>type Base struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

type Network struct {
    Base
}

type Series struct {
    Network          // Flatten out all Network properties (ID + Name)
    NetworkBase Base `json:"network"`
}

type Season struct {
    Series          // Flatten out all Series properties (ID + Name + Network)
    SeriesBase Base `json:"series"`
}

type Episode struct {
    Season              // Flatten out all Season properties (ID + Name + Network + Series)
    SeasonBase Base `json:"season"`
}
</code>```

Title: JSON and struct composition in Go

Body:
I have hierarchical structure similar to this Network -> Serie -> Season -> Episodes. This is a simplified version my real hierarchy is 7 levels deep.

I need to decode/encode these objects with the following JSON:

Network:
{
  id: 1,
  name: 'Fox'
}

Series:
{
   id: 2,
   name: 'The Simpsons',
   network: {
      id: 1,
      name: 'Fox'
   }
}

Season:
{
   id: 3,
   name: 'Season 3',
   network: {
      id: 1,
      name: 'Fox'

   },
   series: {
      id: 2,
      name: 'The Simpsons'
   }
}

Episode:
{
   id: 4,
   name: 'Pilot',
   network: {
      id: 1,
      name: 'Fox'
   },
   series: {
      id: 2,
      name: 'The Simpsons'
   },
   season: {
      id: 3,
      name: 'Season 3'
   }
}

I tried composing my objects like these:

type Base struct {
  ID   string `json:"id"`
  Name string `json:"name"`
}

type Network struct {
  Base
}

type Series struct {
  Network // Flatten out all Network properties (ID + Name)
  Network Base `json:"network"`
}

type Season struct {
  Series  // Flatten out all Series properties (ID + Name + Network)
  Series Base `json:"series"`
}

type Episode struct {
  Season  // Flatten out all Season properties (ID + Name + Network + Series)
  Season Season `json:"season"`
}

Of course it doesn't work due "duplicate field error". In addition the JSON result would be deeply nested.
In classic OOP this is fairly easy using normal inheritance, in prototype languages it's also doable (Object.create/Mixins)

Is there an elegant way of do this with golang? I would prefer to keep code DRY.

Body:
Why not rename the propriety? But keep the json tags, and go will marshal/unmarshal based on that tag

type Base struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

type Network struct {
    Base
}

type Series struct {
    Network          // Flatten out all Network properties (ID + Name)
    NetworkBase Base `json:"network"`
}

type Season struct {
    Series          // Flatten out all Series properties (ID + Name + Network)
    SeriesBase Base `json:"series"`
}

type Episode struct {
    Season              // Flatten out all Season properties (ID + Name + Network + Series)
    SeasonBase Base `json:"season"`
}


问:
File::copyDirectory return nothing
I'm able to copy files using Storage::copy but when i tried to copy folder with File::copyDirectory, it doesn't change anything. Why is that?

My Code:

```<code> public function pasteDocument(Request $request)
    {
      if(Session::get('clipboard') == "copy"){
      // copy to disk
          File::copyDirectory('public\img', 'public\js', true);
         }
      return redirect()->back();
    }
</code>```

答:
You need to pass full paths to copyDirectory():

```<code>File::copyDirectory(public_path('img'), public_path('js'), true);
</code>```

Title: File::copyDirectory return nothing

Body:
I'm able to copy files using Storage::copy but when i tried to copy folder with File::copyDirectory, it doesn't change anything. Why is that?

My Code:

 public function pasteDocument(Request $request)
    {
      if(Session::get('clipboard') == "copy"){
      // copy to disk
          File::copyDirectory('public\img', 'public\js', true);
         }
      return redirect()->back();
    }

Body:
You need to pass full paths to copyDirectory():

File::copyDirectory(public_path('img'), public_path('js'), true);


问:
Stack smashing detected when allocating array C
As the title explains the problem. In this function in my program , whenever I allocate a certain size in the array I get huge chunks of error code on my terminal. The array gets copied properly and everything but right after printing it the program crashes. The purpose of the program is to read from file and then store each line in an array index. Your help is much appreciated. Thanks

The array is declared as a pointer in the main and then it is dynamically allocated inside.

```<code>    void read_file_into_array(char **filearray, FILE * fp)
        {
            /* use get line to count # of lines */
            int numlines = -1;
            numlines = linecount(fp);
            size_t size = 50;
            char *buffer;

            buffer = (char *)malloc(size * sizeof(char));
            if (buffer == NULL) {
                perror("Unable to allocate buffer");
                exit(1);
            }

            if (numlines < 0) {
                fprintf(stderr, "error: unable to determine file length.\n");
                return;
            }

            printf(" number of lines counted are ; %d\n", numlines);

            /* allocate array of size numlines + 1 */

            if (!(*filearray = (char *)malloc(numlines + 1 * sizeof(char)))) {
                fprintf(stderr, "error: virtual memory exhausted.\n");
                return;
            }

            fseek(fp, 0, SEEK_SET);
            for (int i = 0; i < numlines; i++) {
                if (!feof(fp)) {
                    fgets(buffer, size, fp);
                    filearray[i] = (char *)malloc(size * sizeof(char *));
                    strcpy(filearray[i], buffer);
                    printf("buffer at %d : %s\n", i, buffer);
                    printf("array at %d : %s\n", i, filearray[i]);
                }
            }
            free(buffer);
        }

        /* THIS IS MY MAIN BELOW */

        int main (int argc, char **argv)

        {
        FILE *fp = NULL;
        char*  array;

        /* open file for reading (default stdin) */
            fp = argc > 1 ? fopen (argv[1], "r") : stdin;

            if (!fp) {  /* validate file open */
                fprintf (stderr, "error: file open failed '%s'\n", argv[1]);
                return 1;
            }

            read_file_into_array (&array, fp);

        if (fp != stdout)
                if (fclose (fp) == EOF) {
                    fprintf (stderr, "error: fclose() returned EOF\n");
                    return 1;
                }

        return 0;
        }

    /* MY LNE COUNT FUNCITON */
    int linecount(FILE *fp) {
    char buff[MAXLINE];
    int count = 0;

    while(fgets(buff,MAXLINE,fp) != NULL) {
    count++;
    }
    return count;
}
</code>```

答:
OK, let's get you sorted out. First, to pass a pointer to pointer to char as a parameter to a function, allocate within the function and have the results available back in the calling function (without more), you must pass the address of the pointer to pointer to char. Otherwise, the function receives a copy and any changes made in the function are not available back in the caller (main here) because the copy is lost (the address to the start of the allocated block is lost) when the function returns.

Passing the address of the pointer to pointer to char means you have to become a 3-STAR Programmer (it is not a compliment). A better way is to not pass the pointer at all, simply allocate within the function and return a pointer to the caller (but there are some cases where you will still need to pass it as a parameter, so that is shown below)

The program below will read any text file passed as the first argument (or it will read from stdin if no argument is given). It will dynamically allocate pointers and needed (in MAXL blocks rather than one-at-a-time which is highly inefficient). It will allocate (and reallocate) lines as required to accommodate lines of any length. It uses a fixed buffer of MAXC chars to read continually until a complete line is read saving the offset to the position in the current line to append subsequent reads as required.

Finally after reading the file, it will print the text and associated line number to stdout, and free all memory allocated before exiting. Look it over and let me know if you have any questions:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { MAXL = 32, MAXC = 1024 };

char **read_file_into_buf (char ***buf, FILE *fp, int *nlines);

int main (int argc, char **argv) {

    char **buf = NULL;  /* buffer to hold lines of file */
    int n;              /* number of lines read */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    if (read_file_into_buf (&buf, fp, &n)) {        /* read file into buf  */
        for (int i = 0; i < n; i++) {               /* loop over all lines */
            printf ("line[%3d]: %s\n", i, buf[i]);  /* output line */
            free (buf[i]);      /* free line */
        }
        free (buf);             /* free buffer */
    }

    if (fp != stdin) fclose (fp);     /* close file if not stdin */

    return 0;
}

/** read text file from 'fp' into 'buf' update 'nlines'.
 *  Being a 3-STAR Programmer, is NOT a compliment. However,
 *  to pass a pointer to pointer to char as a parameter and
 *  allocate within the function, it is required. You must
 *  pass the address of buf from main otherwise the function
 *  recieves a copy whose allocation is lost on return. A better
 *  approach is to simply assign the return in 'main' and not
 *  pass buf at all.
 */
char **read_file_into_buf (char ***buf, FILE *fp, int *nlines)
{
    /* current allocation, current index, and offset (if less
     * than a whole line is read into line on fgets call), and
     * eol indicates '\n' present.
     */
    size_t n = MAXL, idx = 0, offset = 0, eol = 0;
    char line[MAXC] = "";   /* temp buffer for MAXC chars */
    void *tmp = NULL;       /* pointer for realloc */

    /* validate address, file ptr & nlines address */
    if (!buf || !fp || !nlines) {
        fprintf (stderr, "error; invalid parameter.\n");
        return NULL;
    }

    /* allocate initial MAXL pointers, calloc used to avoid valgrind
     * warning about basing a conditional jump on uninitialized value.
     * calloc allocates and initializes.
     */
    if (!(*buf = calloc (sizeof *buf, MAXL))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return NULL;
    }

    while (fgets (line, MAXC, fp))  /* read every line in file */
    {
        /* save offset from prior read (if any), get len */
        size_t end = offset, len = strlen (line);

        if (len && line[len - 1] == '\n') { /* test for new line */
            line[--len] = 0;                /* overwrite with nul */
            offset = 0;                     /* zero offset, all read */
            eol = 1;                        /* POSIX eol present */
        }
        else {
            line[len] = 0;  /* nul-terminate */
            offset += len;  /* short read, save offset to last char */
            eol = 0;        /* no POSIX eol */
        }

        /* allocate/reallocate for current line + nul-byte */
        tmp = realloc ((*buf)[idx], sizeof ***buf * (end + len + 1));
        if (!tmp) {
            fprintf (stderr, "error: realloc, memory exhausted.\n");
            return *buf;  /* return current buf */
        }
        (*buf)[idx] = tmp;  /* assign block to current index */
        strcpy ((*buf)[idx] + end, line);  /* copy line to block */

        if (!eol) continue;   /* chars remain in line, go read them */

        if (++idx == n) {   /* check pointer allocation, realloc as needed */
            tmp = realloc (*buf, sizeof **buf * (n + MAXL));
            if (!tmp) {
                fprintf (stderr, "error: realloc buf, memory exhausted.\n");
                return *buf;
            }
            *buf = tmp; /* assign new block to *buf */
            memset (*buf + n, 0, sizeof **buf * MAXL);  /* zero new memory */
            n += MAXL;  /* update the current number of ptrs allocated */
        }
        *nlines = idx;  /* update the number of lines read */
    }
    if (!eol) {         /* protect against file with no POSIX ending '\n' */
        idx++;          /* account for final line */
        *nlines = idx;  /* update nlines */
    }

    /* final realloc to size buf to exactly fit number of lines */
    tmp = realloc (*buf, sizeof **buf * (idx));
    if (!tmp)   /* if it fails, return current buf */
        return *buf;

    *buf = tmp; /* assign reallocated block to buf */

    return *buf;
}
</code>```

Note: zeroing the new pointers allocated with memset (*buf + n, 0, sizeof **buf * MAXL); is optional, but it eliminates valgrind warnings about basing a conditional jump on an uninitialized value, just as with calloc/malloc of the initial pointers. There is no option to zero with realloc, so a separate call to memset is required.

Example Use/Output

```<code>$ ./bin/fgets_readfile < dat/damages.txt
line[  0]: Personal injury damage awards are unliquidated
line[  1]: and are not capable of certain measurement; thus, the
line[  2]: jury has broad discretion in assessing the amount of
line[  3]: damages in a personal injury case. Yet, at the same
line[  4]: time, a factual sufficiency review insures that the
line[  5]: evidence supports the jury's award; and, although
line[  6]: difficult, the law requires appellate courts to conduct
line[  7]: factual sufficiency reviews on damage awards in
line[  8]: personal injury cases. Thus, while a jury has latitude in
line[  9]: assessing intangible damages in personal injury cases,
line[ 10]: a jury's damage award does not escape the scrutiny of
line[ 11]: appellate review.
line[ 12]:
line[ 13]: Because Texas law applies no physical manifestation
line[ 14]: rule to restrict wrongful death recoveries, a
line[ 15]: trial court in a death case is prudent when it chooses
line[ 16]: to submit the issues of mental anguish and loss of
line[ 17]: society and companionship. While there is a
line[ 18]: presumption of mental anguish for the wrongful death
line[ 19]: beneficiary, the Texas Supreme Court has not indicated
line[ 20]: that reviewing courts should presume that the mental
line[ 21]: anguish is sufficient to support a large award. Testimony
line[ 22]: that proves the beneficiary suffered severe mental
line[ 23]: anguish or severe grief should be a significant and
line[ 24]: sometimes determining factor in a factual sufficiency
line[ 25]: analysis of large non-pecuniary damage awards.
</code>```

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you haven't written beyond/outside your allocated block of memory, attempted to read or base a jump on an uninitialized value and finally to confirm that you have freed all the memory you have allocated.

For Linux valgrind is the normal choice.

```<code>$ valgrind ./bin/fgets_readfile < dat/damages.txt
==5863== Memcheck, a memory error detector
==5863== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5863== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5863== Command: ./bin/fgets_readfile
==5863==
line[  0]: Personal injury damage awards are unliquidated
line[  1]: and are not capable of certain measurement; thus, the
line[  2]: jury has broad discretion in assessing the amount of
line[  3]: damages in a personal injury case. Yet, at the same
line[  4]: time, a factual sufficiency review insures that the
line[  5]: evidence supports the jury's award; and, although
line[  6]: difficult, the law requires appellate courts to conduct
line[  7]: factual sufficiency reviews on damage awards in
line[  8]: personal injury cases. Thus, while a jury has latitude in
line[  9]: assessing intangible damages in personal injury cases,
line[ 10]: a jury's damage award does not escape the scrutiny of
line[ 11]: appellate review.
line[ 12]:
line[ 13]: Because Texas law applies no physical manifestation
line[ 14]: rule to restrict wrongful death recoveries, a
line[ 15]: trial court in a death case is prudent when it chooses
line[ 16]: to submit the issues of mental anguish and loss of
line[ 17]: society and companionship. While there is a
line[ 18]: presumption of mental anguish for the wrongful death
line[ 19]: beneficiary, the Texas Supreme Court has not indicated
line[ 20]: that reviewing courts should presume that the mental
line[ 21]: anguish is sufficient to support a large award. Testimony
line[ 22]: that proves the beneficiary suffered severe mental
line[ 23]: anguish or severe grief should be a significant and
line[ 24]: sometimes determining factor in a factual sufficiency
line[ 25]: analysis of large non-pecuniary damage awards.
==5863==
==5863== HEAP SUMMARY:
==5863==     in use at exit: 0 bytes in 0 blocks
==5863==   total heap usage: 28 allocs, 28 frees, 1,733 bytes allocated
==5863==
==5863== All heap blocks were freed -- no leaks are possible
==5863==
==5863== For counts of detected and suppressed errors, rerun with: -v
==5863== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
</code>```

Always confirm All heap blocks were freed -- no leaks are possible and equally important ERROR SUMMARY: 0 errors from 0 contexts. (although note: some OS's do not provide adequate memeory exclusion files (the file that excludes system and OS memory from being reported as in use) which will cause valgrind to report that some memory has not yet been freed (despite the fact you have done your job and freed al blocks you allocoted and under your control.)

Body:
As the title explains the problem. In this function in my program , whenever I allocate a certain size in the array I get huge chunks of error code on my terminal. The array gets copied properly and everything but right after printing it the program crashes. The purpose of the program is to read from file and then store each line in an array index. Your help is much appreciated. Thanks

The array is declared as a pointer in the main and then it is dynamically allocated inside.

    void read_file_into_array(char **filearray, FILE * fp)
        {
            /* use get line to count # of lines */
            int numlines = -1;
            numlines = linecount(fp);
            size_t size = 50;
            char *buffer;

            buffer = (char *)malloc(size * sizeof(char));
            if (buffer == NULL) {
                perror("Unable to allocate buffer");
                exit(1);
            }

            if (numlines < 0) {
                fprintf(stderr, "error: unable to determine file length.\n");
                return;
            }

            printf(" number of lines counted are ; %d\n", numlines);

            /* allocate array of size numlines + 1 */

            if (!(*filearray = (char *)malloc(numlines + 1 * sizeof(char)))) {
                fprintf(stderr, "error: virtual memory exhausted.\n");
                return;
            }

            fseek(fp, 0, SEEK_SET);
            for (int i = 0; i < numlines; i++) {
                if (!feof(fp)) {
                    fgets(buffer, size, fp);
                    filearray[i] = (char *)malloc(size * sizeof(char *));
                    strcpy(filearray[i], buffer);
                    printf("buffer at %d : %s\n", i, buffer);
                    printf("array at %d : %s\n", i, filearray[i]);
                }
            }
            free(buffer);
        }

        /* THIS IS MY MAIN BELOW */

        int main (int argc, char **argv)

        {
        FILE *fp = NULL;
        char*  array;

        /* open file for reading (default stdin) */
            fp = argc > 1 ? fopen (argv[1], "r") : stdin;

            if (!fp) {  /* validate file open */
                fprintf (stderr, "error: file open failed '%s'\n", argv[1]);
                return 1;
            }

            read_file_into_array (&array, fp);

        if (fp != stdout)
                if (fclose (fp) == EOF) {
                    fprintf (stderr, "error: fclose() returned EOF\n");
                    return 1;
                }

        return 0;
        }

    /* MY LNE COUNT FUNCITON */
    int linecount(FILE *fp) {
    char buff[MAXLINE];
    int count = 0;

    while(fgets(buff,MAXLINE,fp) != NULL) {
    count++;
    }
    return count;
}

Body:
OK, let's get you sorted out. First, to pass a pointer to pointer to char as a parameter to a function, allocate within the function and have the results available back in the calling function (without more), you must pass the address of the pointer to pointer to char. Otherwise, the function receives a copy and any changes made in the function are not available back in the caller (main here) because the copy is lost (the address to the start of the allocated block is lost) when the function returns.

Passing the address of the pointer to pointer to char means you have to become a 3-STAR Programmer (it is not a compliment). A better way is to not pass the pointer at all, simply allocate within the function and return a pointer to the caller (but there are some cases where you will still need to pass it as a parameter, so that is shown below)

The program below will read any text file passed as the first argument (or it will read from stdin if no argument is given). It will dynamically allocate pointers and needed (in MAXL blocks rather than one-at-a-time which is highly inefficient). It will allocate (and reallocate) lines as required to accommodate lines of any length. It uses a fixed buffer of MAXC chars to read continually until a complete line is read saving the offset to the position in the current line to append subsequent reads as required.

Finally after reading the file, it will print the text and associated line number to stdout, and free all memory allocated before exiting. Look it over and let me know if you have any questions:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { MAXL = 32, MAXC = 1024 };

char **read_file_into_buf (char ***buf, FILE *fp, int *nlines);

int main (int argc, char **argv) {

    char **buf = NULL;  /* buffer to hold lines of file */
    int n;              /* number of lines read */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    if (read_file_into_buf (&buf, fp, &n)) {        /* read file into buf  */
        for (int i = 0; i < n; i++) {               /* loop over all lines */
            printf ("line[%3d]: %s\n", i, buf[i]);  /* output line */
            free (buf[i]);      /* free line */
        }
        free (buf);             /* free buffer */
    }

    if (fp != stdin) fclose (fp);     /* close file if not stdin */

    return 0;
}

/** read text file from 'fp' into 'buf' update 'nlines'.
 *  Being a 3-STAR Programmer, is NOT a compliment. However,
 *  to pass a pointer to pointer to char as a parameter and
 *  allocate within the function, it is required. You must
 *  pass the address of buf from main otherwise the function
 *  recieves a copy whose allocation is lost on return. A better
 *  approach is to simply assign the return in 'main' and not
 *  pass buf at all.
 */
char **read_file_into_buf (char ***buf, FILE *fp, int *nlines)
{
    /* current allocation, current index, and offset (if less
     * than a whole line is read into line on fgets call), and
     * eol indicates '\n' present.
     */
    size_t n = MAXL, idx = 0, offset = 0, eol = 0;
    char line[MAXC] = "";   /* temp buffer for MAXC chars */
    void *tmp = NULL;       /* pointer for realloc */

    /* validate address, file ptr & nlines address */
    if (!buf || !fp || !nlines) {
        fprintf (stderr, "error; invalid parameter.\n");
        return NULL;
    }

    /* allocate initial MAXL pointers, calloc used to avoid valgrind
     * warning about basing a conditional jump on uninitialized value.
     * calloc allocates and initializes.
     */
    if (!(*buf = calloc (sizeof *buf, MAXL))) {
        fprintf (stderr, "error: virtual memory exhausted.\n");
        return NULL;
    }

    while (fgets (line, MAXC, fp))  /* read every line in file */
    {
        /* save offset from prior read (if any), get len */
        size_t end = offset, len = strlen (line);

        if (len && line[len - 1] == '\n') { /* test for new line */
            line[--len] = 0;                /* overwrite with nul */
            offset = 0;                     /* zero offset, all read */
            eol = 1;                        /* POSIX eol present */
        }
        else {
            line[len] = 0;  /* nul-terminate */
            offset += len;  /* short read, save offset to last char */
            eol = 0;        /* no POSIX eol */
        }

        /* allocate/reallocate for current line + nul-byte */
        tmp = realloc ((*buf)[idx], sizeof ***buf * (end + len + 1));
        if (!tmp) {
            fprintf (stderr, "error: realloc, memory exhausted.\n");
            return *buf;  /* return current buf */
        }
        (*buf)[idx] = tmp;  /* assign block to current index */
        strcpy ((*buf)[idx] + end, line);  /* copy line to block */

        if (!eol) continue;   /* chars remain in line, go read them */

        if (++idx == n) {   /* check pointer allocation, realloc as needed */
            tmp = realloc (*buf, sizeof **buf * (n + MAXL));
            if (!tmp) {
                fprintf (stderr, "error: realloc buf, memory exhausted.\n");
                return *buf;
            }
            *buf = tmp; /* assign new block to *buf */
            memset (*buf + n, 0, sizeof **buf * MAXL);  /* zero new memory */
            n += MAXL;  /* update the current number of ptrs allocated */
        }
        *nlines = idx;  /* update the number of lines read */
    }
    if (!eol) {         /* protect against file with no POSIX ending '\n' */
        idx++;          /* account for final line */
        *nlines = idx;  /* update nlines */
    }

    /* final realloc to size buf to exactly fit number of lines */
    tmp = realloc (*buf, sizeof **buf * (idx));
    if (!tmp)   /* if it fails, return current buf */
        return *buf;

    *buf = tmp; /* assign reallocated block to buf */

    return *buf;
}

Note: zeroing the new pointers allocated with memset (*buf + n, 0, sizeof **buf * MAXL); is optional, but it eliminates valgrind warnings about basing a conditional jump on an uninitialized value, just as with calloc/malloc of the initial pointers. There is no option to zero with realloc, so a separate call to memset is required.

Example Use/Output

$ ./bin/fgets_readfile < dat/damages.txt
line[  0]: Personal injury damage awards are unliquidated
line[  1]: and are not capable of certain measurement; thus, the
line[  2]: jury has broad discretion in assessing the amount of
line[  3]: damages in a personal injury case. Yet, at the same
line[  4]: time, a factual sufficiency review insures that the
line[  5]: evidence supports the jury's award; and, although
line[  6]: difficult, the law requires appellate courts to conduct
line[  7]: factual sufficiency reviews on damage awards in
line[  8]: personal injury cases. Thus, while a jury has latitude in
line[  9]: assessing intangible damages in personal injury cases,
line[ 10]: a jury's damage award does not escape the scrutiny of
line[ 11]: appellate review.
line[ 12]:
line[ 13]: Because Texas law applies no physical manifestation
line[ 14]: rule to restrict wrongful death recoveries, a
line[ 15]: trial court in a death case is prudent when it chooses
line[ 16]: to submit the issues of mental anguish and loss of
line[ 17]: society and companionship. While there is a
line[ 18]: presumption of mental anguish for the wrongful death
line[ 19]: beneficiary, the Texas Supreme Court has not indicated
line[ 20]: that reviewing courts should presume that the mental
line[ 21]: anguish is sufficient to support a large award. Testimony
line[ 22]: that proves the beneficiary suffered severe mental
line[ 23]: anguish or severe grief should be a significant and
line[ 24]: sometimes determining factor in a factual sufficiency
line[ 25]: analysis of large non-pecuniary damage awards.

In any code you write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.

It is imperative that you use a memory error checking program to insure you haven't written beyond/outside your allocated block of memory, attempted to read or base a jump on an uninitialized value and finally to confirm that you have freed all the memory you have allocated.

For Linux valgrind is the normal choice.

$ valgrind ./bin/fgets_readfile < dat/damages.txt
==5863== Memcheck, a memory error detector
==5863== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==5863== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==5863== Command: ./bin/fgets_readfile
==5863==
line[  0]: Personal injury damage awards are unliquidated
line[  1]: and are not capable of certain measurement; thus, the
line[  2]: jury has broad discretion in assessing the amount of
line[  3]: damages in a personal injury case. Yet, at the same
line[  4]: time, a factual sufficiency review insures that the
line[  5]: evidence supports the jury's award; and, although
line[  6]: difficult, the law requires appellate courts to conduct
line[  7]: factual sufficiency reviews on damage awards in
line[  8]: personal injury cases. Thus, while a jury has latitude in
line[  9]: assessing intangible damages in personal injury cases,
line[ 10]: a jury's damage award does not escape the scrutiny of
line[ 11]: appellate review.
line[ 12]:
line[ 13]: Because Texas law applies no physical manifestation
line[ 14]: rule to restrict wrongful death recoveries, a
line[ 15]: trial court in a death case is prudent when it chooses
line[ 16]: to submit the issues of mental anguish and loss of
line[ 17]: society and companionship. While there is a
line[ 18]: presumption of mental anguish for the wrongful death
line[ 19]: beneficiary, the Texas Supreme Court has not indicated
line[ 20]: that reviewing courts should presume that the mental
line[ 21]: anguish is sufficient to support a large award. Testimony
line[ 22]: that proves the beneficiary suffered severe mental
line[ 23]: anguish or severe grief should be a significant and
line[ 24]: sometimes determining factor in a factual sufficiency
line[ 25]: analysis of large non-pecuniary damage awards.
==5863==
==5863== HEAP SUMMARY:
==5863==     in use at exit: 0 bytes in 0 blocks
==5863==   total heap usage: 28 allocs, 28 frees, 1,733 bytes allocated
==5863==
==5863== All heap blocks were freed -- no leaks are possible
==5863==
==5863== For counts of detected and suppressed errors, rerun with: -v
==5863== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

Always confirm All heap blocks were freed -- no leaks are possible and equally important ERROR SUMMARY: 0 errors from 0 contexts. (although note: some OS's do not provide adequate memeory exclusion files (the file that excludes system and OS memory from being reported as in use) which will cause valgrind to report that some memory has not yet been freed (despite the fact you have done your job and freed al blocks you allocoted and under your control.)

ContentLicense: CC BY-SA 4.0


问:
Laravel user input form to query database
been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.

perfumes controller

```<code>class perfumescontroller extends Controller
{
  public function index()
 {
   $pstoreNum = request('pstoreNum');

   $result = perfumes::where('StoreNumber','=',$pstoreNum)
        ->get();

    return view('perfumes',compact('result'));

   }

   public function perfWeekSearch()
    {
   $weekNum = request('perfWeekNum');

   $result = perfumes::where('WeekNumber','=',$weekNum)
        ->get();

    return view('perfumes',compact('result'));

    }

    }
</code>```

Route::get('/perfumes', 'perfumescontroller@index');
Route::get('/perfumes', 'perfumescontroller@perfWeekSearch');

Blade:

```<code><form action="perfumes" method="get">
            {{ csrf_field() }}
              <div class="input-group">
                <input type="text" class="form-control" name="perfWeekNum"                     placeholder="Type in Store Number">
                  <span class="input-group-btn">
                    <button type="submit" class="btn btn-default">
                      <span class="glyphicon glyphicon-search"></span>
                    </button>
                  </span>
              </div>
          </form>
</code>```

Do i need to use some sort of check if not null method? or is there an easier way??

Thanks

答:
I think this would be work below is your perfumes controller

```<code>  class perfumescontroller extends Controller
  {
     public function index()
     {
       $data = $request->all();

       if(!empty($data['pstoreNum'])){
       $pstoreNum = $data['pstoreNum'];

        $result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
                  ->get();

      return view('perfumes',compact('result'));
      } else if(!empty($data['perfWeekNum'])){
          $weekNum = $data['perfWeekNum'];

          $result = DB::table('perfumes')->where('WeekNumber','=',$weekNum)
                 ->get();

           return view('perfumes',compact('result'));
       }

      }

 }
</code>```

and you use any with route like below:

```<code>   Route::any('/perfumes', 'perfumescontroller@index');
</code>```

Body:
been trying to create a laravel form with several fields that the user can enter text/number into a field and it takes the field with data and performs a database query. Now the form works with just one field but when i add more fields it only returns data for the final query, not for the other two.

perfumes controller

class perfumescontroller extends Controller
{
  public function index()
 {
   $pstoreNum = request('pstoreNum');

   $result = perfumes::where('StoreNumber','=',$pstoreNum)
        ->get();

    return view('perfumes',compact('result'));

   }

   public function perfWeekSearch()
    {
   $weekNum = request('perfWeekNum');

   $result = perfumes::where('WeekNumber','=',$weekNum)
        ->get();

    return view('perfumes',compact('result'));

    }

    }

Route::get('/perfumes', 'perfumescontroller@index');
Route::get('/perfumes', 'perfumescontroller@perfWeekSearch');

Blade:

<form action="perfumes" method="get">
            {{ csrf_field() }}

                <input type="text" class="form-control" name="perfWeekNum"                     placeholder="Type in Store Number">

                    <button type="submit" class="btn btn-default">

                    </button>

          </form>

Do i need to use some sort of check if not null method? or is there an easier way??

Thanks

Body:
I think this would be work below is your perfumes controller

  class perfumescontroller extends Controller
  {
     public function index()
     {
       $data = $request->all();

       if(!empty($data['pstoreNum'])){
       $pstoreNum = $data['pstoreNum'];

        $result = DB::table('perfumes')->where('StoreNumber','=',$pstoreNum)
                  ->get();

      return view('perfumes',compact('result'));
      } else if(!empty($data['perfWeekNum'])){
          $weekNum = $data['perfWeekNum'];

          $result = DB::table('perfumes')->where('WeekNumber','=',$weekNum)
                 ->get();

           return view('perfumes',compact('result'));
       }

      }

 }

and you use any with route like below:

   Route::any('/perfumes', 'perfumescontroller@index');


问:
Using JQuery to hide and show text
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="trainersptjavascript.js"></script>
</head>
<body>
    <div class="trainers">
            <h2 class="center">Choose your Personal Trainer</h2>
            <div class="ptpics center">
                <h3 class="pt center">Jason O'Reilly</h3>
                <p class="center"><img src="images/ptjay.jpg" alt="Westside Fitness PT Jason" width="320" height="350"></p>
                <p class="ptdeats">Hi there , my name is Jay I am a personal trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Jean Meehan</h3>
                <p class="center"><img src="images/ptjean.jpg" alt="Westside Fitness PT Jean" width="320" height="350"></p>
                <p class="ptdeats">I am a qualified Level 4 Personal Trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center">Aoife McIntyre</h3>
                <p class="center"><img src="images/ptaoife.jpg" alt="Westside Fitness PT Aoifendrew" width="320" height="350"></p>
                <p class="ptdeats">I am Registered Nurse with a Personal Training Qualification.</p>
            </div>
    </div>
</body>
</html>
</code>```

This is the css configuration

```<code>.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }
</code>```

JQuery configuration:

```<code>$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});
</code>```

答:
Okay, so I copied and pasted your code and made a few changes! These changes should fix them. Let me know if they work.

HTML:

```<code><!--Here I ONLY added the id's into each h3 elements. They should not cause any damage to the code. I will tell you why at the end. -->
<!DOCTYPE html>
<html lang="en">
<head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="trainersptjavascript.js"></script>
</head>
<body>
    <div class="trainers">
            <h2 class="center">Choose your Personal Trainer</h2>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_1">Jason O'Reilly</h3>
                <p class="center"><img src="images/ptjay.jpg" alt="Westside Fitness PT Jason" width="320" height="350"></p>
                <p class="ptdeats">Hi there , my name is Jay I am a personal trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_2">Jean Meehan</h3>
                <p class="center"><img src="images/ptjean.jpg" alt="Westside Fitness PT Jean" width="320" height="350"></p>
                <p class="ptdeats">I am a qualified Level 4 Personal Trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_3">Aoife McIntyre</h3>
                <p class="center"><img src="images/ptaoife.jpg" alt="Westside Fitness PT Aoifendrew" width="320" height="350"></p>
                <p class="ptdeats">I am Registered Nurse with a Personal Training Qualification.</p>
            </div>
    </div>
</body>
</html>
</code>```

JAVASCRIPT:

```<code>//I simply modified the classes to put what you wanted it to do. I guess this was simply a class issue then? Because everything seems alright except that.
$(document).ready(function(){
    $(".ptdeats").hide();
    $(".pt").click(function(){
        $(".ptdeats").show();
    });
});
</code>```

JAVASCRIPT, SUGGESTED:

```<code>//This should work better because you want the user to be able to remove that new added text if they want to. Just a minor suggestion. Toggle makes a hidden object to show and a shown object to hide.
$(document).ready(function(){
    $(".ptdeats").hide();
    $(".pt").click(function(){
        $(".ptdeats").toggle();
    });
});
</code>```

JAVASCRIPT, ADDUP WITH ID'S, ALSO SUGGESTED:

```<code>//This is where the ID's come into play.
$(document).ready(function(){
    $(".ptdeats").hide();
    // console.log(this);
    $(".pt").click(function(){
        $("#"+this.id).next().next().toggle();
    });
});
</code>```

Explanation: The two first Javascript will show all the texts in all ".ptdeats" when you click on ".pt" because you tell JS to show ".ptdeats". Any HTML with that class will show.

Nevertheless, there's a cool trick in JS where you can find any specific attribute of the specific element that you clicked on. Also, if you're unfamiliar with "this", "this" basically designates the elements that you are on. For example, if you click on
Jason O'Reilly
, even though you designated it on JS with ".pt", "this" refers specifically to
Jason O'Reilly
. Try uncommenting the // console.log(this); and check your web console to see what I mean.

Finally, .next() in jQuery designates the very next element. In here it works only because of how you structured your HTML. The first .next() is the p tag with the image in it and the second one is the text you actually want to toggle.
This is better because it will toggle the text specific to the person you are clicking on!

Let me know if this works. I am confident it will: I copied and pasted from what you gave and made only minor changes. I also tested it on four different browsers: Opera, Mozilla, Chrome, and Safari. I don't have IE, so I am not sure how it will behave, but this is nothing too complicated so it should work as expected.

Title: Using JQuery to hide and show text

Body:
I want to use JQuery to hide text when web page is launched and when you click on an item it will show the hidden text.

When I load the page it shows the text in h2 and the text in h3 and hides the text in ptdeats as expected. When I click on the text containing "Jason O'Reilly", it doesn't show the text "Hi there, my name is Jay......".

The classes trainers ptpics, pt, center are configured in css.

The jquery is also configured to highlight h3 and also when h3 is click it shows the text and when you click on h3 it hides it again.

This is what I have configured in html:

<!DOCTYPE html>

    <link href="style.css" rel="stylesheet">

Choose your Personal Trainer

Jason O'Reilly

Hi there , my name is Jay I am a personal trainer.

Jean Meehan

I am a qualified Level 4 Personal Trainer.

Aoife McIntyre

I am Registered Nurse with a Personal Training Qualification.

This is the css configuration

.trainers
    {
    width: 80%;
    background-color: #36454F;
    color: #FFFFFF;
    text-align: justify;
    height: auto;
    margin-left: 10%;
    margin-left: 10%;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.pt
    {
    width: 100%;
    cursor: pointer;
    color: #FFFFFF;
    padding-left: 6px;
    padding-right: 6px;
    float: left;
    }

.ptpics
    {
    width: 33%;
    background-color: #36454F;
    color: #FFFFFF;
    border: 1px;
    border-color:#009900;
    text-align: justify;
    height: auto;
    float: left;
    padding-left: 6px;
    padding-right: 6px;
    }

JQuery configuration:

$(document).ready(function()
{
$(".me").hide();
$(".pt").click(function(){
$(".me").show();
});
});

Body:
Okay, so I copied and pasted your code and made a few changes! These changes should fix them. Let me know if they work.

HTML:

<!--Here I ONLY added the id's into each h3 elements. They should not cause any damage to the code. I will tell you why at the end. -->
<!DOCTYPE html>
<html lang="en">
<head>
    <link href="style.css" rel="stylesheet">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="trainersptjavascript.js"></script>
</head>
<body>
    <div class="trainers">
            <h2 class="center">Choose your Personal Trainer</h2>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_1">Jason O'Reilly</h3>
                <p class="center"><img src="images/ptjay.jpg" alt="Westside Fitness PT Jason" width="320" height="350"></p>
                <p class="ptdeats">Hi there , my name is Jay I am a personal trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_2">Jean Meehan</h3>
                <p class="center"><img src="images/ptjean.jpg" alt="Westside Fitness PT Jean" width="320" height="350"></p>
                <p class="ptdeats">I am a qualified Level 4 Personal Trainer.</p>
            </div>
            <div class="ptpics center">
                <h3 class="pt center" id="h3_3">Aoife McIntyre</h3>
                <p class="center"><img src="images/ptaoife.jpg" alt="Westside Fitness PT Aoifendrew" width="320" height="350"></p>
                <p class="ptdeats">I am Registered Nurse with a Personal Training Qualification.</p>
            </div>
    </div>
</body>
</html>

JAVASCRIPT:

//I simply modified the classes to put what you wanted it to do. I guess this was simply a class issue then? Because everything seems alright except that.
$(document).ready(function(){
    $(".ptdeats").hide();
    $(".pt").click(function(){
        $(".ptdeats").show();
    });
});

JAVASCRIPT, SUGGESTED:

//This should work better because you want the user to be able to remove that new added text if they want to. Just a minor suggestion. Toggle makes a hidden object to show and a shown object to hide.
$(document).ready(function(){
    $(".ptdeats").hide();
    $(".pt").click(function(){
        $(".ptdeats").toggle();
    });
});

JAVASCRIPT, ADDUP WITH ID'S, ALSO SUGGESTED:

//This is where the ID's come into play.
$(document).ready(function(){
    $(".ptdeats").hide();
    // console.log(this);
    $(".pt").click(function(){
        $("#"+this.id).next().next().toggle();
    });
});

Explanation: The two first Javascript will show all the texts in all ".ptdeats" when you click on ".pt" because you tell JS to show ".ptdeats". Any HTML with that class will show.

Nevertheless, there's a cool trick in JS where you can find any specific attribute of the specific element that you clicked on. Also, if you're unfamiliar with "this", "this" basically designates the elements that you are on. For example, if you click on <h3 class="pt center" id="h3_1">Jason O'Reilly</h3>, even though you designated it on JS with ".pt", "this" refers specifically to <h3 class="pt center" id="h3_1">Jason O'Reilly</h3>. Try uncommenting the // console.log(this); and check your web console to see what I mean.

Finally, .next() in jQuery designates the very next element. In here it works only because of how you structured your HTML. The first .next() is the p tag with the image in it and the second one is the text you actually want to toggle.
This is better because it will toggle the text specific to the person you are clicking on!

Let me know if this works. I am confident it will: I copied and pasted from what you gave and made only minor changes. I also tested it on four different browsers: Opera, Mozilla, Chrome, and Safari. I don't have IE, so I am not sure how it will behave, but this is nothing too complicated so it should work as expected.