Title: RStudio does not run long length web extension

Body:
There seems to be a bug in RStudio, where it cannot read long lines of code (can someone confirm this?). I found an ugly solution which is to cut it into two objects and then paste them together.

link <- "http://www.nomisweb.co.uk/api/v01/dataset/NM_144_1.data.csv?date=latest&geography=1237321209...1237321232,1237326502...1237326564,1237321121...1237321160,1237326565...1237326631,1237321161...1237321208,1237320728...1237320838,1237321276...1237321319,1237327043...1237327140,1237321233...1237321275,1237322311...1237322476,1237320313...1237320527,1237324154...1237324261,1237326984,1237326985,1237324262...1237324409,1237320528...1237320578,1237320595...1237320616,1237320579...1237320594,1237320617...1237320638,1237321343...1237321368,1237321320...1237321342,1237321369...1237321422,1237325041...1237325213,1237320639...1237320680,1237327368,1237320681,1237320682,1237327369,1237320683...1237320727,1237321002...1237321048,1237326991,1237321049...1237321053,1237326992,1237326993,1237321054...1237321061,1237326994,1237321062,1237326995,1237321063...1237321120,1237321423...1237321461,1237321478...1237321497,1237321462...1237321477,1237322477...1237322481,1237326959,1237322482,1237322483,1237326960,1237322484,1237322485,1237326961,1237322486,1237322487,1237326962,1237322488...1237322490,1237326963,1237322491...1237322633,1237327242...1237327256,1237324410...1237324722,1237324926...1237324989,1237326982,1237324990...1237324995,1237326983,1237324996...1237325001,1237327257...1237327289,1237325002...1237325028,1237327028,1237325029...1237325032,1237327029,1237325033...1237325035,1237327030,1237325036...1237325038,1237327031,1237325039,1237325040,1237325214...1237325296,1237327290...1237327325,1237325297...1237325349,1237321498...1237321537,1237326632...1237326694,1237327147...1237327183,1237321538...1237321570,1237325586...1237325759,1237326141...1237326194,1237327018,1237326195,1237326497,1237327019,1237326196,1237326498,1237326197,1237327020,1237326198,1237326199,1237326499,1237327021,1237326500,1237326200...1237326204,1237327022,1237326205...1237326207,1237327023,1237326208...1237326210,1237326501,1237327024...1237327027,1237326211...1237326230,1237320839...1237321001,1237326376...1237326496,1237327184...1237327241,1237321820...1237321838,1237321796...1237321819,1237321839...1237321875,1237322206...1237322265,1237326964,1237322266,1237326965,1237326966,1237327009,1237322267,1237327010,1237322268,1237326967,1237322269,1237322270,1237326968,1237327011,1237327012,1237326969,1237322271,1237327013,1237322272,1237327014,1237322273,1237326970,1237327015,1237322274,1237327016,1237322275,1237326971,1237327017,1237326972,1237322276...1237322280,1237322282...1237322299,1237322301...1237322310,1237322281,1237322300,1237323052...1237323293,1237327141,1237327142,1237323294...1237323302,1237327143,1237323303,1237323304,1237327144,1237323305,1237323306,1237327145,1237323307,1237327146,1237323308...1237323312,1237323687...1237323875,1237324723...1237324846,1237326989,1237324847...1237324871,1237326990,1237324872...1237324925,1237325760...1237325934,1237319791...1237319808,1237319681...1237319688,1237319894...1237319947,1237320029...1237320062,1237320079...1237320117,1237320138...1237320157,1237320197...1237320217,1237320236...1237320252,1237320273...1237320312,1237319689...1237319790,1237319809...1237319893,1237319948...1237320028,1237320063...1237320078,1237320118...1237320137,1237320158...1237320196,1237320218...1237320235,1237320253...1237320272,1237321898...1237321915,1237322047...1237322067,1237326920...1237326958,1237321876...1237321897,1237322024...1237322046,1237322068...1237322081,1237321946...1237321975,1237322082...1237322097,1237321916...1237321945,1237321976...1237322023,1237322098...1237322205,1237322951...1237323051,1237323442,1237323443,1237323449,1237323444...1237323448,1237323450...1237323602,1237327365,1237323603,1237323604,1237327366,1237327367,1237323605...1237323686,1237323876...1237323996,1237326986,1237323997...1237324005,1237326987,1237324006...1237324011,1237326988,1237324012...1237324115,1237326973,1237324116...1237324124,1237326974,1237324125...1237324153,1237325350...1237325486,1237325935...1237326140,1237326231...1237326375,1237321571...1237321607"
link2 <- ",1237321740...1237321757,1237321608...1237321642,1237326695...1237326821,1237327034,1237327035,1237321643...1237321653,1237327036,1237327037,1237321654...1237321663,1237327038,1237327039,1237321664,1237327040,1237321665...1237321667,1237327041,1237321668,1237327042,1237321669,1237321705...1237321724,1237321758...1237321773,1237321670...1237321704,1237321774...1237321795,1237321725...1237321739,1237326822...1237326919,1237322634...1237322647,1237326975,1237326976,1237322648...1237322651,1237326977,1237322652...1237322659,1237326978,1237322660...1237322679,1237326979,1237322680...1237322692,1237326980,1237322693...1237322700,1237326981,1237322701...1237322757,1237327032,1237322758...1237322764,1237327033,1237322765...1237322950,1237323313...1237323433,1237326996...1237326998,1237323434,1237326999...1237327001,1237323435,1237327002,1237323436,1237327003,1237323437,1237327004,1237323438,1237327005,1237327006,1237323439,1237327007,1237323440,1237323441,1237327008,1237325487...1237325520,1237327326...1237327348,1237325521...1237325585,1237327349...1237327364,1237327370...1237327380,1237328174,1237327381...1237327383,1237328175,1237327384,1237328176,1237327385...1237327388,1237328177,1237327389...1237327391,1237328178,1237327392...1237327396,1237328179,1237327397...1237327399,1237328180,1237327400...1237327481,1237328205,1237327482,1237328206,1237327483...1237327495,1237328207,1237327496...1237327499,1237328208,1237328209,1237327500...1237327503,1237328210,1237327504...1237327595,1237328195,1237327596,1237328196,1237328197,1237327597...1237327600,1237328198,1237327601...1237327603,1237328199,1237327604,1237327605,1237328200,1237327606...1237327608,1237328201,1237327609...1237327615,1237328202,1237327616...1237327624,1237328203,1237327625...1237327628,1237328204,1237327629...1237327668,1237328185,1237327669...1237327692,1237328186,1237327693...1237327740,1237328238...1237328240,1237327741,1237328241,1237327742,1237328242...1237328244,1237327743...1237327747,1237328245,1237328246,1237327748...1237327750,1237328247,1237327751...1237327753,1237328248,1237327754...1237327756,1237328249,1237327757...1237327777,1237328250,1237327778...1237327927,1237328188,1237327928,1237327929,1237328189,1237327930...1237327934,1237328190,1237327935...1237327948,1237328191,1237327949...1237327965,1237328224,1237327966...1237327968,1237328225,1237327969...1237327971,1237328226,1237327972...1237327976,1237328227,1237327977,1237328148...1237328168,1237328192,1237328169...1237328171,1237328193,1237328172,1237328194,1237328173,1237327978...1237327995,1237328181,1237328182,1237327996...1237328005,1237328183,1237328006...1237328011,1237328184,1237328012...1237328035,1237328187,1237328036...1237328042,1237328211,1237328043,1237328212,1237328044...1237328046,1237328213...1237328215,1237328047...1237328050,1237328216...1237328219,1237328051,1237328220,1237328221,1237328052,1237328222,1237328223,1237328053...1237328056,1237328228...1237328235,1237328057,1237328058,1237328236,1237328237,1237328059...1237328147,1946157057...1946157404&rural_urban=0&cell=0,7&measures=20100&select=date_name,geography_name,geography_code,rural_urban_name,cell_name,measures_name,obs_value,obs_status_name"
link3 <- paste(link, link2, "")
pop_uk_2011 <- read.csv(link3)


来源: stackexchange

问:
Is there any structure to programmatically access indices of a String array in Java?
I'm creating a content provider for an Android app in Java and have a String array of constants and separate names for the index of each string in this array, as follows:

```<code>private static final String[] FILM_PROJECTION = {
    FilmContract.FilmEntry.COLUMN_FILM_ID,
    FilmContract.FilmEntry.COLUMN_TITLE,
    FilmContract.FilmEntry.COLUMN_POSTER_URL,
    FilmContract.FilmEntry.COLUMN_OVERVIEW,
    FilmContract.FilmEntry.COLUMN_RATING,
    FilmContract.FilmEntry.COLUMN_DATE,
    FilmContract.FilmEntry.COLUMN_POPULARITY,
    FilmContract.FilmEntry.COLUMN_VIDEOS,
    FilmContract.FilmEntry.COLUMN_REVIEWS
};

private static final int COLUMN_FILM_ID_INDEX    = 0;
private static final int COLUMN_TITLE_INDEX      = 1;
private static final int COLUMN_POSTER_URL_INDEX = 2;
private static final int COLUMN_OVERVIEW_INDEX   = 3;
private static final int COLUMN_RATING_INDEX     = 4;
private static final int COLUMN_DATE_INDEX       = 5;
private static final int COLUMN_POPULARITY_INDEX = 6;
private static final int COLUMN_VIDEOS_INDEX     = 7;
private static final int COLUMN_REVIEWS_INDEX    = 8;
</code>```

I'm thinking there's surely a better way to do this, and I tried it with enum e.g:

```<code>private enum FILM_PROJECTION_INDICES {
    FILM_PROJECTION
}
</code>```

But Java doesn't unpack the String array so that doesn't work (despite all the values being constant). What I'm asking for is something like this:

```<code>index = FILM_PROJECTION.getIndexOf(FilmContract.FilmEntry.COLUMN_TITLE);
</code>```

Is there any way to do this?

答:
FilmEntry itself should already be an Enum (see tutorial) with a custom toString() method:

```<code>enum FilmEntry {
    COLUMN_FILM_ID("Film Id"),
    COLUMN_TITLE("Title"),
    COLUMN_POSTER_URL("Poster URL"),
    COLUMN_OVERVIEW("Overview"),
    COLUMN_RATING("Rating"),
    COLUMN_DATE("Date"),
    COLUMN_POPULARITY("Popularity"),
    COLUMN_VIDEOS("Videos"),
    COLUMN_REVIEWS("Reviews");

    private String title;

    FilmEntry(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return title;
    }
}

System.out.println FilmEntry.COLUMN_FILM_ID.toString(); // returns "Film Id"
System.out.println FilmEntry.COLUMN_FILM_ID.name(); // returns "COLUMN_FILM_ID"
System.out.println FilmEntry.COLUMN_FILM_ID.ordinal(); // returns 0
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a content provider for an Android app in Java and have a String array of constants and separate names for the index of each string in this array, as follows:

private static final String[] FILM_PROJECTION = {
    FilmContract.FilmEntry.COLUMN_FILM_ID,
    FilmContract.FilmEntry.COLUMN_TITLE,
    FilmContract.FilmEntry.COLUMN_POSTER_URL,
    FilmContract.FilmEntry.COLUMN_OVERVIEW,
    FilmContract.FilmEntry.COLUMN_RATING,
    FilmContract.FilmEntry.COLUMN_DATE,
    FilmContract.FilmEntry.COLUMN_POPULARITY,
    FilmContract.FilmEntry.COLUMN_VIDEOS,
    FilmContract.FilmEntry.COLUMN_REVIEWS
};

private static final int COLUMN_FILM_ID_INDEX    = 0;
private static final int COLUMN_TITLE_INDEX      = 1;
private static final int COLUMN_POSTER_URL_INDEX = 2;
private static final int COLUMN_OVERVIEW_INDEX   = 3;
private static final int COLUMN_RATING_INDEX     = 4;
private static final int COLUMN_DATE_INDEX       = 5;
private static final int COLUMN_POPULARITY_INDEX = 6;
private static final int COLUMN_VIDEOS_INDEX     = 7;
private static final int COLUMN_REVIEWS_INDEX    = 8;

I'm thinking there's surely a better way to do this, and I tried it with enum e.g:

private enum FILM_PROJECTION_INDICES {
    FILM_PROJECTION
}

But Java doesn't unpack the String array so that doesn't work (despite all the values being constant). What I'm asking for is something like this:

index = FILM_PROJECTION.getIndexOf(FilmContract.FilmEntry.COLUMN_TITLE);

Is there any way to do this?

Body:
FilmEntry itself should already be an Enum (see tutorial) with a custom toString() method:

enum FilmEntry {
    COLUMN_FILM_ID("Film Id"),
    COLUMN_TITLE("Title"),
    COLUMN_POSTER_URL("Poster URL"),
    COLUMN_OVERVIEW("Overview"),
    COLUMN_RATING("Rating"),
    COLUMN_DATE("Date"),
    COLUMN_POPULARITY("Popularity"),
    COLUMN_VIDEOS("Videos"),
    COLUMN_REVIEWS("Reviews");

    private String title;

    FilmEntry(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return title;
    }
}

System.out.println FilmEntry.COLUMN_FILM_ID.toString(); // returns "Film Id"
System.out.println FilmEntry.COLUMN_FILM_ID.name(); // returns "COLUMN_FILM_ID"
System.out.println FilmEntry.COLUMN_FILM_ID.ordinal(); // returns 0


问:
How can I center elements with angular material2?
I use https://material.angular.io/ for my new angular 2 cli project and its responsive and web design and ux.
I am trying to do a footer with it, how can I center the span?

```<code><md-toolbar color="secondary">
  <md-toolbar-row>
    <span></span>
  </md-toolbar-row>
</md-toolbar>
</code>```

I am coming from a bootstrap background so I suppose there should be something like  span  class="md-center"

Can anyone help me with that? I can't find so much in the docs

Thanks

答:
Unfortunately (or maybe fortunately), material2 doesn't add those sorts of helper classes. But, it's pretty straight-forward to add such logic yourself with basic css.

To align the text in the center of an element,  use text-align: center. This works without issue with a div or anything else with a specified width. In the case of a span, you may want to set the width of the span if you want your content centered across your entire containing element (eg width: 100% or something on the span).

PS. ng2-material is deprecated. That project was created when @angular/material was in its infancy to help provide more components than what was available in the official material project at the time. Since the @angular/material project has ramped up, updates on ng2-material have stopped to focus on the official project.

So you may want to investigate making that switch yourself in the long term.

Body:
I use https://material.angular.io/ for my new angular 2 cli project and its responsive and web design and ux.
I am trying to do a footer with it, how can I center the span?

<md-toolbar color="secondary">
  <md-toolbar-row>

  </md-toolbar-row>
</md-toolbar>

I am coming from a bootstrap background so I suppose there should be something like  span  class="md-center"

Can anyone help me with that? I can't find so much in the docs

Thanks


问:
how to access an element that included using php file
I set template php scripts in order to easily make a change to the file. I have index.php as main page and two php scripts footer.php and header.php. I included two of them in index.php. My question is can access html elements inside footer.php from header.php?

index.php

```<code><!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
    <div class="header"><?php require "templates/header.php" ?></div>
    <div class="footer"><?php require "templates/footer.php" ?></div>
 </body>
</html>
</code>```

header.php

```<code><!DOCTYPE html>
<html>
 <head>
  <script src="scripts/jquery.js"></script>
  <script>
   $(document).ready(function(){
    $("#footerDiv").css('display','none');
    });
  </script>
 </head>
 <body>
 </body>
</html>
</code>```

footer.php

```<code><!DOCTYPE html>
<html>
 <head>
  <script src="scripts/jquery.js"></script>
  <script>
   $(document).ready(function(){
    $("#footerDiv").css('display','block');
    });
  </script>
 </head>
 <body>
  <div id="footerDiv">
   <p>I wanted to access this div from header.php</p>
  </div>
 </body>
</html>
</code>```

答:
first create index.php file like this

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div class="header"><?php require "header.php" ?></div>
  <div class="footer"><?php require "footer.php" ?></div>
</body>
</html>
</code>```

then create header.php file like this

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
   $("#footerDiv").css('display','none');
  });

</script>
</code>```

then create footer.php file like this

```<code><div id="footerDiv">
  <p>I wanted to access this div from header.php</p>
 </div>
</code>```

finally run index.php then you can see footer content hide

Body:
I set template php scripts in order to easily make a change to the file. I have index.php as main page and two php scripts footer.php and header.php. I included two of them in index.php. My question is can access html elements inside footer.php from header.php?

index.php

<!DOCTYPE html>

<?php require "templates/header.php" ?>

<?php require "templates/footer.php" ?>

header.php

<!DOCTYPE html>

footer.php

<!DOCTYPE html>

I wanted to access this div from header.php

Body:
first create index.php file like this

<!DOCTYPE html>
<html>
<head>
</head>
<body>
  <div class="header"><?php require "header.php" ?></div>
  <div class="footer"><?php require "footer.php" ?></div>
</body>
</html>

then create header.php file like this

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
  $(document).ready(function(){
   $("#footerDiv").css('display','none');
  });

</script>

then create footer.php file like this

<div id="footerDiv">
  <p>I wanted to access this div from header.php</p>
 </div>

finally run index.php then you can see footer content hide


问:
Symbolic Link, not accessible from network computer. getting error “The symbolic link cannot be followed because its type is disabled”
I have created symbolic link for shared folder on my machine and this symbolic link is present in another share folder on same machine. i can access this folder content using symbolic link from the same machine. however when i try to access the symbolic link from another machine. i am getting access denied error on windows xp. and windows 2008 shows access denied error with "The symbolic link cannot be followed because its type is disabled"

i have also used fsutil behavior set SymlinkEvaluation R2R:1 L2R:1 R2L:1 to create symbolic link on my machine( windows 7). i have created symbolic link using kernel32 API CreateSymbolicLink.

i am usign following code to create symbolic link,

```<code>[DllImport("kernel32.dll")]
static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
static int SYMLINK_FLAG_DIRECTORY = 1;

string finalTargetD = @"\\abhande-win2k8\CopiedFiles";
string sharedDirectory = @"\\abhande-xp\SharedFiles";

public static void CreateSymLink()
{
 using (WindowsImpersonationContext ctx = WindowsIdentity.GetCurrent().Impersonate())
 {

  if(CreateSymbolicLink(sharedDirectory, finalTargetD, SYMLINK_FLAG_DIRECTORY))
  {
    //symbolic link created successfully
  }
 }

}
</code>```

Do any one have idea why symbolic link is not accessible from another network machine.

Thanks Arvind

答: The SymlinkEvaluation behaviour needs to be set appropriately on the PC you want to "follow" the symlink on. The symlink source/destination (local/remote) are both relative to the machine opening the symlink.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have created symbolic link for shared folder on my machine and this symbolic link is present in another share folder on same machine. i can access this folder content using symbolic link from the same machine. however when i try to access the symbolic link from another machine. i am getting access denied error on windows xp. and windows 2008 shows access denied error with "The symbolic link cannot be followed because its type is disabled"

i have also used fsutil behavior set SymlinkEvaluation R2R:1 L2R:1 R2L:1 to create symbolic link on my machine( windows 7). i have created symbolic link using kernel32 API CreateSymbolicLink.

i am usign following code to create symbolic link,

[DllImport("kernel32.dll")]
static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, int dwFlags);
static int SYMLINK_FLAG_DIRECTORY = 1;

string finalTargetD = @"\\abhande-win2k8\CopiedFiles";
string sharedDirectory = @"\\abhande-xp\SharedFiles";

public static void CreateSymLink()
{
 using (WindowsImpersonationContext ctx = WindowsIdentity.GetCurrent().Impersonate())
 {

  if(CreateSymbolicLink(sharedDirectory, finalTargetD, SYMLINK_FLAG_DIRECTORY))
  {
    //symbolic link created successfully
  }
 }

}

Do any one have idea why symbolic link is not accessible from another network machine.

Thanks Arvind


问:
OnClickListener not working for textview
I am trying to start a new fragment when a textView is presses. I have tried alternative methods but still the onClickListener is not working. I have no crashes, nothing. I have also tried with buttons, or creating the onClick method in the OncreateView method and setting a listener.

```<code>Fragment:package georgia.languagelandscape.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import georgia.languagelandscape.R;

//import android.support.v4.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ProfileFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ProfileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HelpFragment extends Fragment implements MyProjectsFragment.OnFragmentInteractionListener, View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private FragmentManager fm = null;
    private FragmentTransaction ft = null;

    private OnFragmentInteractionListener mListener;

    public HelpFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HelpFragment newInstance(String param1, String param2) {
        HelpFragment fragment = new HelpFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private ListView mListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
     //   String frameVideo = "<html><body>Youtube video .. <br> <iframe width=\"320\" height=\"315\" src=\"https://www.youtube.com/embed/lY2H2ZP56K4\" frameborder=\"0\" allowfullscreen></iframe></body></html>";

        View rootview = inflater.inflate(R.layout.fragment_help, container, false);

        TextView tv= (TextView) rootview.findViewById(R.id.item1);
        tv.setFocusableInTouchMode(false);
        tv.setOnClickListener(this);

    /*   WebView display = (WebView) rootview.findViewById(R.id.webView);
        display.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        WebSettings webSettings = display.getSettings();
        webSettings.setJavaScriptEnabled(true);
        display.loadData(frameVideo, "text/html", "utf-8");*/

        return inflater.inflate(R.layout.fragment_help, container, false);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {

            switch (v.getId()) {
                case R.id.item1:
                    MyProjectsFragment myProjectsFragment= new MyProjectsFragment();
                    fm = getFragmentManager();
                    ft = fm.beginTransaction();
                    Log.d("dcf","da");
                    ft.replace(R.id.content_replace, myProjectsFragment);
                    ft.commit();
                    break;
                /*case R.id.item2:
                    //Do what you want for create_button
                    break;
                default:
                    break;*/
            }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

}
</code>```

xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="georgia.languagelandscape.fragments.HelpFragment"
    android:background="@android:color/background_light"
    tools:background="@android:color/white">

            <TextView
                android:text="Help"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="17dp"
                android:id="@+id/textView"
                android:textSize="30sp"
                android:textStyle="normal|bold"
                android:textColor="#000"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/item1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="50dp"
        android:text="item1"
        android:clickable="true" />

            <WebView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/webView"
                android:layout_marginTop="100dp"
                android:padding="10dp"
                android:layout_below="@+id/textView"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

</RelativeLayout>
</code>```

答:
You have one view called rootview. and you are returning ANOTHER view when you do return inflater.inflate(R.layout.fragment_help, container, false); at the end.

Replace:

```<code>return inflater.inflate(R.layout.fragment_help, container, false);
</code>```

With:

```<code>return rootview;
</code>```

That's it.

Body:
I am trying to start a new fragment when a textView is presses. I have tried alternative methods but still the onClickListener is not working. I have no crashes, nothing. I have also tried with buttons, or creating the onClick method in the OncreateView method and setting a listener.

Fragment:package georgia.languagelandscape.fragments;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import georgia.languagelandscape.R;

//import android.support.v4.app.Fragment;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link ProfileFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link ProfileFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class HelpFragment extends Fragment implements MyProjectsFragment.OnFragmentInteractionListener, View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private FragmentManager fm = null;
    private FragmentTransaction ft = null;

    private OnFragmentInteractionListener mListener;

    public HelpFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ProfileFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static HelpFragment newInstance(String param1, String param2) {
        HelpFragment fragment = new HelpFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    private ListView mListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
     //   String frameVideo = "Youtube video ..
 ";

        View rootview = inflater.inflate(R.layout.fragment_help, container, false);

        TextView tv= (TextView) rootview.findViewById(R.id.item1);
        tv.setFocusableInTouchMode(false);
        tv.setOnClickListener(this);

    /*   WebView display = (WebView) rootview.findViewById(R.id.webView);
        display.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }
        });
        WebSettings webSettings = display.getSettings();
        webSettings.setJavaScriptEnabled(true);
        display.loadData(frameVideo, "text/html", "utf-8");*/

        return inflater.inflate(R.layout.fragment_help, container, false);

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onClick(View v) {

            switch (v.getId()) {
                case R.id.item1:
                    MyProjectsFragment myProjectsFragment= new MyProjectsFragment();
                    fm = getFragmentManager();
                    ft = fm.beginTransaction();
                    Log.d("dcf","da");
                    ft.replace(R.id.content_replace, myProjectsFragment);
                    ft.commit();
                    break;
                /*case R.id.item2:
                    //Do what you want for create_button
                    break;
                default:
                    break;*/
            }

    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     *

     * See the Android Training lesson Communicating with Other Fragments for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

}

xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="georgia.languagelandscape.fragments.HelpFragment"
    android:background="@android:color/background_light"
    tools:background="@android:color/white">

            <TextView
                android:text="Help"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="17dp"
                android:id="@+id/textView"
                android:textSize="30sp"
                android:textStyle="normal|bold"
                android:textColor="#000"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"/>
    <TextView
        android:id="@+id/item1"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="100dp"
        android:layout_marginLeft="50dp"
        android:text="item1"
        android:clickable="true" />

            <WebView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/webView"
                android:layout_marginTop="100dp"
                android:padding="10dp"
                android:layout_below="@+id/textView"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />

</RelativeLayout>

Body:
You have one view called rootview. and you are returning ANOTHER view when you do return inflater.inflate(R.layout.fragment_help, container, false); at the end.

Replace:

return inflater.inflate(R.layout.fragment_help, container, false);

With:

return rootview;

That's it.


问:
Detect first launch of iOS app
I am trying to find a way in Swift to detect the first launch.</p>

答:
Swift 3

```<code>extension UserDefaults {

     var hasLaunchBefore: Bool {
           get {
             return self.bool(forKey: #function)
           }
           set {
             self.set(newValue, forKey: #function)
           }
     }
}
</code>```

Swift 5 (Property wrappers)

UserDefaultWrapper:

```<code>@propertyWrapper
struct UserDefaultWrapper<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}
</code>```

UserDefaultsStore:

```<code>struct UserDefaultsStore {
    @UserDefaultWrapper("has_launch_before", defaultValue: false)
    static var hasLaunchBefore: Bool
}
</code>```

Usage:

```<code>UserDefaultsStore.hasLaunchBefore = false
</code>```

Title: Detect first launch of iOS app

Body:
Swift 3

extension UserDefaults {

     var hasLaunchBefore: Bool {
           get {
             return self.bool(forKey: #function)
           }
           set {
             self.set(newValue, forKey: #function)
           }
     }
}

Swift 5 (Property wrappers)

UserDefaultWrapper:

@propertyWrapper
struct UserDefaultWrapper<T> {
    let key: String
    let defaultValue: T

    init(_ key: String, defaultValue: T) {
        self.key = key
        self.defaultValue = defaultValue
    }

    var wrappedValue: T {
        get {
            return UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}

UserDefaultsStore:

struct UserDefaultsStore {
    @UserDefaultWrapper("has_launch_before", defaultValue: false)
    static var hasLaunchBefore: Bool
}

Usage:

UserDefaultsStore.hasLaunchBefore = false

ContentLicense: CC BY-SA 4.0


问:
JavaScript calling a server-side calculation?
** edited post - initial question essentially meant: **

I am trying to learn how to add a server-side calculation to my JavaScript.

To call the server-side calculation, I presume I need to use AJAX technology. But I am still unsure what form of data exchange I should expect for the return values?

** addition a few months later: **

The answer to this is: to webpages/routes are needed. One (call it "a") to interact with the user, the other one (call it "b") to perform the calculation. a calls b via an ajax request (XmlHttpRequest). b performs calculation and outputs a JSON object. a reads the JSON object and updates its DOM accordingly to output results.

答:
A pseudo code example handling both update and insert without reloading the entire thing.

var number1 = document.getElementById('number1');
var number2 = document.getElementById('number2');
var modifiedExample = document.getElementById('modifiedExample');
var insertedExample = document.getElementById('insertedExample');
var ajaxHandle;

function something() {
  //I use timeout instead of AJAX, since i dont actually have a server to poll but it should be pretty interchangeable
  clearTimeout(ajaxHandle);
  var n1 = parseInt(number1.value, 10);
  var n2 = parseInt(number2.value, 10);
  ajaxHandle = setTimeout(function() {
    modifiedExample.value = n1 + n2;
    insertedExample.appendChild(document.createElement("li")).innerHTML = n1 + n2;
  }, 100 + 500 * Math.random());
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
  Number 1: <input type="number" value="0" id="number1" onchange="something()" /><br/>
  Number 2: <input type="number" value="0" id="number2" onchange="something()" /><br/>
  Result: <input type="number" value="0" id="modifiedExample" readonly/>
</form>

<ul id="insertedExample">
  <li>Results are inserted here</li>
</ul></code>```

Body:
A pseudo code example handling both update and insert without reloading the entire thing.

var number1 = document.getElementById('number1');
var number2 = document.getElementById('number2');
var modifiedExample = document.getElementById('modifiedExample');
var insertedExample = document.getElementById('insertedExample');
var ajaxHandle;

function something() {
  //I use timeout instead of AJAX, since i dont actually have a server to poll but it should be pretty interchangeable
  clearTimeout(ajaxHandle);
  var n1 = parseInt(number1.value, 10);
  var n2 = parseInt(number2.value, 10);
  ajaxHandle = setTimeout(function() {
    modifiedExample.value = n1 + n2;
    insertedExample.appendChild(document.createElement("li")).innerHTML = n1 + n2;
  }, 100 + 500 * Math.random());
}

<form>
  Number 1: <input type="number" value="0" id="number1" onchange="something()" /><br/>
  Number 2: <input type="number" value="0" id="number2" onchange="something()" /><br/>
  Result: <input type="number" value="0" id="modifiedExample" readonly/>
</form>

<ul id="insertedExample">
  <li>Results are inserted here</li>
</ul>


问:
Install Django using setup file in Python 2.7
I am trying to install Diango via setup up file then it shows the following error: </p>

```<code>hari@hari-HP-Pavilion-g6-Notebook-PC:~/Downloads/django-master$ sudo python setup.py install
Traceback (most recent call last):
  File "setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "/home/hari/Downloads/django-master/django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "/home/hari/Downloads/django-master/django/utils/version.py", line 60, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'
</code>```

<p>How to fix this error? </p>

答:
Maybe the zip file from github is only for windows, but i see that you are using linux so:

1) Use PIP (Use sudo as you are not inside virtualenv)

```<code>sudo pip install Django==1.10.6
</code>```

2) Use GIT

```<code>git clone https://github.com/django/django.git
</code>```

Hope this help

Body:
I am trying to install Diango via setup up file then it shows the following error:

hari@hari-HP-Pavilion-g6-Notebook-PC:~/Downloads/django-master$ sudo python setup.py install
Traceback (most recent call last):
  File "setup.py", line 32, in <module>
    version = __import__('django').get_version()
  File "/home/hari/Downloads/django-master/django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
  File "/home/hari/Downloads/django-master/django/utils/version.py", line 60, in <module>
    @functools.lru_cache()
AttributeError: 'module' object has no attribute 'lru_cache'

How to fix this error?

Body:
Maybe the zip file from github is only for windows, but i see that you are using linux so:

1) Use PIP (Use sudo as you are not inside virtualenv)

sudo pip install Django==1.10.6

2) Use GIT

git clone https://github.com/django/django.git

Hope this help


问:
How can I allow my program to continue when a regex doesn't match?
I want to use the regex crate and capture numbers from a string.

```<code>let input = "abcd123efg";
let re = Regex::new(r"([0-9]+)").unwrap();
let cap = re.captures(e).unwrap().get(1).unwrap().as_str();
println!("{}", cap);
</code>```

It worked if numbers exist in input, but if numbers don't exist in input I get the following error:

thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'
```

I want my program continue if the regex doesn't match. How can I handle this error?

答:
You probably want to (re-)read the chapter on "Error Handling" in the Rust book. Error handling in Rust is mostly done via the types Result<T, E> and Option<T>, both representing an optional value of type T with Result<T, E> carrying additional information about the absence of the main value.

You are calling unwrap() on each Option or Result you encounter. unwrap() is a method saying: "if there is no value of type T, let the program explode (panic)". You only want to call unwrap() if an absence of a value is not expected and thus would be a bug! (NB: actually, the unwrap() in your second line is a perfectly reasonable use!)

But you use unwrap() incorrectly twice: on the result of captures() and on the result of get(1). Let's tackle captures() first; it returns an Option<_> and the docs say:

If no match is found, then None is returned.

In most cases, the input string not matching the regex is to be expected, thus we should deal with it. We could either just match the Option (the standard way to deal with those possible errors, see the Rust book chapter) or we could use Regex::is_match() before, to check if the string matches.

Next up: get(1). Again, the docs tell us:

Returns the match associated with the capture group at index i. If i does not correspond to a capture group, or if the capture group did not participate in the match, then None is returned.

But this time, we don't have to deal with that. Why? Our regex (([0-9]+)) is constant and we know that the capture group exists and encloses the whole regex. Thus we can rule out both possible situations that would lead to a None. This means we can unwrap(), because we don't expect the absence of a value.

The resulting code could look like this:

```<code>let input = "abcd123efg";
let re = Regex::new(r"([0-9]+)").unwrap();
match re.captures(e) {
    Some(caps) => {
        let cap = caps.get(1).unwrap().as_str();
        println!("{}", cap);
    }
    None => {
        // The regex did not match. Deal with it here!
    }
}
</code>```

Body:
I want to use the regex crate and capture numbers from a string.

let input = "abcd123efg";
let re = Regex::new(r"([0-9]+)").unwrap();
let cap = re.captures(e).unwrap().get(1).unwrap().as_str();
println!("{}", cap);

It worked if numbers exist in input, but if numbers don't exist in input I get the following error:

thread 'main' panicked at 'called `Option::unwrap()` on a `None` value'

I want my program continue if the regex doesn't match. How can I handle this error?

Body:
You probably want to (re-)read the chapter on "Error Handling" in the Rust book. Error handling in Rust is mostly done via the types Result<T, E> and Option<T>, both representing an optional value of type T with Result<T, E> carrying additional information about the absence of the main value.

You are calling unwrap() on each Option or Result you encounter. unwrap() is a method saying: "if there is no value of type T, let the program explode (panic)". You only want to call unwrap() if an absence of a value is not expected and thus would be a bug! (NB: actually, the unwrap() in your second line is a perfectly reasonable use!)

But you use unwrap() incorrectly twice: on the result of captures() and on the result of get(1). Let's tackle captures() first; it returns an Option<_> and the docs say:

If no match is found, then None is returned.

In most cases, the input string not matching the regex is to be expected, thus we should deal with it. We could either just match the Option (the standard way to deal with those possible errors, see the Rust book chapter) or we could use Regex::is_match() before, to check if the string matches.

Next up: get(1). Again, the docs tell us:

Returns the match associated with the capture group at index i. If i does not correspond to a capture group, or if the capture group did not participate in the match, then None is returned.

But this time, we don't have to deal with that. Why? Our regex (([0-9]+)) is constant and we know that the capture group exists and encloses the whole regex. Thus we can rule out both possible situations that would lead to a None. This means we can unwrap(), because we don't expect the absence of a value.

The resulting code could look like this:

let input = "abcd123efg";
let re = Regex::new(r"([0-9]+)").unwrap();
match re.captures(e) {
    Some(caps) => {
        let cap = caps.get(1).unwrap().as_str();
        println!("{}", cap);
    }
    None => {
        // The regex did not match. Deal with it here!
    }
}


问:
Message queues. msgsnd: Invalid argument
The task is:
Find all prime numbers in the specified interval of numbers divided into several ranges.
Each range is processed in the generated process.
Well, I really tried to make it. But something is going wrong. Can't understand my mistake.
The code:

```<code>#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <stdbool.h>

#define MAX_SEND_SIZE 50

#define PROCESS_NUMBER 5

struct mymsgbuf {
    long mtype;
    int marray[MAX_SEND_SIZE];
};
typedef struct mymsgbuf type_mymsgbuf;

int msgqid, rc;

void send_message(int qid, type_mymsgbuf* qbuf, long type, int* text, int numbers_per_process) {
    int i;
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    for (i = 0; i < numbers_per_process; i++) {
        qbuf->marray[i] = text[i];
    }
    if ((msgsnd(qid, (struct msgbuf*)qbuf, (size_t) length, 0)) == -1) {
        perror("msgsnd");
        exit(1);
    }
}

void read_message(int qid, type_mymsgbuf* qbuf, long type, int numbers_per_process) {
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    msgrcv(qid, (struct msgbuf*)qbuf, (size_t)length, type, 0);
    for (int i = 0; i < numbers_per_process && qbuf->marray[i] != 0; i++) {
        printf("%d\n", qbuf->marray[i]);
    }
}

bool isprime (int a) {
    if(a == 1) {
        return false;
    }
    for (int i = 2; i*i < a; ++i) {
        if ((a % i) == 0) {
            return false;
        }
    }
    return true;
}

int* find_primes_part (int a, int b) {
    int j = 0;
    int* primes = (int*)malloc(sizeof(int)*(b-a));
    for (int k = 0; k < (b-a); ++k) {
        primes[k] = 0;
    }
    for (int i = a; i < b; ++i) {
        if(isprime(i)) {
            primes[j] = i;
            printf("%d\n TEST", primes[j]);
            j++;
        }
    }
    return primes;
}

int find_primes(int a, int b) {
    int status, stat;
    pid_t pid[PROCESS_NUMBER];
    key_t key;
    int qtype = 1;
    type_mymsgbuf qbuf;

    int numbers_per_process = (b-a)/PROCESS_NUMBER;
    if ((key = ftok(".", 'm')) < 0) {
        perror("ftok");
        exit(1);
    }
    if((msgqid = msgget(key, IPC_CREAT|0660)) == -1) {
        perror("msgget");
        exit(1);
    }

    for (int i = 0; i < PROCESS_NUMBER; i++) {
        pid[i] = fork();

        if (-1 == pid[i]) {
            perror("fork");
            exit(1);
        }
        else if (0 == pid[i]) {
            int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
            send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
        }
    }
    for (int j = 0; j < PROCESS_NUMBER; ++j) {
        status = waitpid(pid[j], &stat, 0);
        if (pid[j] == status) {
            if (WEXITSTATUS(stat) != 0) {
                perror("process failed: ");
                exit(1);
            }
        }
    }
    for (int i = 0; i < PROCESS_NUMBER; ++i) {
        read_message(msgqid, &qbuf, qtype, numbers_per_process);
    }

    if ((rc = msgctl(msgqid, IPC_RMID, NULL)) < 0) {
        perror("msgctl");
        return 1;
    }
    return 0;
}

int main() {
    find_primes(10, 200);
    return 0;
}
</code>```

Output is very wrong and its different every other time.
Its something like:

```<code>181
191
193
197
199
163
167
169msgsnd: Invalid argument

173
179
181
191
193
197
msgctl: Invalid argument
</code>```

The main question is this 2 errors

```<code>msgsnd: Invalid argument
msgctl: Invalid argument
</code>```

How to eliminate it?

答:
I suspect that the message queue is removed prematurely.

The problem might be that every process, including the children, execute the cleanup code. Only the parent should run the cleanup code.

I think you are missing a return; or exit(0); in the client specific code, right after the call to send_message().

Body:
The task is:
Find all prime numbers in the specified interval of numbers divided into several ranges.
Each range is processed in the generated process.
Well, I really tried to make it. But something is going wrong. Can't understand my mistake.
The code:

#include <stdio.h>
#include <sys/msg.h>
#include <stdlib.h>
#include <unistd.h>
#include <wait.h>
#include <stdbool.h>

#define MAX_SEND_SIZE 50

#define PROCESS_NUMBER 5

struct mymsgbuf {
    long mtype;
    int marray[MAX_SEND_SIZE];
};
typedef struct mymsgbuf type_mymsgbuf;

int msgqid, rc;

void send_message(int qid, type_mymsgbuf* qbuf, long type, int* text, int numbers_per_process) {
    int i;
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    for (i = 0; i < numbers_per_process; i++) {
        qbuf->marray[i] = text[i];
    }
    if ((msgsnd(qid, (struct msgbuf*)qbuf, (size_t) length, 0)) == -1) {
        perror("msgsnd");
        exit(1);
    }
}

void read_message(int qid, type_mymsgbuf* qbuf, long type, int numbers_per_process) {
    int length = sizeof(struct mymsgbuf) - sizeof(long);
    qbuf->mtype = type;
    msgrcv(qid, (struct msgbuf*)qbuf, (size_t)length, type, 0);
    for (int i = 0; i < numbers_per_process && qbuf->marray[i] != 0; i++) {
        printf("%d\n", qbuf->marray[i]);
    }
}

bool isprime (int a) {
    if(a == 1) {
        return false;
    }
    for (int i = 2; i*i < a; ++i) {
        if ((a % i) == 0) {
            return false;
        }
    }
    return true;
}

int* find_primes_part (int a, int b) {
    int j = 0;
    int* primes = (int*)malloc(sizeof(int)*(b-a));
    for (int k = 0; k < (b-a); ++k) {
        primes[k] = 0;
    }
    for (int i = a; i < b; ++i) {
        if(isprime(i)) {
            primes[j] = i;
            printf("%d\n TEST", primes[j]);
            j++;
        }
    }
    return primes;
}

int find_primes(int a, int b) {
    int status, stat;
    pid_t pid[PROCESS_NUMBER];
    key_t key;
    int qtype = 1;
    type_mymsgbuf qbuf;

    int numbers_per_process = (b-a)/PROCESS_NUMBER;
    if ((key = ftok(".", 'm')) < 0) {
        perror("ftok");
        exit(1);
    }
    if((msgqid = msgget(key, IPC_CREAT|0660)) == -1) {
        perror("msgget");
        exit(1);
    }

    for (int i = 0; i < PROCESS_NUMBER; i++) {
        pid[i] = fork();

        if (-1 == pid[i]) {
            perror("fork");
            exit(1);
        }
        else if (0 == pid[i]) {
            int* part_primes = find_primes_part(a + numbers_per_process*i, a + numbers_per_process*(i+1));
            send_message(msgqid, (type_mymsgbuf*)&qbuf, qtype, part_primes, numbers_per_process);
        }
    }
    for (int j = 0; j < PROCESS_NUMBER; ++j) {
        status = waitpid(pid[j], &stat, 0);
        if (pid[j] == status) {
            if (WEXITSTATUS(stat) != 0) {
                perror("process failed: ");
                exit(1);
            }
        }
    }
    for (int i = 0; i < PROCESS_NUMBER; ++i) {
        read_message(msgqid, &qbuf, qtype, numbers_per_process);
    }

    if ((rc = msgctl(msgqid, IPC_RMID, NULL)) < 0) {
        perror("msgctl");
        return 1;
    }
    return 0;
}

int main() {
    find_primes(10, 200);
    return 0;
}

Output is very wrong and its different every other time.
Its something like:

181
191
193
197
199
163
167
169msgsnd: Invalid argument

173
179
181
191
193
197
msgctl: Invalid argument

The main question is this 2 errors

msgsnd: Invalid argument
msgctl: Invalid argument

How to eliminate it?


问:
Could not find a part of path when using ImageBrush
I get that error if i try to run my "application". In fact that's an empty window with background.

```<code><Window x:Class="NWN_Tsuki.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="831" Width="875">
<Window.Background>
    <ImageBrush Stretch="None" ImageSource="pack://siteoforigin:,,,/Resources/Book.png" />
</Window.Background>
<Grid/>
</Window>
</code>```

That's all my app. And i get error. If i set absolute path to image - all working fine.

I tried to google, i searched same topics here and tried to do what worked for others - there are no progress. Just one window. Just one background image in resourses added through wizard.

Visual Studio 2013, Windows 7 Ultimate x64

答:
I have experienced this. It turned out, the .png was corrupted. When I navigated to the folder in File Explorer, I saw the following

I think the mkelem is something to do with our source control, so maybe it was that which corrupted it, regardless, this is why some people may get this error message.

Body:
I get that error if i try to run my "application". In fact that's an empty window with background.

<Window x:Class="NWN_Tsuki.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="831" Width="875">
<Window.Background>
    <ImageBrush Stretch="None" ImageSource="pack://siteoforigin:,,,/Resources/Book.png" />
</Window.Background>
<Grid/>
</Window>

That's all my app. And i get error. If i set absolute path to image - all working fine.

I tried to google, i searched same topics here and tried to do what worked for others - there are no progress. Just one window. Just one background image in resourses added through wizard.

Visual Studio 2013, Windows 7 Ultimate x64


问:
Position div under another div
I have 2 divs: div with submit and order-content div

        <form>

submit

        </form>

                  <form>
                  </form>

```

Also when I add new product, im appending new table row, so css position attribute doesn't work as I want cause it has static values. I thought about making jquery which gets height of new row and increments submit input position, but is there better solution?

答:
You need to use JavaScript to move elements in DOM to a different order than they appear in the original document. Something like (jsfiddle with jQuery):

https://jsfiddle.net/khabgc6h/2/

```<code>$('.input').insertAfter('.new-product')
</code>```

Title: Position div under another div

Body:
I have 2 divs: div with submit and order-content div

        <form>

submit

        </form>

                  <form>
                  </form>

Also when I add new product, im appending new table row, so css position attribute doesn't work as I want cause it has static values. I thought about making jquery which gets height of new row and increments submit input position, but is there better solution?

Body:
You need to use JavaScript to move elements in DOM to a different order than they appear in the original document. Something like (jsfiddle with jQuery):

https://jsfiddle.net/khabgc6h/2/

$('.input').insertAfter('.new-product')


问:
Paypal payment method in Laravel
I just think about that i have to integrate a payment method for my site.My site is developed in laravel.That's why i am looking for a way to add paypal integration.My site is there you can visit.</p>

答:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

```
composer create-project --prefer-dist laravel/laravel blog
```

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

```<code>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

```<code>"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",
</code>```

then after run following command in your terminal

```<code>php artisan vendore:publlish
</code>```

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

```<code><?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available option 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);
</code>```

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

```<code>Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));
</code>```

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

```<code>php artisan make:controller AddMoneyController
</code>```

Ok, now put bellow content in controller file:

app/Http/Controllers/AddMoneyController.php

```<code><?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }
</code>```

Step 7: Create View

In Last step, let's create paywithpaypal.blade.php(resources/views/paywithpaypal.blade.php) for layout and we will write design code here and also form for pay amount by paypal, So put following code:
resources/views/paywithpaypal.blade.php

```<code>@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading">Paywith Paypal</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Amount</label>

                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
</code>```

Now we are ready to run our example so run bellow command ro quick run:

```<code>php artisan serve
</code>```

Now you can open bellow URL on your browser:

```<code>DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret
</code>```0

please visit this toturials link..

https://www.youtube.com/watch?v=ly2xm_NM46g

Title: Paypal payment method in Laravel

Body:
Follow Bellow Few Step:

1)Install Laravel Application

2)Database Configuration

3)Install Required Packages

4)configuration paypal.php file

5)create route

6)create controller

7)create view file

Step 1 : Install Laravel Application

we are going from scratch, So we require to get fresh Laravel application using bellow command, So open your terminal OR command prompt and run bellow command:

composer create-project --prefer-dist laravel/laravel blog

Step 2 : Database Configuration

In this step, we require to make database configuration, you have to add
 following details on your .env file.

1.Database Username

1.Database Password

1.Database Name

In .env file also available host and port details, you can configure all details as in your system, So you can put like as bellow:
.env

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Step 3 : Install Required Packages

We have required following 2 packages for integrate paypal payment in our laravel application.
add following two package in your composer.json file.

"guzzlehttp/guzzle": "~5.4",
"paypal/rest-api-sdk-php": "*",

then after run following command in your terminal

php artisan vendore:publlish

after run this command, then after automatic create paypal.php file in your config/paypal.php path.

Step 4 : Configuration paypal.php file

&lt;?php

return array(
/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
/**
* SDK configuration
*/
'settings' => array(
    /**
    * Available option 'sandbox' or 'live'
    */
    'mode' => 'sandbox',
    /**
    * Specify the max request time in seconds
    */
    'http.ConnectionTimeOut' => 1000,
    /**
    * Whether want to log to a file
    */
    'log.LogEnabled' => true,
    /**
    * Specify the file that want to write on
    */
    'log.FileName' => storage_path() . '/logs/paypal.log',
    /**
    * Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
    *
    * Logging is most verbose in the 'FINE' level and decreases as you
    * proceed towards ERROR
    */
    'log.LogLevel' => 'FINE'
    ),
);

Step 5: Create Route

In this is step we need to create route for paypal payment. so open your routes/web.php file and add following route.
routes/web.php

Route::get('paywithpaypal', array('as' => 'addmoney.paywithpaypal','uses' => 'AddMoneyController@payWithPaypal',));
Route::post('paypal', array('as' => 'addmoney.paypal','uses' => 'AddMoneyController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'AddMoneyController@getPaymentStatus',));

Step 6: Create Controller

In this point, now we should create new controller as AddMoneyController in this path app/Http/Controllers/AddMoneyController.php. this controller will manage layout and payment post request, So run bellow command for generate new controller:

php artisan make:controller AddMoneyController

Ok, now put bellow content in controller file:

app/Http/Controllers/AddMoneyController.php

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class AddMoneyController extends HomeController
{

    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();

        /** setup PayPal api context **/
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

        $item_1 = new Item();

        $item_1->setName('Item 1') /** item name **/
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount')); /** unit price **/

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('addmoney.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('addmoney.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        /** add payment ID to session **/
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {
            /** redirect to paypal **/
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
        return Redirect::route('addmoney.paywithpaypal');
    }

    public function getPaymentStatus()
    {
        /** Get the payment ID before session clear **/
        $payment_id = Session::get('paypal_payment_id');
        /** clear the session payment ID **/
        Session::forget('paypal_payment_id');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('addmoney.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') {

            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/

            \Session::put('success','Payment success');
            return Redirect::route('addmoney.paywithpaypal');
        }
        \Session::put('error','Payment failed');

        return Redirect::route('addmoney.paywithpaypal');
    }
  }

Step 7: Create View

In Last step, let's create paywithpaypal.blade.php(resources/views/paywithpaypal.blade.php) for layout and we will write design code here and also form for pay amount by paypal, So put following code:
resources/views/paywithpaypal.blade.php

@extends('layouts.app')

@section('content')
<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading">Paywith Paypal</div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Amount</label>

                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/paywithpaypal

please visit this toturials link..

https://www.youtube.com/watch?v=ly2xm_NM46g


问:
Return structure pointer in C
Could you please help me in correcting my code:

This is a function that returns a pointer to struct item:

```<code>struct item* findItem(const char* key) {
    for (int i = 0; i < nItems; i++) {
        if (!strcmp(items[i].key, key)) { return &items[i]; }
    }
    return NULL;
}
</code>```

From main function, I want to retrieve my struct value as following:

```<code>struct item search_items = findItem(&key) ; // I have problem with this line
char* itemValue;
if (search_items != NULL)
{
    itemValue = search_items->value;
}
</code>```

How can I retrieve the structure and save it to be used in the main function?

答:
If you are returning pointer from function, then you have to read it as pointer.
Notice struct item* search_items part on my code and on your (I added pointer *)

```<code>struct item* search_items = findItem(&key) ; // i have problem with this line
char* itemValue;
if ( search_items != NULL)
{
    itemValue = search_items->value;
}
</code>```

Title: Return structure pointer in C

Body:
Could you please help me in correcting my code:

This is a function that returns a pointer to struct item:

struct item* findItem(const char* key) {
    for (int i = 0; i < nItems; i++) {
        if (!strcmp(items[i].key, key)) { return &items[i]; }
    }
    return NULL;
}

From main function, I want to retrieve my struct value as following:

struct item search_items = findItem(&key) ; // I have problem with this line
char* itemValue;
if (search_items != NULL)
{
    itemValue = search_items->value;
}

How can I retrieve the structure and save it to be used in the main function?

Body:
If you are returning pointer from function, then you have to read it as pointer.
Notice struct item* search_items part on my code and on your (I added pointer *)

struct item* search_items = findItem(&key) ; // i have problem with this line
char* itemValue;
if ( search_items != NULL)
{
    itemValue = search_items->value;
}


问:
AutoMapper Nested Mapping not working. Here is the config and code :
Followed the steps mentioned in Automapper wiki to configure nested mapping with complex objects. but not working :

```<code>public class Student
    {
        public int ID{get;set;}
        public string Name { get; set; }
        public string Standard { get; set; }
        public List<string> Course { get; set; }
        public int Age { get; set; }
        public string FatherName { get; set; }
        public string  MotherName{ get; set; }
        public char Gender { get; set; }
        public DateTime DOB { get; set; }
        public string BloodGroup { get; set; }
        public int TestCondition { get; set; }
        public Address Address { get; set; }

    }

  public class Address
    {
        public int ID { get; set; }
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Zip { get; set; }
    }
</code>```

DTO :

```<code>public class StudentDTO
    {
        public string Name { get; set; }
        public string Standard { get; set; }
        public char Gender { get; set; }
        public DateTime DOB { get; set; }
        public string BG { get; set; }
        public int TestCondition { get; set; }
        public AddressDTO AddressDTO { get; set; }

    }
 public class AddressDTO
    {
        public int ID { get; set; }
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Zip { get; set; }
    }
</code>```

Configuration :

```<code>public class AutoMapperProfileConfig : Profile
    {

        public AutoMapperProfileConfig()
        {

            CreateMap<Student, StudentDTO>().ForMember(dest => dest.DOB, opt=>opt.Ignore())
                                            .ForMember(x=>x.BG,opt=>opt.MapFrom(y=>y.BloodGroup))/*.AfterMap((src, dest) => dest.Name = "After MAP")*/
                                            .ForMember(x=>x.TestCondition, opt=>opt.Condition(src => (src.TestCondition >= 100))
                                            );
CreateMap<Address, AddressDTO>();
</code>```

Execution :

```<code>Student student = new Student();
            Address add = new Address();
            add.Line1 = "abcd";
            student.Address = add;
            var studentLite = Mapper.Map<StudentDTO>(student);
</code>```

Although studentDTO is getting mapped properly the AddressDTO is null.

答:
You're mapping Student.Address to StudentDTO.AddressDTO. As the name of your target property has changed, AutoMapper doesn't know what to do with it. If you changed your propertyname in StudentDTO from AddressDTO into Address, Automapper should be able pick it up and map it.

An alternative solution would of course be to instruct AutoMapper explicitly to map Student.Address to StudentDTO.AddressDTO.

Body:
Followed the steps mentioned in Automapper wiki to configure nested mapping with complex objects. but not working :

public class Student
    {
        public int ID{get;set;}
        public string Name { get; set; }
        public string Standard { get; set; }
        public List<string> Course { get; set; }
        public int Age { get; set; }
        public string FatherName { get; set; }
        public string  MotherName{ get; set; }
        public char Gender { get; set; }
        public DateTime DOB { get; set; }
        public string BloodGroup { get; set; }
        public int TestCondition { get; set; }
        public Address Address { get; set; }

    }

  public class Address
    {
        public int ID { get; set; }
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Zip { get; set; }
    }

DTO :

public class StudentDTO
    {
        public string Name { get; set; }
        public string Standard { get; set; }
        public char Gender { get; set; }
        public DateTime DOB { get; set; }
        public string BG { get; set; }
        public int TestCondition { get; set; }
        public AddressDTO AddressDTO { get; set; }

    }
 public class AddressDTO
    {
        public int ID { get; set; }
        public string Line1 { get; set; }
        public string Line2 { get; set; }
        public string Zip { get; set; }
    }

Configuration :

public class AutoMapperProfileConfig : Profile
    {

        public AutoMapperProfileConfig()
        {

            CreateMap<Student, StudentDTO>().ForMember(dest => dest.DOB, opt=>opt.Ignore())
                                            .ForMember(x=>x.BG,opt=>opt.MapFrom(y=>y.BloodGroup))/*.AfterMap((src, dest) => dest.Name = "After MAP")*/
                                            .ForMember(x=>x.TestCondition, opt=>opt.Condition(src => (src.TestCondition >= 100))
                                            );
CreateMap<Address, AddressDTO>();

Execution :

Student student = new Student();
            Address add = new Address();
            add.Line1 = "abcd";
            student.Address = add;
            var studentLite = Mapper.Map<StudentDTO>(student);

Although studentDTO is getting mapped properly the AddressDTO is null.


问:
L5.3 - Call route from another route
I've a simple route into the file web.php:

```<code>Route::get('first/{param?}', [
   'uses' => 'App\Http\Controllers\MyController@index',
   'as' => 'myControllerIndex'
]);
</code>```

Now, I'd like to create a second route that uses the first route but passing specific params.
I tried something like this:

```<code>Route::get('second', function () {
   return file_get_contents(route('myControllerIndex', ['param' => 'book1']));
});
</code>```

but it doesn't work.

Can anyone help me?

Thank you.

答:
You could use a redirect

```<code>Route::get('second', function () {
   return redirect()->route('myControllerIndex', ['param' => 'book1']);
});
</code>```

Or you can access the controller directly

```<code>Route::get('second', function () {
   return app('App\Http\Controllers\MyController')->index('book1');
});
</code>```

Title: L5.3 - Call route from another route

Body:
I've a simple route into the file web.php:

Route::get('first/{param?}', [
   'uses' => 'App\Http\Controllers\MyController@index',
   'as' => 'myControllerIndex'
]);

Now, I'd like to create a second route that uses the first route but passing specific params.
I tried something like this:

Route::get('second', function () {
   return file_get_contents(route('myControllerIndex', ['param' => 'book1']));
});

but it doesn't work.

Can anyone help me?

Thank you.

Body:
You could use a redirect

Route::get('second', function () {
   return redirect()->route('myControllerIndex', ['param' => 'book1']);
});

Or you can access the controller directly

Route::get('second', function () {
   return app('App\Http\Controllers\MyController')->index('book1');
});


问:
.innerHTML not changing value on maths quiz
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

```<code>function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;
</code>```

答:
You are not calling your function

document.getElementById("questions").innerHTML = getNumber();

function getNumber(){
    var oplist = ["=","-","*"],
    num1 = Math.floor((Math.random() * 10) + 1),
    num2 = Math.floor((Math.random() * 10) + 1),
    op = oplist [Math.floor(Math.random()* oplist.length)],
ans = 0;
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
return ans;
}

document.getElementById("questions").innerHTML = getNumber();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="questions"></div></code>```

Body:
As part of a school project I have to make a full randomised maths quiz (with three operators) using HTML, CSS, Javascript and JQuery, if necessairy. It also has to include css styling i.e. it has to look good as well.

I've hit a road block where my question doesn't appear in the assigned div of 'questions'. I understand I've made plenty of mistakes, this is my first time using javascript, any help would be appriciated and if you need the full code, just ask. Thanks.

function getNumber(){
    var oplist = ["=","-","*"];
    num1 = Math.floor((Math.random() * 10) + 1);
    num2 = Math.floor((Math.random() * 10) + 1);
    op = oplist [Math.floor(Math.random()* oplist.length)];
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
}

document.getElementById("questions").innerHTML = num1 + op + num2;

Body:
You are not calling your function

document.getElementById("questions").innerHTML = getNumber();

function getNumber(){
    var oplist = ["=","-","*"],
    num1 = Math.floor((Math.random() * 10) + 1),
    num2 = Math.floor((Math.random() * 10) + 1),
    op = oplist [Math.floor(Math.random()* oplist.length)],
ans = 0;
    if (op == "+"){
        ans = (num1 + num2)
    }
    else if (op == "-"){
        ans = (num1 - num2)
    }
    else if (op == "*"){
        ans = (num1 * num2)
    }
return ans;
}

document.getElementById("questions").innerHTML = getNumber();

<div id="questions"></div>


问:
What is considered a "best practice" for the design of a set of PHP scripts which service AJAX requests?
I am designing a website which will query a simple MySQL database using AJAX calls to PHP scripts.

I have looked into frameworks which achieve this but I'm looking for a lighter weight solution and so am rolling my own. At present I have all AJAX calls hitting a single script, which then calls further functions based on the content of POSTed variables. Those functions return objects or throw exceptions, and in my main script I either return a JSON encoded version of the object or catch the exceptions and return a JSON encoded "error object".

Does this approach sound ok or not? If not, what is best practice in this scenario?

答:
on the serverside i would reommend a restful approach.

and for the client side javascript i would recommend jQuery ($().ajax())

and it probably would't hurt to code after the principles of MVC


答:
Assuming your MONTH column has the DATE data type:

```<code>SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT t.*,
         LAG( month  ) OVER ( PARTITION BY id ORDER BY month ) AS prev_month,
         LAG( income ) OVER ( PARTITION BY id ORDER BY month ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;
</code>```

Update:

```<code>SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT id,
         TO_DATE( month, 'MM/YYYY' ) AS month,
         income,
         LAG( TO_DATE( month, 'MM/YYYY' )  ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_month,
         LAG( income                       ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;
</code>```

Title: How to find percentage change in income from month to month?

Body:
I have a sample table of IDs with income and months and would like to get the percent change in income from month to month. A change of income from 0 to something else is not valid.

ID  INCOME  MONTH
1   150     02/2017
1   100     01/2017
2   25      03/2017
2   75      02/2017
2   50      01/2017
3   100     03/2017
3   0       02/2017
4   100     03/2017
4   25      02/2017
4   50      01/2017
5   0       02/2017
5   0       01/2017
6   100     02/2017
6   0       01/2017
6   50      12/2016
7   100     11/2016
7   100     10/2016

% Change = ((New Income – Original Income)/Original Income) *100

So for ID #1, for 01/2017-02/2017, that's ((150-100)/100)*100=50%. For ID #2, for 02/2017-03/2017, that's ((25-75)/75)*100 = -67%, and for 01/2017-02/2017, that's ((75-50)/50)*100=50%.

Intended results:

ID  Period              % Change
1   01/2017-02/2017     50
2   01/2017-02/2017     50
2   02/2017-03/2017     -67
4   01/2017-02/2017     -50
4   02/2017-03/2017     300
6   12/2016-01/2017     -100
7   10/2016-11/2016     0

How can this be achieved?

Body:
Assuming your MONTH column has the DATE data type:

SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT t.*,
         LAG( month  ) OVER ( PARTITION BY id ORDER BY month ) AS prev_month,
         LAG( income ) OVER ( PARTITION BY id ORDER BY month ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;

Update:

SELECT id,
       TO_CHAR( prev_month, 'MM/YYYY' ) || '-' || TO_CHAR( month, 'MM/YYYY' ) As period,
       100 * income / prev_income - 100 AS "% Change"
FROM   (
  SELECT id,
         TO_DATE( month, 'MM/YYYY' ) AS month,
         income,
         LAG( TO_DATE( month, 'MM/YYYY' )  ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_month,
         LAG( income                       ) OVER ( PARTITION BY id ORDER BY TO_DATE( month, 'MM/YYYY' ) ) AS prev_income
  FROM   your_table t
)
WHERE  ADD_MONTHS( prev_month, 1 ) = month
AND    prev_income > 0;