问:
No retrofit annotation found #1
i am trying to make a post request using retrofit 2.0 which also has image to be sent but everytime i try i get an error saying no retrofit annotation found .. please help me out in resolving this issue ...will be very thankful.. following below is my code snippet

MY RETROFIT INTERFACE

```<code> @Multipart
    @POST("empowerapp/seekerreg.php")
    Call<ResponseModel> registerSeeker(@Part MultipartBody.Part image,
                                       @Part("fname") RequestBody fname,
                                       @Part("fname") RequestBody lname,
                                       @Part("promoter") RequestBody promoter,
                                       @Part("dob") RequestBody dob,
                                       @Part("gender") RequestBody gender,
                                       @Part("paswd") RequestBody paswd,
                                       @Part("ph") RequestBody phone,
                                       @Part("email") RequestBody email,
                                       @Part("weight") RequestBody weight,
                                       @Part("height") RequestBody height,
                                       @Part("qualification") RequestBody qualification,
                                       @Part("color") RequestBody color,
                                       @Part("lang_known") RequestBody languages,
                                       @Part("experience") RequestBody experience,
                                       @Part("exp_type") RequestBody exptype,
                                       @Part("dres_code") RequestBody dresscode,
                                       @Part("vehicle_mode") RequestBody vehicleMode,
                                       @Part("photo1") RequestBody photo1,
                                       @Part("photo2") RequestBody photo2,
                                       @Part("photo3") RequestBody photo3,
                                       @Part("address") RequestBody address,
                                       @Part("landmark") RequestBody landmark,
                                       @Part("location") RequestBody location,
                                       @Part("city") RequestBody city,
                                       @Part("state") RequestBody state,
                                       @Part("contry") RequestBody contry,
                                       @Part("pincode") RequestBody pincode,
                                       @Part("bank_name") RequestBody bankName,
                                       @Part("ac_name") RequestBody acName,
                                       @Part("ac_number") RequestBody acNumber,
                                       @Part("ifsc") RequestBody ifsc,
                                       @Part("br_name") RequestBody brName,
                                       @Part("size") RequestBody size);
</code>```

MY RETROFIT CALL METHOD

```<code>public void registerSeeker(SeekerProfileModel profileModel) {

        System.out.println("###exp" + s_exp.getText().toString());

        //create file which we want to send to server.
        File imageFIle = new File(selectedIdproofPath);

        //request body is used to attach file.
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),imageFIle);

        //and request body and file name using multipart.
        MultipartBody.Part selectedIdproof = MultipartBody.Part.createFormData("id_proof", imageFIle.getName(),requestBody); //"image" is parameter for photo in API.

        RequestBody promoter = RequestBody.create(MediaType.parse("text/plain"),profileModel.getPromoter() );
        RequestBody fname = RequestBody.create(MediaType.parse("text/plain"),profileModel.getFname());
        RequestBody lname = RequestBody.create(MediaType.parse("text/plain"),profileModel.getLname());
        RequestBody email = RequestBody.create(MediaType.parse("text/plain"), profileModel.getEmail());
        RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhone());
        RequestBody languages = RequestBody.create(MediaType.parse("text/plain"), profileModel.getLanguages());
        RequestBody address = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAddress());
        RequestBody landmark = RequestBody.create(MediaType.parse("text/plain"),profileModel.getLandmark());
        RequestBody city = RequestBody.create(MediaType.parse("text/plain"),profileModel.getCity());
        RequestBody state = RequestBody.create(MediaType.parse("text/plain"), profileModel.getState());
        RequestBody contry = RequestBody.create(MediaType.parse("text/plain"), profileModel.getContry());
        RequestBody pincode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPincode());
        RequestBody paswd = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPassword());
        RequestBody dob = RequestBody.create(MediaType.parse("text/plain"), profileModel.getDob());
        RequestBody gender = RequestBody.create(MediaType.parse("text/plain"), profileModel.getGender());

        RequestBody exp = RequestBody.create(MediaType.parse("text/plain"), profileModel.getExperience());
        RequestBody weight = RequestBody.create(MediaType.parse("text/plain"), profileModel.getWeight());
        RequestBody expType = RequestBody.create(MediaType.parse("text/plain"), profileModel.getExperienceType());
        RequestBody qualification = RequestBody.create(MediaType.parse("text/plain"), profileModel.getQualification());
        RequestBody color = RequestBody.create(MediaType.parse("text/plain"), profileModel.getColor());

        RequestBody size = RequestBody.create(MediaType.parse("text/plain"), profileModel.getSize());
        RequestBody height = RequestBody.create(MediaType.parse("text/plain"), profileModel.getHeight());
        RequestBody dresscode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getDressCode());
        RequestBody vehicleMode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getVehicleMode());
        RequestBody photo1 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto1());
        RequestBody photo2 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto2());
        RequestBody photo3 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto3());
        RequestBody bankname = RequestBody.create(MediaType.parse("text/plain"), profileModel.getBankName());
        RequestBody branchname = RequestBody.create(MediaType.parse("text/plain"), profileModel.getBranchName());
        RequestBody acccountnumber = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAccontNumber());
        RequestBody ifsc = RequestBody.create(MediaType.parse("text/plain"), profileModel.getIfsc());
        RequestBody accountholder = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAccountName());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Allconstants.MAIN_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitInterface service = retrofit.create(RetrofitInterface.class);

        Call<ResponseModel> call = service.registerSeeker(selectedIdproof,fname,lname,promoter,dob,gender,paswd,phone,email,weight,height,qualification,color,languages,exp,expType,dresscode,vehicleMode,photo1,photo2,photo3,address,landmark,landmark,city,state,contry,pincode,bankname,accountholder,acccountnumber,ifsc,branchname,size
                );
        call.enqueue(new Callback<ResponseModel>() {
            @Override
            public void onResponse(Response<ResponseModel> response, Retrofit retrofit) {
                System.out.println("###coming" + response.body().getStatus());
                pd.dismiss();
                if (response.body().getStatus().equalsIgnoreCase("Success"))
                {
                    pd.dismiss();
                    loginSession.createLoginSession(Allconstants.SEEKER,Allconstants.S_REG_ACTIVITY,response.body().getName(), response.body().getId());
                    Toast.makeText(Registration.this,"successfully registered",Toast.LENGTH_LONG).show();
                    System.out.println("###coming"+response.body().toString());
                }else{
                    pd.dismiss();
                    Toast.makeText(Registration.this,"oops!!!something went wrong..try again"+response.body().getStatus(),Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Throwable t) {
                pd.dismiss();
                Toast.makeText(Registration.this, t.getStackTrace().toString(), Toast.LENGTH_LONG).show();
                System.out.println("###error1" + t.getMessage());
                System.out.println("###stack trace: ");
                t.printStackTrace();
            }
        });
    }
</code>```

答:
For the first parameter ,

examine this code

```<code>File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);

MultipartBody.Part body = MultipartBody.Part.createFormData("upload",file.getName(), reqFile);
</code>```

you had this MediaType.parse("multipart/form-data") try the above.You need to use file providers,To securely offer a file from your app to another app, you need to configure your app to offer a secure handle to the file, in the form of a content URI. The Android FileProvider component generates content URIs for files, based on specifications you provide in XML.

Defining a FileProvider for your app requires an entry in your manifest. This entry specifies the authority to use in generating content URIs, as well as the name of an XML file that specifies the directories your app can share.

```<code> String mCurrentPhotoPath;

 private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new  Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
    imageFileName,  /* prefix */
    ".jpg",         /* suffix */
    storageDir      /* directory */
);

// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
</code>```

}

then call that  function exposing the file to fileprovider to get a path.

```<code>    Uri photoURI = FileProvider.getUriForFile(this,
                                              "com.example.android.fileprovider", image /* return file*/);
</code>```

Title: No retrofit annotation found #1

Body:
i am trying to make a post request using retrofit 2.0 which also has image to be sent but everytime i try i get an error saying no retrofit annotation found .. please help me out in resolving this issue ...will be very thankful.. following below is my code snippet

MY RETROFIT INTERFACE

 @Multipart
    @POST("empowerapp/seekerreg.php")
    Call<ResponseModel> registerSeeker(@Part MultipartBody.Part image,
                                       @Part("fname") RequestBody fname,
                                       @Part("fname") RequestBody lname,
                                       @Part("promoter") RequestBody promoter,
                                       @Part("dob") RequestBody dob,
                                       @Part("gender") RequestBody gender,
                                       @Part("paswd") RequestBody paswd,
                                       @Part("ph") RequestBody phone,
                                       @Part("email") RequestBody email,
                                       @Part("weight") RequestBody weight,
                                       @Part("height") RequestBody height,
                                       @Part("qualification") RequestBody qualification,
                                       @Part("color") RequestBody color,
                                       @Part("lang_known") RequestBody languages,
                                       @Part("experience") RequestBody experience,
                                       @Part("exp_type") RequestBody exptype,
                                       @Part("dres_code") RequestBody dresscode,
                                       @Part("vehicle_mode") RequestBody vehicleMode,
                                       @Part("photo1") RequestBody photo1,
                                       @Part("photo2") RequestBody photo2,
                                       @Part("photo3") RequestBody photo3,
                                       @Part("address") RequestBody address,
                                       @Part("landmark") RequestBody landmark,
                                       @Part("location") RequestBody location,
                                       @Part("city") RequestBody city,
                                       @Part("state") RequestBody state,
                                       @Part("contry") RequestBody contry,
                                       @Part("pincode") RequestBody pincode,
                                       @Part("bank_name") RequestBody bankName,
                                       @Part("ac_name") RequestBody acName,
                                       @Part("ac_number") RequestBody acNumber,
                                       @Part("ifsc") RequestBody ifsc,
                                       @Part("br_name") RequestBody brName,
                                       @Part("size") RequestBody size);

MY RETROFIT CALL METHOD

public void registerSeeker(SeekerProfileModel profileModel) {

        System.out.println("###exp" + s_exp.getText().toString());

        //create file which we want to send to server.
        File imageFIle = new File(selectedIdproofPath);

        //request body is used to attach file.
        RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"),imageFIle);

        //and request body and file name using multipart.
        MultipartBody.Part selectedIdproof = MultipartBody.Part.createFormData("id_proof", imageFIle.getName(),requestBody); //"image" is parameter for photo in API.

        RequestBody promoter = RequestBody.create(MediaType.parse("text/plain"),profileModel.getPromoter() );
        RequestBody fname = RequestBody.create(MediaType.parse("text/plain"),profileModel.getFname());
        RequestBody lname = RequestBody.create(MediaType.parse("text/plain"),profileModel.getLname());
        RequestBody email = RequestBody.create(MediaType.parse("text/plain"), profileModel.getEmail());
        RequestBody phone = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhone());
        RequestBody languages = RequestBody.create(MediaType.parse("text/plain"), profileModel.getLanguages());
        RequestBody address = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAddress());
        RequestBody landmark = RequestBody.create(MediaType.parse("text/plain"),profileModel.getLandmark());
        RequestBody city = RequestBody.create(MediaType.parse("text/plain"),profileModel.getCity());
        RequestBody state = RequestBody.create(MediaType.parse("text/plain"), profileModel.getState());
        RequestBody contry = RequestBody.create(MediaType.parse("text/plain"), profileModel.getContry());
        RequestBody pincode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPincode());
        RequestBody paswd = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPassword());
        RequestBody dob = RequestBody.create(MediaType.parse("text/plain"), profileModel.getDob());
        RequestBody gender = RequestBody.create(MediaType.parse("text/plain"), profileModel.getGender());

        RequestBody exp = RequestBody.create(MediaType.parse("text/plain"), profileModel.getExperience());
        RequestBody weight = RequestBody.create(MediaType.parse("text/plain"), profileModel.getWeight());
        RequestBody expType = RequestBody.create(MediaType.parse("text/plain"), profileModel.getExperienceType());
        RequestBody qualification = RequestBody.create(MediaType.parse("text/plain"), profileModel.getQualification());
        RequestBody color = RequestBody.create(MediaType.parse("text/plain"), profileModel.getColor());

        RequestBody size = RequestBody.create(MediaType.parse("text/plain"), profileModel.getSize());
        RequestBody height = RequestBody.create(MediaType.parse("text/plain"), profileModel.getHeight());
        RequestBody dresscode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getDressCode());
        RequestBody vehicleMode = RequestBody.create(MediaType.parse("text/plain"), profileModel.getVehicleMode());
        RequestBody photo1 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto1());
        RequestBody photo2 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto2());
        RequestBody photo3 = RequestBody.create(MediaType.parse("text/plain"), profileModel.getPhoto3());
        RequestBody bankname = RequestBody.create(MediaType.parse("text/plain"), profileModel.getBankName());
        RequestBody branchname = RequestBody.create(MediaType.parse("text/plain"), profileModel.getBranchName());
        RequestBody acccountnumber = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAccontNumber());
        RequestBody ifsc = RequestBody.create(MediaType.parse("text/plain"), profileModel.getIfsc());
        RequestBody accountholder = RequestBody.create(MediaType.parse("text/plain"), profileModel.getAccountName());

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Allconstants.MAIN_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RetrofitInterface service = retrofit.create(RetrofitInterface.class);

        Call<ResponseModel> call = service.registerSeeker(selectedIdproof,fname,lname,promoter,dob,gender,paswd,phone,email,weight,height,qualification,color,languages,exp,expType,dresscode,vehicleMode,photo1,photo2,photo3,address,landmark,landmark,city,state,contry,pincode,bankname,accountholder,acccountnumber,ifsc,branchname,size
                );
        call.enqueue(new Callback<ResponseModel>() {
            @Override
            public void onResponse(Response<ResponseModel> response, Retrofit retrofit) {
                System.out.println("###coming" + response.body().getStatus());
                pd.dismiss();
                if (response.body().getStatus().equalsIgnoreCase("Success"))
                {
                    pd.dismiss();
                    loginSession.createLoginSession(Allconstants.SEEKER,Allconstants.S_REG_ACTIVITY,response.body().getName(), response.body().getId());
                    Toast.makeText(Registration.this,"successfully registered",Toast.LENGTH_LONG).show();
                    System.out.println("###coming"+response.body().toString());
                }else{
                    pd.dismiss();
                    Toast.makeText(Registration.this,"oops!!!something went wrong..try again"+response.body().getStatus(),Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFailure(Throwable t) {
                pd.dismiss();
                Toast.makeText(Registration.this, t.getStackTrace().toString(), Toast.LENGTH_LONG).show();
                System.out.println("###error1" + t.getMessage());
                System.out.println("###stack trace: ");
                t.printStackTrace();
            }
        });
    }

Body:
For the first parameter ,

examine this code

File file = new File(filePath);

RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);

MultipartBody.Part body = MultipartBody.Part.createFormData("upload",file.getName(), reqFile);

you had this MediaType.parse("multipart/form-data") try the above.You need to use file providers,To securely offer a file from your app to another app, you need to configure your app to offer a secure handle to the file, in the form of a content URI. The Android FileProvider component generates content URIs for files, based on specifications you provide in XML.

Defining a FileProvider for your app requires an entry in your manifest. This entry specifies the authority to use in generating content URIs, as well as the name of an XML file that specifies the directories your app can share.

 String mCurrentPhotoPath;

 private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new  Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
    imageFileName,  /* prefix */
    ".jpg",         /* suffix */
    storageDir      /* directory */
);

// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;

}

then call that  function exposing the file to fileprovider to get a path.

    Uri photoURI = FileProvider.getUriForFile(this,
                                              "com.example.android.fileprovider", image /* return file*/);


来源: stackexchange

问:
Shell - check if a git tag exists in an if/else statement
I am creating a deploy script for a zend application. The script is almost done only I want to verify that a tag exists within the repo to force tags on the team. Currently I have the following code:

```<code># First update the repo to make sure all the tags are in
cd /git/repo/path
git pull

# Check if the tag exists in the rev-list.
# If it exists output should be zero,
# else an error will be shown which will go to the else statement.
if [ -z "'cd /git/repo/path && git rev-list $1..'" ]; then

    echo "gogo"

else

    echo "No or no correct GIT tag found"
    exit

fi
</code>```

Looking forward to your feedback!

Update

When I execute the following in the command line:

```<code>cd /git/repo/path && git rev-list v1.4..
</code>```

I get NO output, which is good. Though when I execute:

```<code>cd /git/repo/path && git rev-list **BLA**..
</code>```

I get an error, which again is good:

```<code>fatal: ambiguous argument 'BLA..': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions
</code>```

The -z in the statement says, if sting is empty then... In other words, it works fine via command line. Though when I use the same command in a shell script inside a statement it does not seem to work.

```<code>[ -z "'cd /git/repo/path && git rev-list $1..'" ]
</code>```

This method is inspired by Validate if commit exists

Update 2

I found the problem:

See Using if elif fi in shell scripts >

sh is interpreting the && as a shell operator. Change it to -a, that’s
[’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ] Also, you should always
quote the variables, because [ gets confused when you leave off
arguments.

in other words, I changed the && to ; and simplified the condition. Now it works beautiful.

```<code>if cd /path/to/repo ; git rev-list $1.. >/dev/null

then

    echo "gogo"

else
    echo "WRONG"
    exit
fi
</code>```

答:
Why so complicated? Here’s a dead-simple solution (based on cad106uk’s approach further down the page):

```<code>version=1.2.3

if [ $(git tag -l "$version") ]; then
    echo yes
else
    echo no
fi
</code>```

It is not necessary to compare the output of git tag -l with the version number, because the output will be empty if the version is not found. Therefore it’s sufficient to test if there’s any output at all.

Note: The quotes around $version are important to avoid false positives. Because if $version is empty for some reason, git tag -l would just list all tags, and the condition would always be true.

ContentLicense: CC BY-SA 4.0

Body:
I am creating a deploy script for a zend application. The script is almost done only I want to verify that a tag exists within the repo to force tags on the team. Currently I have the following code:

# First update the repo to make sure all the tags are in
cd /git/repo/path
git pull

# Check if the tag exists in the rev-list.
# If it exists output should be zero,
# else an error will be shown which will go to the else statement.
if [ -z "'cd /git/repo/path && git rev-list $1..'" ]; then

    echo "gogo"

else

    echo "No or no correct GIT tag found"
    exit

fi

Looking forward to your feedback!

Update

When I execute the following in the command line:

cd /git/repo/path && git rev-list v1.4..

I get NO output, which is good. Though when I execute:

cd /git/repo/path && git rev-list **BLA**..

I get an error, which again is good:

fatal: ambiguous argument 'BLA..': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions

The -z in the statement says, if sting is empty then... In other words, it works fine via command line. Though when I use the same command in a shell script inside a statement it does not seem to work.

[ -z "'cd /git/repo/path && git rev-list $1..'" ]

This method is inspired by Validate if commit exists

Update 2

I found the problem:

See Using if elif fi in shell scripts >

sh is interpreting the && as a shell operator. Change it to -a, that’s
[’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ] Also, you should always
quote the variables, because [ gets confused when you leave off
arguments.

in other words, I changed the && to ; and simplified the condition. Now it works beautiful.

if cd /path/to/repo ; git rev-list $1.. >/dev/null

then

    echo "gogo"

else
    echo "WRONG"
    exit
fi

Body:
Why so complicated? Here’s a dead-simple solution (based on cad106uk’s approach further down the page):

version=1.2.3

if [ $(git tag -l "$version") ]; then
    echo yes
else
    echo no
fi

It is not necessary to compare the output of git tag -l with the version number, because the output will be empty if the version is not found. Therefore it’s sufficient to test if there’s any output at all.

Note: The quotes around $version are important to avoid false positives. Because if $version is empty for some reason, git tag -l would just list all tags, and the condition would always be true.


问:
Why does my CGContext-drawn circle suck?
I have a custom table view cell that is intended to draw a circle like the iPhone’s Mail.app does:

Instead, it draws like this:

Here’s my code:

```<code>CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor grayColor];

[grayColor set];

CGContextStrokeEllipseInRect(context, CGRectMake(9, 10, 23, 23));
</code>```

How can I make it not suck? :)

Edit: Ignore the fact that I omitted the code that draws the white background color.

What about it sucks? It doesn’t look close to, if not exactly like, the circle from Mail.

答:
Try setting its alpha to 0.5 and making the borders thicker, for example, like this:</p>

```<code>CGContextSetAlpha(context, 0.5);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a custom table view cell that is intended to draw a circle like the iPhone’s Mail.app does:

Instead, it draws like this:

Here’s my code:

CGContextRef context = UIGraphicsGetCurrentContext();
UIColor *grayColor = [UIColor grayColor];

[grayColor set];

CGContextStrokeEllipseInRect(context, CGRectMake(9, 10, 23, 23));

How can I make it not suck? :)

Edit: Ignore the fact that I omitted the code that draws the white background color.

What about it sucks? It doesn’t look close to, if not exactly like, the circle from Mail.

Body:
Try setting its alpha to 0.5 and making the borders thicker, for example, like this:

CGContextSetAlpha(context, 0.5);


问:
switch between 2 tabbar controllers swift ios
Hi I ve got 2 TabBar Controllers
Tabbar Controller A
Tabbar Controller B

from A.tab3 I need to switch to B.tab1

everything I ve done so far makes B.tab1 open within A.tab1. what I need is to open B.tab1 outside the "A" tabbar controller

any help appreciated
thanks

答:
solved with this bit of code:</p>

```<code>let tbb = storyboard!.instantiateViewController(withIdentifier: "TabbarB") as! UITabBarController
UIApplication.shared.keyWindow?.rootViewController = tbb
</code>```

ContentLicense: CC BY-SA 3.0

Body:
solved with this bit of code:

let tbb = storyboard!.instantiateViewController(withIdentifier: "TabbarB") as! UITabBarController
UIApplication.shared.keyWindow?.rootViewController = tbb


问:
Octave - Create a matrix of all binary values
In Octave, given a number, (say 5), I need to make a matrix of (2^5 X 5) with each row having the binary representation of numbers from 0 to 2^5 - 1 i.e the matrix would be like

[[ 0,  0,  0,  0,  0],

[ 0,  0,  0,  0,  1]]

[ 0,  0,  0,  1,  0]]

and so on. Is there any built-in function to do this? Unable to figure out how to do it efficiently? One way I can think of is running a loop and generating the binary value for each value from 0:(2^5-1) and storing it in matrix, but this seems very inefficient.

答:
de2bi might be in the octave communications toolbox, but I don't have that installed.  The following is a one-line implementation of decimal to binary that may be good enough

```<code>nums = (1:7)';
bsxfun(@(u,v)bitand(u,v)~=0, [16 8 4 2 1], nums)
</code>```

Body:
de2bi might be in the octave communications toolbox, but I don't have that installed.  The following is a one-line implementation of decimal to binary that may be good enough

nums = (1:7)';
bsxfun(@(u,v)bitand(u,v)~=0, [16 8 4 2 1], nums)


问:
convert Any to json on the fly
I have a very large .tsv file that has a somewhat strange structure, it has rows like this:

```<code>CA  110123140   14228123056896  [{"id":"missing_required_gtin_future_disapproval","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:57:36Z"}, {"id":"missing_required_gtin_error","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:57:36Z"}]]
</code>```

So, as you can see, it's 4 columns but the 4th one is a json object.

I can load the file to a df on spark with:

```<code>val df = sqlContext.read.format("com.databricks.spark.csv")
.option("delimiter", "\t")
.load(file_path)
</code>```

But this:

```<code>df.take(1)(0)(3)
</code>```

yields:

```<code>res53:  Any = [{"id":"missing_required_gtin_future_disapproval","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:54:43Z"}, {"id":"missing_required_gtin_error","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:54:43Z"}]
</code>```

which makes it (for me) difficult to parse as a json object.

Ideally, what I would like to have is a dataframe where the columns are they keys of the json object:

```<code>"id"    "location"   "severity"          "timestamp"
 123     blabla      critical       2017-02-19T20:54:43Z
 234     blabla      critical       2017-02-19T21:54:43Z
</code>```

So the difficulty is two-fold.

For each row on the original file, I may have several rows on the final dataframe, as every json object is a list.

How do I process the json object?

EDIT:

I realize I wasn't very clear on what I actually want.
What I would actually like is to be able to access as well the first three columns so that the final df looks like this:

```<code>"country "   "user"    "object"  "id"    "location"   "severity"          "timestamp"
    CA      98172937   87647563  123     blabla      critical       2017-02-19T20:54:43Z
    CA      98172937   87647563  234     blabla      critical       2017-02-19T21:54:43Z
</code>```

This is the most difficult part I believe, as it involves inserting somehow the information on the first 3 columns on the json object.

答:
you can read your data as rdd and then transform the json column to a dataframe like this:</p>

```<code> val rdd = sc.textFile("path/filet.tsv").map(_.split('\t')(3))
 val df = sqlContext.read.json(rdd)
 df.printSchema
  root
   |-- id: string (nullable = true)
   |-- location: string (nullable = true)
   |-- severity: string (nullable = true)
   |-- timestamp: string (nullable = true)
</code>```

Title: convert Any to json on the fly

Body:
I have a very large .tsv file that has a somewhat strange structure, it has rows like this:

CA  110123140   14228123056896  [{"id":"missing_required_gtin_future_disapproval","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:57:36Z"}, {"id":"missing_required_gtin_error","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:57:36Z"}]]

So, as you can see, it's 4 columns but the 4th one is a json object.

I can load the file to a df on spark with:

val df = sqlContext.read.format("com.databricks.spark.csv")
.option("delimiter", "\t")
.load(file_path)

But this:

df.take(1)(0)(3)

yields:

res53:  Any = [{"id":"missing_required_gtin_future_disapproval","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:54:43Z"}, {"id":"missing_required_gtin_error","location":"gtin","severity":"critical","timestamp":"2017-02-19T20:54:43Z"}]

which makes it (for me) difficult to parse as a json object.

Ideally, what I would like to have is a dataframe where the columns are they keys of the json object:

"id"    "location"   "severity"          "timestamp"
 123     blabla      critical       2017-02-19T20:54:43Z
 234     blabla      critical       2017-02-19T21:54:43Z

So the difficulty is two-fold.

For each row on the original file, I may have several rows on the final dataframe, as every json object is a list.

How do I process the json object?

EDIT:

I realize I wasn't very clear on what I actually want.
What I would actually like is to be able to access as well the first three columns so that the final df looks like this:

"country "   "user"    "object"  "id"    "location"   "severity"          "timestamp"
    CA      98172937   87647563  123     blabla      critical       2017-02-19T20:54:43Z
    CA      98172937   87647563  234     blabla      critical       2017-02-19T21:54:43Z

This is the most difficult part I believe, as it involves inserting somehow the information on the first 3 columns on the json object.

Body:
you can read your data as rdd and then transform the json column to a dataframe like this:

 val rdd = sc.textFile("path/filet.tsv").map(_.split('\t')(3))
 val df = sqlContext.read.json(rdd)
 df.printSchema
  root
   |-- id: string (nullable = true)
   |-- location: string (nullable = true)
   |-- severity: string (nullable = true)
   |-- timestamp: string (nullable = true)


问:
How to add Session value to DropDownList using SqlDataSource in ASP.Net?
I have a DropDownList, it is connected with SqlDataSource, I am passing two values in that DropDownList

1.ReportName = it is default value TotalSales

2.UserID = it is session Value Session["UserID"]

Here is my code

Aspx.code

```<code><asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HQWebMatajer13 %>" SelectCommand="SELECT [UserFileName] FROM [ReportSave] WHERE (([ReportName] = @ReportName) AND ([UserID] = @UserID))">
    <SelectParameters>
        <asp:Parameter DefaultValue="TotalSales" Name="ReportName" Type="String" />
        <asp:SessionParameter Name="UserID" SessionField="UserID" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>
</code>```

Here is the

I already pass the value in session from my previous page called UserReports.aspx

That page code:

```<code>protected void linkTotalSales_Click(object sender, EventArgs e)
{
    Session["UserID"] = Session["UserID"].ToString();
    Response.Redirect("ReportTotalSalesPivot.aspx");
}
</code>```

When I click the link of TotalSales from UserReports.aspx page.
It shows the following error

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'UserID'.

答:
It's showing error because in your datasource you are not selecting UserId and ReportName. You are just Using them as a Condition in your WHERE clause.

And I'm not getting that why you're doing like

```<code> Session["UserId"] = Session["UserId"].ToString();
</code>```

Because you session is already having a string variable in it. And another thing to note is Session will be dynamic throughout your Web Application.

Body:
I have a DropDownList, it is connected with SqlDataSource, I am passing two values in that DropDownList

1.ReportName = it is default value TotalSales

2.UserID = it is session Value Session["UserID"]

Here is my code

Aspx.code

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:HQWebMatajer13 %>" SelectCommand="SELECT [UserFileName] FROM [ReportSave] WHERE (([ReportName] = @ReportName) AND ([UserID] = @UserID))">
    <SelectParameters>
        <asp:Parameter DefaultValue="TotalSales" Name="ReportName" Type="String" />
        <asp:SessionParameter Name="UserID" SessionField="UserID" Type="String" />
    </SelectParameters>
</asp:SqlDataSource>

Here is the

I already pass the value in session from my previous page called UserReports.aspx

That page code:

protected void linkTotalSales_Click(object sender, EventArgs e)
{
    Session["UserID"] = Session["UserID"].ToString();
    Response.Redirect("ReportTotalSalesPivot.aspx");
}

When I click the link of TotalSales from UserReports.aspx page.
It shows the following error

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'UserID'.

Body:
It's showing error because in your datasource you are not selecting UserId and ReportName. You are just Using them as a Condition in your WHERE clause.

And I'm not getting that why you're doing like

 Session["UserId"] = Session["UserId"].ToString();

Because you session is already having a string variable in it. And another thing to note is Session will be dynamic throughout your Web Application.


问:
How to Configure Angular 2
Trying to configure Angular 2 as per Angular 2 document and available resources but getting stuck. So how to Configure Angular 2 environment in Visual studio or any native editor. </p>

答:
Install visual studio editor and add this plugins

And also TypeScript Emmet as commented by @Sasxa

This is all you will need for development.

Title: How to Configure Angular 2


问:
PHP - How to get all the calling class
How to get all the calling class?

I tried:

```<code>function __autoload ($class){
require $class;
debug_print_backtrace();
}

$obj1 = new Foo();
$obj2 = new Foo();
$obj3 = new Foo();
</code>```

Result:

```<code>#0 __autoload(Foo) called at [/var/www/index.php:8]
</code>```

But I need result - I need to list all calls :(

```<code>#0 __autoload(Foo) called at [/var/www/index.php:8]
#0 __autoload(Foo) called at [/var/www/index.php:9]
#0 __autoload(Foo) called at [/var/www/index.php:10]
</code>```

Can anyone please help? Thank you.

答:
The problem is that you are not printing the backtrace on calling the class, you are printing it on loading it. And you only need to load it once (the first time it is called).

If you want to show it on calling, you need to add it to the constructor of your Foo class, like

```<code>class Foo
{
    public function __construct()
    {
         // your other construct code
         // if you didn't have one, maybe a parent::__construct()
         debug_print_backtrace();
    }
}
</code>```

Now you get the backtrace everytime you make an instance of the class.

This does mean you have to do it in every class, which can be tedious, but it's the best you can do. Maybe there is a different solution to what you are trying to do, but you have not added the reason for this requirement, so it's hard to find that other solution :)

Title: PHP - How to get all the calling class

Body:
How to get all the calling class?

I tried:

function __autoload ($class){
require $class;
debug_print_backtrace();
}

$obj1 = new Foo();
$obj2 = new Foo();
$obj3 = new Foo();

Result:

#0 __autoload(Foo) called at [/var/www/index.php:8]

But I need result - I need to list all calls :(

#0 __autoload(Foo) called at [/var/www/index.php:8]
#0 __autoload(Foo) called at [/var/www/index.php:9]
#0 __autoload(Foo) called at [/var/www/index.php:10]

Can anyone please help? Thank you.

Body:
The problem is that you are not printing the backtrace on calling the class, you are printing it on loading it. And you only need to load it once (the first time it is called).

If you want to show it on calling, you need to add it to the constructor of your Foo class, like

class Foo
{
    public function __construct()
    {
         // your other construct code
         // if you didn't have one, maybe a parent::__construct()
         debug_print_backtrace();
    }
}

Now you get the backtrace everytime you make an instance of the class.

This does mean you have to do it in every class, which can be tedious, but it's the best you can do. Maybe there is a different solution to what you are trying to do, but you have not added the reason for this requirement, so it's hard to find that other solution :)


问:
Text size of android design TabLayout tabs
I have difficulties changing the text size of the tabs of design library tablayout (android.support.design.widget.TabLayout).

I managed to change it by assigning tabTextAppearance in TabLayout

```<code>app:tabTextAppearance="@style/MyTabLayoutTextAppearance"
</code>```

the following style

```<code><style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
    <item name="android:textSize">14sp</item>
</style>
</code>```

but I have 2 side effects :

1) I lost the accent color of the selected tab

2) The tab text is not capitalized any more.

答:
```<code>TabLayout  tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);

private void changeTabsFont() {
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
    ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(font);
                ((TextView) tabViewChild).setTextSize(15);

            }
        }
    }
}
</code>```

This code is works for me using tablayout.
It will change size of fonts and also change font style.

This will also help you guys please check this link

https://stackoverflow.com/a/43156384/5973946

This code works for Tablayout change text color,type face (font style) and also text size.

Body:
I have difficulties changing the text size of the tabs of design library tablayout (android.support.design.widget.TabLayout).

I managed to change it by assigning tabTextAppearance in TabLayout

app:tabTextAppearance="@style/MyTabLayoutTextAppearance"

the following style

but I have 2 side effects :

1) I lost the accent color of the selected tab

2) The tab text is not capitalized any more.

Body:
TabLayout  tab_layout = (TabLayout)findViewById(R.id.tab_Layout_);

private void changeTabsFont() {
    Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/"+ Constants.FontStyle);
    ViewGroup vg = (ViewGroup) tab_layout.getChildAt(0);
    int tabsCount = vg.getChildCount();
    for (int j = 0; j < tabsCount; j++) {
        ViewGroup vgTab = (ViewGroup) vg.getChildAt(j);
        int tabChildsCount = vgTab.getChildCount();
        for (int i = 0; i < tabChildsCount; i++) {
            View tabViewChild = vgTab.getChildAt(i);
            if (tabViewChild instanceof TextView) {
                ((TextView) tabViewChild).setTypeface(font);
                ((TextView) tabViewChild).setTextSize(15);

            }
        }
    }
}

This code is works for me using tablayout.
It will change size of fonts and also change font style.

This will also help you guys please check this link

https://stackoverflow.com/a/43156384/5973946

This code works for Tablayout change text color,type face (font style) and also text size.


问:
What template is loaded by Django?
I was following Django tutorial, and got stuck where it asked me to replace the default template for administrative part of the site with my own.  The problem was a typo in the template's name.  I suspected there must be a problem like that, but to troubleshoot the problem it'd be very helpful to see some kind of report from Django on what template it used to render a particular page.  Is there any way to do this?</p>

答:
Still, not exactly the answer, but something to get me closer. One could start Django shell, and then try this:

```<code>>>> from django.template.loader import get_template
>>> get_template('template/name').origin.name
</code>```

to find out what template was actually used.  This is still not enough to see though which templates were considered while resolving the template.

Title: What template is loaded by Django?

Body:
Still, not exactly the answer, but something to get me closer. One could start Django shell, and then try this:

>>> from django.template.loader import get_template
>>> get_template('template/name').origin.name

to find out what template was actually used.  This is still not enough to see though which templates were considered while resolving the template.


问:
Searching for exact phrase
How do i achieve "Exact Phrase" functionality on this field using BooleanQuery/any other class? For example if a user types in "top selling book" then it should return books which has this phrase in its description.

Thanks again!

答: Having the query within double quotes should work.</p>

Title: Searching for exact phrase

OwnerDisplayName: olle


问:
Apache: help converting .htaccess
I'm trying to convert the following .htaccess rewrite rule to the appropriate NGINX format.

```<code># Redirect /signup/PLANNAME or /signup/PLANNAME/ --> /signup/index.php?account_type=PLANNAME
RewriteEngine on
RewriteRule ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1 [NC,L]
</code>```

I tried using the following NGINX rule, but it's not working.

```<code>rewrite  ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;
</code>```

Any idea what I'm doing wrong to make this work with NGINX? Looking at the official documentation isn't very helpful since the documentation is not very through.

答:
As you're not within a .htaccess file, you have to use absolute paths. As such:</p>

```<code>rewrite  ^/signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;
</code>```

Title: Apache: help converting .htaccess

Body:
I'm trying to convert the following .htaccess rewrite rule to the appropriate NGINX format.

# Redirect /signup/PLANNAME or /signup/PLANNAME/ --> /signup/index.php?account_type=PLANNAME
RewriteEngine on
RewriteRule ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1 [NC,L]

I tried using the following NGINX rule, but it's not working.

rewrite  ^signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;

Any idea what I'm doing wrong to make this work with NGINX? Looking at the official documentation isn't very helpful since the documentation is not very through.

Body:
As you're not within a .htaccess file, you have to use absolute paths. As such:

rewrite  ^/signup/([A-Za-z]+)/?$ /signup/index.php?account_type=$1  last;


问:
How to handle an "Internal Server Error" with Android WebView?
I'm using onReceivedError to intercept any errors when loading webview. Since our webpage had an Internal Server Error and the whole app is based on webview (no native navigation), it will just look like this:

Example Screenshot

This way I intercept errors:

```<code>    @SuppressLint("NewApi")
    public void onReceivedError(final WebView view, WebResourceRequest request, final WebResourceError error) {
        Log.d(TAG, "HTTP error " + error.getErrorCode() + " ---> " + error.getDescription());
        int err = error.getErrorCode();
        if (err == -2) {
            view.loadUrl("about:blank");
            view.loadUrl("file:///android_asset/de_offline.html");
        } else {
            view.reload();
        }
    }
</code>```

Why didn't the app recognize this Internal Server Error? It recognizes if there's no internet connection.

But this error kinda destroys the whole app, because this screen won't go away, even if the webpage is back online. This means I'm forced to setAppCacheEnabled to false.

I guess that is because it's stored in the cache or the reload button is missing. But since we're on a shared hoster, we can't add an reload button to this html error page.

Even if I fully close the app and start it again, this error will be displayed.

The only option for a user would be uninstalling the app or removing the cache manually, but I don't think anyone would do that or in most cases don't know that.

So my question is why the onReceivedError didn't even load the local de_offline.html asset html page instead? Do I have to intercept at some point earlier and what method or where would that be?

答:
Check that the Error Page is not responded with an HTTP 200 Status code. Server Errors should be responded with HTTP-5xx Status codes.
I suspect that the WebView is receiving an HTTP 2xx and "thinks" the response is OK, so your error handling doesn't take place.

Ref: List of HTTP status codes and their meaning

Edit:
I just looked up on: WebViewClient - Error Code
From what I see this describes whole different set of errors. But why?

Another Edit: Oh my ... what the heck?!
As far as I can see there is no way of getting HTTP status codes in a WebView?! This is beyond me.
All I could get is this workaround How can I check from Android WebView if a page is a "404 page not found"?. Adapt this for Internal Server Erros (if applicable use the method from Android SDK API Level 23, where an onReceivedHttpError was added)

Body:
I'm using onReceivedError to intercept any errors when loading webview. Since our webpage had an Internal Server Error and the whole app is based on webview (no native navigation), it will just look like this:

Example Screenshot

This way I intercept errors:

    @SuppressLint("NewApi")
    public void onReceivedError(final WebView view, WebResourceRequest request, final WebResourceError error) {
        Log.d(TAG, "HTTP error " + error.getErrorCode() + " ---> " + error.getDescription());
        int err = error.getErrorCode();
        if (err == -2) {
            view.loadUrl("about:blank");
            view.loadUrl("file:///android_asset/de_offline.html");
        } else {
            view.reload();
        }
    }

Why didn't the app recognize this Internal Server Error? It recognizes if there's no internet connection.

But this error kinda destroys the whole app, because this screen won't go away, even if the webpage is back online. This means I'm forced to setAppCacheEnabled to false.

I guess that is because it's stored in the cache or the reload button is missing. But since we're on a shared hoster, we can't add an reload button to this html error page.

Even if I fully close the app and start it again, this error will be displayed.

The only option for a user would be uninstalling the app or removing the cache manually, but I don't think anyone would do that or in most cases don't know that.

So my question is why the onReceivedError didn't even load the local de_offline.html asset html page instead? Do I have to intercept at some point earlier and what method or where would that be?


问:
i am stucking when i submitt my contact form
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!  </p>

```<code><?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "<script>alert('Message Send')</script>";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>
</code>```

答:
Try this with checking for last inserted id then it will redirect you to your destination script. And please post your html form. Maybe is error in there too. This must work 100%.

Php code in contact-page.php

```<code><?php

include("company_profile/lib/data.config.php");

if(isset($_POST['btnsubmit']))
{
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $cource = mysqli_real_escape_string($conn, $_POST['cource']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    $created_date = date('Y-m-d');
    $time = date('H:i:s');

    $q = "INSERT INTO enquiry_form ( name, email, contact, message, cource, created_date, etime ) VALUES ( '$name', '$email', '$phone', '$message', '$cource', '$created_date', '$time' )";

    $r = mysqli_query($conn, $q);

    // if is returned last inserted id
    if(mysqli_insert_id($conn))
    {
        header("location:thanks.php");
    }
    else
    {
        echo "there was a problem";
    }

}

?>
</code>```

Html form in contact-page.php

```<code><form  action="contact-page.php" method="POST">
    <label>Name</label><br>
    <input type="text" name="name" required /><br>
    <label>Subject</label><br>
    <input type="text" name="cource" required /><br>
    <label>Email</label><br>
    <input type="text" name="email" pattern="[^ @]*@[^ @]*" required /><br>
    <label>Phone</label><br>
    <input type="tel" name="phone" maxlength="10" pattern="[0-9]{10,11}" pattern="[0-9]{10}" required /><br>
    <label>Message</label><br>
    <textarea cols="46" rows="3" name="message" required></textarea><br>
    <input class="button" type="submit" value="Sumbit" name="btnsubmit" />
</form>
</code>```

Body:
I have made a contact from... which is supposed to redirect a user to the "THANK YOU" page once the details of the same is submitted; However on submitting.. the user is not getting directed to the "THANK YOU PAGE". Can you please find out the mistake ? I would be really grateful.. THANK YOU SO MUCH!!

<?php
include("company_profile/lib/data.config.php");
$btnsubmit  =isset($_POST['btnsubmit'])?$_POST['btnsubmit']:'';
if(isset($_POST['btnsubmit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$cource = $_POST['cource'];
$message = $_POST['message'];
$created_date = date('Y-m-d');
$time = date('H:i:s');
$q="Insert INTO enquiry_form SET name='$name',email='$email',
contact='$phone',message='$message',cource='$cource',
created_date='$created_date',etime='$time'";

    $r = mysqli_query($conn,$q);

   if($r)
    {
    //echo "Thankyou for Inquery";
    header("location:thanks.php");
    //echo "";

  }else
  {
    echo "there was a problem";
  }

  }

  ?>

Body:
Try this with checking for last inserted id then it will redirect you to your destination script. And please post your html form. Maybe is error in there too. This must work 100%.

Php code in contact-page.php

<?php

include("company_profile/lib/data.config.php");

if(isset($_POST['btnsubmit']))
{
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    $email = mysqli_real_escape_string($conn, $_POST['email']);
    $phone = mysqli_real_escape_string($conn, $_POST['phone']);
    $cource = mysqli_real_escape_string($conn, $_POST['cource']);
    $message = mysqli_real_escape_string($conn, $_POST['message']);
    $created_date = date('Y-m-d');
    $time = date('H:i:s');

    $q = "INSERT INTO enquiry_form ( name, email, contact, message, cource, created_date, etime ) VALUES ( '$name', '$email', '$phone', '$message', '$cource', '$created_date', '$time' )";

    $r = mysqli_query($conn, $q);

    // if is returned last inserted id
    if(mysqli_insert_id($conn))
    {
        header("location:thanks.php");
    }
    else
    {
        echo "there was a problem";
    }

}

?>

Html form in contact-page.php

<form  action="contact-page.php" method="POST">
    <label>Name</label><br>
    <input type="text" name="name" required /><br>
    <label>Subject</label><br>
    <input type="text" name="cource" required /><br>
    <label>Email</label><br>
    <input type="text" name="email" pattern="[^ @]*@[^ @]*" required /><br>
    <label>Phone</label><br>
    <input type="tel" name="phone" maxlength="10" pattern="[0-9]{10,11}" pattern="[0-9]{10}" required /><br>
    <label>Message</label><br>
    <textarea cols="46" rows="3" name="message" required></textarea><br>
    <input class="button" type="submit" value="Sumbit" name="btnsubmit" />
</form>


问:
MYSQL - Selecting 2 values in same Colum
I am trying to get some products from my database where is has number 1 and 2

```<code>"SELECT * FROM dagenshug_product WHERE stock_quantity > '0' AND product_in_sale = '1' AND category_sex = '1' AND category_sex = '2' AND category_id = '".$req_category_id."' ORDER BY id DESC");
</code>```

As you can see i am choosing category_sex twice, but is only returning ths the values from the first one, (alle with 1)

How do i make it take both? ;)

Thanks for your help

答:
I think you need this:

```<code>"SELECT * FROM dagenshug_product
WHERE
stock_quantity > 0 AND product_in_sale = '1' AND category_sex IN('1', '2') AND category_id = '".$req_category_id."' ORDER BY id DESC");
</code>```

category_sex = '1' AND category_sex = '2' Doesn't makes sense because it  means that value for this column, for same row, should be '1' and '2' same time. this is impossible.

Also not use expressions like this: stock_quantity > '0'. This is math comparison, so you can use directly numeric values: stock_quantity > 0

Body:
I am trying to get some products from my database where is has number 1 and 2

"SELECT * FROM dagenshug_product WHERE stock_quantity > '0' AND product_in_sale = '1' AND category_sex = '1' AND category_sex = '2' AND category_id = '".$req_category_id."' ORDER BY id DESC");

As you can see i am choosing category_sex twice, but is only returning ths the values from the first one, (alle with 1)

How do i make it take both? ;)

Thanks for your help

Body:
I think you need this:

"SELECT * FROM dagenshug_product
WHERE
stock_quantity > 0 AND product_in_sale = '1' AND category_sex IN('1', '2') AND category_id = '".$req_category_id."' ORDER BY id DESC");

category_sex = '1' AND category_sex = '2' Doesn't makes sense because it  means that value for this column, for same row, should be '1' and '2' same time. this is impossible.

Also not use expressions like this: stock_quantity > '0'. This is math comparison, so you can use directly numeric values: stock_quantity > 0


问:
Values of the inserted row in a Trigger Oracle
I want a trigger that updates the value of a column, but I just want to update a small set of rows that depends of the values of the inserted row.
My trigger is:

```<code>CREATE OR REPLACE TRIGGER example
AFTER INSERT ON table1
FOR EACH ROW
BEGIN
UPDATE table1 t
SET column2 = 3
WHERE t.column1 = :new.column1;
END;
/
</code>```

But as I using FOR EACH ROW I have a problem when I try it, I get the mutating table runtime error.
Other option is not to set the FOR EACH ROW, but if I do this, I dont know the inserted "column1" for comparing (or I dont know how to known it).

What can I do for UPDATING a set of rows that depends of the last inserted row?

I am using Oracle 9.

答:
If you need to update multiple rows in table1 when you are updating one row, then you would seem to have a problem with the data model.

This need suggests that you need a separate table with one row per column1. You can then fetch the value in that table using join. The trigger will then be updating another table, so there will be no mutation problem.

Body:
I want a trigger that updates the value of a column, but I just want to update a small set of rows that depends of the values of the inserted row.
My trigger is:

CREATE OR REPLACE TRIGGER example
AFTER INSERT ON table1
FOR EACH ROW
BEGIN
UPDATE table1 t
SET column2 = 3
WHERE t.column1 = :new.column1;
END;
/

But as I using FOR EACH ROW I have a problem when I try it, I get the mutating table runtime error.
Other option is not to set the FOR EACH ROW, but if I do this, I dont know the inserted "column1" for comparing (or I dont know how to known it).

What can I do for UPDATING a set of rows that depends of the last inserted row?

I am using Oracle 9.


问:
How to select multiple rows from mysql with one query and use them in php
I currently have a database like the picture below.

Where there is a query that selects the rows with number1 equaling 1. When using

```<code>mysql_fetch_assoc()
</code>```

in php I am only given the first is there any way to get the second? Like through a dimesional array like

```<code>array['number2'][2]
</code>```

or something similar

答:
This is another easy way

```<code>$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}
</code>```

Demo Link

Body:
I currently have a database like the picture below.

Where there is a query that selects the rows with number1 equaling 1. When using

mysql_fetch_assoc()

in php I am only given the first is there any way to get the second? Like through a dimesional array like

array['number2'][2]

or something similar

Body:
This is another easy way

$sql_shakil ="SELECT app_id, doctor_id FROM patients WHERE doctor_id = 201 ORDER BY ABS(app_id) ASC";
if ($result = $con->query($sql_shakil)) {

while ($row = $result->fetch_assoc()) {
    printf ("%s (%s)\n", $row["app_id"], $row["doctor_id"]);
}

Demo Link


问:
VBA: Find red cells and copy header
Background: I have already used the 'conditional' formatting to highlight the 10 lowest values in each row in light red.

Now, I am trying to compose a code that searches each row for the red marked cells and copies their name from the header row to a new sheet.

What I am aiming for is the following: a code that searches each row for the cells in red and that copies the name (in header) to the same row in another sheet (=result sheet). This should result in a result sheet with 11 columns: first column being the dates and the following 10 columns in that row being the names of the lowest values for that date.

This is the code that I have so far but it does not work:

```<code>Sub CopyReds()

Dim i As Long, j As Long

Dim sPrice As Worksheet
Dim sResult As Worksheet

Set sPrice = Sheets("Prices")
Set sResult = Sheets("Result")

i = 2
For j = 2 To 217
    Do Until i = 1086
        If sPrice.Cells(j, i).Offset(j, 0).Interior.Color = 13551615 Then
            sPrice.Cells(j, i).Copy Destination:=sResult.Cells(2, 2).Offset(j, 1)
        End If
    Loop
Next j

End Sub
</code>```

Update: screenshot worksheet

Update 2: Screenshot result sample

答:
I think that your algorithm should be redesigned: instead of testing the cells displayed color, check if the value is below a limit. This limit can be calculated with WorksheetFunction.Small, which returns the n-th smallest element.

```<code>Sub CopyReds()
    Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
    Dim sResult As Worksheet: Set sResult = Sheets("Result")
    Const colPriceName As Long = 2 ' The column in which cells can be colored red and contains the names to copy
    Const clrCopy As Long = 13551615 ' The color which indicates that the cell should be copied (red)
    Const colResult As Long = 2 ' The column where the results should be copied
    Const rowResultFirst As Long = 2 ' First row on sResult to use for output
    Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
    Const colSort As Long = 2 ' The column in which cells contain the values from which the lowest lngCount should be selected

    Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.UsedRange.Cells(2, colSort).Resize(sPrice.UsedRange.Rows.Count - 1, 1), 10)
    Dim rowResult As Long: rowResult = rowResultFirst
    Dim rowPrice As Long: For rowPrice = 2 To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
        If sPrice.Cells(rowPrice, colSort).Value <= varLimit Then
            sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colPriceName).Value
            rowResult = rowResult + 1
        End If
    Next rowPrice
End Sub
</code>```

Based on the screenshots, I revised the code:

```<code>Sub CopyReds()
    Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
    Dim sResult As Worksheet: Set sResult = Sheets("Result")
    Const rowResultFirst As Long = 2 ' First row on sResult to use for output
    Const rowPriceFirst As Long = 2 ' First row on sPrice to process
    Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
    Const colDate As Long = 1 ' The column which contains the dates
    Const colValueStart As Long = 2 ' The column where values start

    Dim rowResult As Long: rowResult = rowResultFirst
    Dim rowPrice As Long: For rowPrice = rowPriceFirst To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
        Dim colResult As Long: colResult = 1
        sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colDate).Value
        colResult = colResult + 1
        Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.Cells(rowPrice, colValueStart).Resize(1, sPrice.UsedRange.Columns.Count - colValueStart + 1), lngCount)
        Dim colPrice As Long: For colPrice = colValueStart To sPrice.UsedRange.Columns.Count - colValueStart + 1
            If sPrice.Cells(rowPrice, colPrice).Value <= varLimit Then
                sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowResultFirst - 1, colPrice).Value
                colResult = colResult + 1
            End If
        Next colPrice
        rowResult = rowResult + 1
    Next rowPrice
End Sub
</code>```

Title: VBA: Find red cells and copy header

Body:
Background: I have already used the 'conditional' formatting to highlight the 10 lowest values in each row in light red.

Now, I am trying to compose a code that searches each row for the red marked cells and copies their name from the header row to a new sheet.

What I am aiming for is the following: a code that searches each row for the cells in red and that copies the name (in header) to the same row in another sheet (=result sheet). This should result in a result sheet with 11 columns: first column being the dates and the following 10 columns in that row being the names of the lowest values for that date.

This is the code that I have so far but it does not work:

Sub CopyReds()

Dim i As Long, j As Long

Dim sPrice As Worksheet
Dim sResult As Worksheet

Set sPrice = Sheets("Prices")
Set sResult = Sheets("Result")

i = 2
For j = 2 To 217
    Do Until i = 1086
        If sPrice.Cells(j, i).Offset(j, 0).Interior.Color = 13551615 Then
            sPrice.Cells(j, i).Copy Destination:=sResult.Cells(2, 2).Offset(j, 1)
        End If
    Loop
Next j

End Sub

Update: screenshot worksheet

Update 2: Screenshot result sample

Body:
I think that your algorithm should be redesigned: instead of testing the cells displayed color, check if the value is below a limit. This limit can be calculated with WorksheetFunction.Small, which returns the n-th smallest element.

Sub CopyReds()
    Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
    Dim sResult As Worksheet: Set sResult = Sheets("Result")
    Const colPriceName As Long = 2 ' The column in which cells can be colored red and contains the names to copy
    Const clrCopy As Long = 13551615 ' The color which indicates that the cell should be copied (red)
    Const colResult As Long = 2 ' The column where the results should be copied
    Const rowResultFirst As Long = 2 ' First row on sResult to use for output
    Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
    Const colSort As Long = 2 ' The column in which cells contain the values from which the lowest lngCount should be selected

    Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.UsedRange.Cells(2, colSort).Resize(sPrice.UsedRange.Rows.Count - 1, 1), 10)
    Dim rowResult As Long: rowResult = rowResultFirst
    Dim rowPrice As Long: For rowPrice = 2 To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
        If sPrice.Cells(rowPrice, colSort).Value <= varLimit Then
            sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colPriceName).Value
            rowResult = rowResult + 1
        End If
    Next rowPrice
End Sub

Based on the screenshots, I revised the code:

Sub CopyReds()
    Dim sPrice As Worksheet: Set sPrice = Sheets("Prices")
    Dim sResult As Worksheet: Set sResult = Sheets("Result")
    Const rowResultFirst As Long = 2 ' First row on sResult to use for output
    Const rowPriceFirst As Long = 2 ' First row on sPrice to process
    Const lngCount As Long = 10 ' Copy lngCount lowest elements (the actual number may be higher due to ties)
    Const colDate As Long = 1 ' The column which contains the dates
    Const colValueStart As Long = 2 ' The column where values start

    Dim rowResult As Long: rowResult = rowResultFirst
    Dim rowPrice As Long: For rowPrice = rowPriceFirst To sPrice.UsedRange.Rows.Count - sPrice.UsedRange.Row + 1 ' Loop until last row
        Dim colResult As Long: colResult = 1
        sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowPrice, colDate).Value
        colResult = colResult + 1
        Dim varLimit As Variant: varLimit = Application.WorksheetFunction.Small(sPrice.Cells(rowPrice, colValueStart).Resize(1, sPrice.UsedRange.Columns.Count - colValueStart + 1), lngCount)
        Dim colPrice As Long: For colPrice = colValueStart To sPrice.UsedRange.Columns.Count - colValueStart + 1
            If sPrice.Cells(rowPrice, colPrice).Value <= varLimit Then
                sResult.Cells(rowResult, colResult).Value = sPrice.Cells(rowResultFirst - 1, colPrice).Value
                colResult = colResult + 1
            End If
        Next colPrice
        rowResult = rowResult + 1
    Next rowPrice
End Sub


问:
Why can't I input it at once and output it?
This code was run through Atom.

Why can't I input it once and then output it?

Once the desired temperature is entered, the converted temperature should be output.

Conditions: Keep Three Functions, Using a main function to run three functions

```<code>def main():
    print("This program converts Celsius into fahrenheit.")
    print("============================")
    # ===Modify codes below=================
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
    print_fahrenheit_value(celsius_value, fahrenheit_value)
    print("===========================")
    print("Program has ended.")

def input_celsius_value():
    celsius_value = float(input("Enter desired temperature to convert.: "))
    return celsius_value

def convert_celsius_fahrenheit(fahrenheit_value):
    celsius_value = float(input())
    fahrenheit_value = ((9/5) * float(celsius_value)) + 32
    return fahrenheit_value

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(fahrenheit_value)
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)
    return print_fahrenheit_value

if __name__ == '__main__':
    main()
</code>```

答:
In your print_fahrenheit_values function, you have called the other two functions a second time. Once a variable has been returned you don't need to call the function again.

This is what the code should be:

```<code>def print_fahrenheit_value(celsius_value, fahrenheit_value):
    # you have the variables already ^^^^^^^^^^^

    print("Centigrade temperature :", celsius_value)

    print("fahrenheit temperature :", fahrenheit_value)

    return print_fahrenheit_value
</code>```

Body:
This code was run through Atom.

Why can't I input it once and then output it?

Once the desired temperature is entered, the converted temperature should be output.

Conditions: Keep Three Functions, Using a main function to run three functions

def main():
    print("This program converts Celsius into fahrenheit.")
    print("============================")
    # ===Modify codes below=================
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(celsius_value)
    print_fahrenheit_value(celsius_value, fahrenheit_value)
    print("===========================")
    print("Program has ended.")

def input_celsius_value():
    celsius_value = float(input("Enter desired temperature to convert.: "))
    return celsius_value

def convert_celsius_fahrenheit(fahrenheit_value):
    celsius_value = float(input())
    fahrenheit_value = ((9/5) * float(celsius_value)) + 32
    return fahrenheit_value

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    celsius_value = input_celsius_value()
    fahrenheit_value = convert_celsius_fahrenheit(fahrenheit_value)
    print("Centigrade temperature :", celsius_value)
    print("fahrenheit temperature :", fahrenheit_value)
    return print_fahrenheit_value

if __name__ == '__main__':
    main()

Body:
In your print_fahrenheit_values function, you have called the other two functions a second time. Once a variable has been returned you don't need to call the function again.

This is what the code should be:

def print_fahrenheit_value(celsius_value, fahrenheit_value):
    # you have the variables already ^^^^^^^^^^^

    print("Centigrade temperature :", celsius_value)

    print("fahrenheit temperature :", fahrenheit_value)

    return print_fahrenheit_value


答:
```<code>"SELECT * FROM dagenshug_product WHERE stock_quantity > '0' AND product_in_sale = '1' AND (category_sex = '1' OR category_sex = '2') AND category_id = '".$req_category_id."' ORDER BY id DESC");
</code>```

Try this

Title: MYSQL - Selecting 2 values in same Colum

Body:
"SELECT * FROM dagenshug_product WHERE stock_quantity > '0' AND product_in_sale = '1' AND (category_sex = '1' OR category_sex = '2') AND category_id = '".$req_category_id."' ORDER BY id DESC");

Try this


问:
Query to update the content of a cell using
I have a table with the following format:

```<code>column1   column2
   40       blue
   20       red
</code>```

I have I would like to update the contain of my column based on a value entered a TextBox and a comboBox, for example if I select red from my comboBox and enter the value 30 in my TextBox , I would like my table to be updated as follow

```<code>column1   column2
   40       blue
   50       red
</code>```

I thought of something like this:

```<code>update tablename set column1=....+TextBox.Text where column2=ComboBox.Text
</code>```

My question how do I get the current content of that row? do I need a query to do that?

答:
You are so close.  You can just reference the column:

```<code>update tablename
    set column1 = column1 + TextBox.Text
    where column2 = ComboBox.Text;
</code>```

I should note that you should not be constructing the query from user input.  You should be parameterizing the query.  There are two important reasons.  The first is to prevent unexpected syntax errors.  The second is to guard against SQL injection.

If you are just learning to program with SQL, then using parameters is doubly important.  You don't want to start learning bad habits.

Body:
I have a table with the following format:

column1   column2
   40       blue
   20       red

I have I would like to update the contain of my column based on a value entered a TextBox and a comboBox, for example if I select red from my comboBox and enter the value 30 in my TextBox , I would like my table to be updated as follow

column1   column2
   40       blue
   50       red

I thought of something like this:

update tablename set column1=....+TextBox.Text where column2=ComboBox.Text

My question how do I get the current content of that row? do I need a query to do that?

Body:
You are so close.  You can just reference the column:

update tablename
    set column1 = column1 + TextBox.Text
    where column2 = ComboBox.Text;

I should note that you should not be constructing the query from user input.  You should be parameterizing the query.  There are two important reasons.  The first is to prevent unexpected syntax errors.  The second is to guard against SQL injection.

If you are just learning to program with SQL, then using parameters is doubly important.  You don't want to start learning bad habits.


问:
NHibernate and AutoMapper
What is the best way to run raw SQL against NHibernate,  then push it into List  using AutoMapper?

Example:

```<code>public virtual List<T> GetList<T>(string mainsql)
{
    IQuery q = GetSession().CreateSQLQuery(mainsql);
    IEnumerable srcAllRows = q.List();
    List<T> targetAllRows = new List<T>();
    *** do AutoMapper thing to get srcAllRow to targetAllRows ***
    return targetAllRows;
}
</code>```

答:
This is what I ended up with in the do AutoMapper thing section

```<code>public virtual List<T> GetList<T>(string mainSql)
{
    DataTable ldt = new DataTable();
    StartReader(mainSql); //load a reader with data.

    ldt.Load(reader);
    DataTableReader rdr = ldt.CreateDataReader();

    return (List<T>)Mapper.Map<IDataReader, IList<T>>(rdr);
}
</code>```

Title: NHibernate and AutoMapper

Body:
What is the best way to run raw SQL against NHibernate,  then push it into List  using AutoMapper?

Example:

public virtual List<T> GetList<T>(string mainsql)
{
    IQuery q = GetSession().CreateSQLQuery(mainsql);
    IEnumerable srcAllRows = q.List();
    List<T> targetAllRows = new List<T>();
    *** do AutoMapper thing to get srcAllRow to targetAllRows ***
    return targetAllRows;
}

Body:
This is what I ended up with in the do AutoMapper thing section

public virtual List<T> GetList<T>(string mainSql)
{
    DataTable ldt = new DataTable();
    StartReader(mainSql); //load a reader with data.

    ldt.Load(reader);
    DataTableReader rdr = ldt.CreateDataReader();

    return (List<T>)Mapper.Map<IDataReader, IList<T>>(rdr);
}


问:
Conversion of if condition to ternary operator
```<code>status = (Hcill_state == HCILL_STATE_AWAKE)?GPIO_Request(GPIO_5,13):API_FAIL;
</code>```

Is the above code equivalent to the code below?

```<code> if (Hcill_state == HCILL_STATE_AWAKE)
 {
     status = GPIO_Request (GPIO_5,13);
 }
</code>```

答:
The two pieces of code are not equivalent, because the first one performs reassignment unconditionally, while the second one assigns only when the condition is true.

The equivalent of the first code would have an else branch assigning API_FAIL to status:

```<code>if (Hcill_state == HCILL_STATE_AWAKE)
{
    status = GPIO_Request (GPIO_5,13);
}
else
{
    status = API_FAIL;
}
</code>```

Body:
status = (Hcill_state == HCILL_STATE_AWAKE)?GPIO_Request(GPIO_5,13):API_FAIL;

Is the above code equivalent to the code below?

 if (Hcill_state == HCILL_STATE_AWAKE)
 {
     status = GPIO_Request (GPIO_5,13);
 }

Body:
The two pieces of code are not equivalent, because the first one performs reassignment unconditionally, while the second one assigns only when the condition is true.

The equivalent of the first code would have an else branch assigning API_FAIL to status:

if (Hcill_state == HCILL_STATE_AWAKE)
{
    status = GPIO_Request (GPIO_5,13);
}
else
{
    status = API_FAIL;
}


问:
Item position by css?
I am new to html and css. Sorry this too easy question, maybe stupit. vid2 under the vid1, it's ok. But, I try to put vid3 rigth of to vid1. But It isn't working.

Actually, I am tring to do something like that;

index.html;

[vid1]   [vid3]  [vid5]

[vid2]   [vid4]  [vid6]

Could you help me to fix code. Thank you.

.vid1
    {
    position: absolute; overflow:hidden; left: 10px; top: 10px; z-index:0;
    }
    .vid2
    {
    position : absolute; overflow:hidden; left::20px; top:180px;  z-index:0;
    }
    .vid3
    {
    position : absolute; overflow:hidden; left::200px; top:10px;  z-index:0;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><iframe class="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
<iframe class="vid2"  src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
<iframe class="vid3"  src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe></code>```

答:
I would suggest you not to use position: absolute; because it will be too messy if you change the display/window size and also your code will be too complex to work on later.

What i would suggest instead is to go column by column using relative positioning.
Like this:

column-1     column-2     column-3

   [vid1]           [vid3]           [vid5]

   [vid2]           [vid4]           [vid6]

Here's your code with the above relative positioning modifications:

iframe {
  display: block;
  margin: 0 0 10px 0;
}

iframe:nth-child(2) {
  margin: 0;
}

.row {
  clear: both;
  padding: 0px;
  margin: 0px;
}

.column {
  display: block;
  float: left;
  margin: 10px 0 0 0;
}

.column:first-child {
  margin-left: 0;
}

.col_1_of_3 {
  width: 32.66%;
}

@media only screen and (max-width: 1000px) {
  .col_1_of_3 {
    width: 100%;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

<head>
  <meta charset="utf-8">
  <title>title</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>

  <div class="row">

    <!--COLUMN 1-->
    <div class="column col_1_of_3">
      <iframe id="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
      <iframe id="vid3" src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
    </div>

    <!--COLUMN 2-->
    <div class="column col_1_of_3">
      <iframe id="vid2" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
      <iframe id="vid4" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
    </div>

  </div>

</body>

</html></code>```

Run the above Code Snippet in Full Page and verify the layout yourself. The advantage of this code is that, this is easily scalable to add more videos in the same manner specified by you and is also responsive - to work with small devices like tablets and phones.

You can always rely on this simple grid generator tool: http://www.responsivegridsystem.com which generates elegant responsive CSS grid codes.

Let me know if this helps, also feel free to ask questions if you find something ambiguous on my answer.

Title: Item position by css?

Body:
I would suggest you not to use position: absolute; because it will be too messy if you change the display/window size and also your code will be too complex to work on later.

What i would suggest instead is to go column by column using relative positioning.
Like this:

column-1     column-2     column-3

   [vid1]           [vid3]           [vid5]

   [vid2]           [vid4]           [vid6]

Here's your code with the above relative positioning modifications:

iframe {
  display: block;
  margin: 0 0 10px 0;
}

iframe:nth-child(2) {
  margin: 0;
}

.row {
  clear: both;
  padding: 0px;
  margin: 0px;
}

.column {
  display: block;
  float: left;
  margin: 10px 0 0 0;
}

.column:first-child {
  margin-left: 0;
}

.col_1_of_3 {
  width: 32.66%;
}

@media only screen and (max-width: 1000px) {
  .col_1_of_3 {
    width: 100%;
  }
}

<html>

<head>
  <meta charset="utf-8">
  <title>title</title>
  <link rel="stylesheet" type="text/css" href="style.css" />
</head>

<body>

  <div class="row">

    <!--COLUMN 1-->
    <div class="column col_1_of_3">
      <iframe id="vid1" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
      <iframe id="vid3" src="http://www.youtube.com/embed/i7sxqaC062A" frameborder="0" allowfullscreen></iframe>
    </div>

    <!--COLUMN 2-->
    <div class="column col_1_of_3">
      <iframe id="vid2" src="http://www.youtube.com/embed/YeJQBbtjgK8" frameborder="0" allowfullscreen></iframe>
      <iframe id="vid4" src="http://www.youtube.com/embed/r9dsH8H-4P8" frameborder="0" allowfullscreen></iframe>
    </div>

  </div>

</body>

</html>

Run the above Code Snippet in Full Page and verify the layout yourself. The advantage of this code is that, this is easily scalable to add more videos in the same manner specified by you and is also responsive - to work with small devices like tablets and phones.

You can always rely on this simple grid generator tool: http://www.responsivegridsystem.com which generates elegant responsive CSS grid codes.

Let me know if this helps, also feel free to ask questions if you find something ambiguous on my answer.


问:
How to create a new column, by variable?
My data includes data on different people (ID) over each Day of the week and the time they spend in different areas of the hospital or Ward. I am given this time, in minutes:seconds or Duration. An example of my data is:

```<code>ShiftData <- data.frame(ID = c("Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin",
                      "Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin"),
               Day = c("Monday", "Monday", "Monday", "Monday", "Monday",
                       "Monday", "Monday", "Monday", "Monday", "Monday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday"),
               Ward = c("Gen", "Anaesth", "Front Desk", "PreOp", "Front Desk",
                       "PreOp", "Front Desk", "Anaesth", "Front Desk", "Gen",
                       "Gen", "Anaesth", "PreOp", "Front Desk", "Gen",
                       "Front Desk", "PreOp", "PostOp", "Front Desk", "Anaesth"),
               Duration = c("5:35", "4:08", "4:30", "6:33", "4:17",
                            "15:35", "4:28", "9:37", "18:33", "4:20",
                            "9:45", "8:28", "6:37", "2:34", "4:27",
                            "19:35", "4:20", "9:47", "11:33", "4:26"))
</code>```

I first wish to include a column that indicates when each ID was on a rotation or shift. A "Front Desk" in the Ward column indicates when a person alters their shift. A person may start on "Front Desk", regulated by how many hours they work the day before (this calculation not required for the current analysis). My anticipated output would
    be:

```<code>ShiftData$Shift <- c(1,1,0,2,0,
                     1,0,2,0,3,
                     1,1,1,0,2,
                     0,1,1,0,2)
</code>```

My question is similar to this question except when there is a "Front Desk" I want a 0 and any activity afterward, to count sequentially up.

How do I please create this?

I know that I can include a 0 for "Front Desk" using:

```<code>ShiftData$Shift <- ifelse(ShiftData$Ward=='Front Desk', 0, NA)
</code>```

But I am unsure how to include a sequential count for every other part of the column?

答:
Note that your question is quite similar to this one.

So this is a way to solve it:

```<code>library(dplyr)

ShiftData %>%
  group_by(ID, Day) %>%
  mutate(Shift = cumsum(Ward != "Front Desk" & lag(Ward) %in% c("Front Desk", NA))) %>%
  mutate(Shift = ifelse(Ward == "Front Desk", 0, Shift))

# Source: local data frame [20 x 5]
# Groups: ID, Day [4]
#
#        ID     Day       Ward Duration Shift
#    <fctr>  <fctr>     <fctr>   <fctr> <dbl>
# 1  Nelson  Monday        Gen     5:35     1
# 2  Nelson  Monday    Anaesth     4:08     1
# 3  Nelson  Monday Front Desk     4:30     0
# 4  Nelson  Monday      PreOp     6:33     2
# 5  Nelson  Monday Front Desk     4:17     0
# 6  Justin  Monday      PreOp    15:35     1
# 7  Justin  Monday Front Desk     4:28     0
# 8  Justin  Monday    Anaesth     9:37     2
# 9  Justin  Monday Front Desk    18:33     0
# 10 Justin  Monday        Gen     4:20     3
# 11 Nelson Tuesday        Gen     9:45     1
# 12 Nelson Tuesday    Anaesth     8:28     1
# 13 Nelson Tuesday      PreOp     6:37     1
# 14 Nelson Tuesday Front Desk     2:34     0
# 15 Nelson Tuesday        Gen     4:27     2
# 16 Justin Tuesday Front Desk    19:35     0
# 17 Justin Tuesday      PreOp     4:20     1
# 18 Justin Tuesday     PostOp     9:47     1
# 19 Justin Tuesday Front Desk    11:33     0
# 20 Justin Tuesday    Anaesth     4:26     2
</code>```

How it works: After grouping, we create the Shift column by adding 1 each time a non-Front Desk is preceded by a Front Desk. Then we replace Shift by 0 on all Front Desk rows.

Body:
My data includes data on different people (ID) over each Day of the week and the time they spend in different areas of the hospital or Ward. I am given this time, in minutes:seconds or Duration. An example of my data is:

ShiftData <- data.frame(ID = c("Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin",
                      "Nelson", "Nelson", "Nelson", "Nelson", "Nelson",
                      "Justin", "Justin", "Justin", "Justin", "Justin"),
               Day = c("Monday", "Monday", "Monday", "Monday", "Monday",
                       "Monday", "Monday", "Monday", "Monday", "Monday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday",
                      "Tuesday", "Tuesday", "Tuesday", "Tuesday", "Tuesday"),
               Ward = c("Gen", "Anaesth", "Front Desk", "PreOp", "Front Desk",
                       "PreOp", "Front Desk", "Anaesth", "Front Desk", "Gen",
                       "Gen", "Anaesth", "PreOp", "Front Desk", "Gen",
                       "Front Desk", "PreOp", "PostOp", "Front Desk", "Anaesth"),
               Duration = c("5:35", "4:08", "4:30", "6:33", "4:17",
                            "15:35", "4:28", "9:37", "18:33", "4:20",
                            "9:45", "8:28", "6:37", "2:34", "4:27",
                            "19:35", "4:20", "9:47", "11:33", "4:26"))

I first wish to include a column that indicates when each ID was on a rotation or shift. A "Front Desk" in the Ward column indicates when a person alters their shift. A person may start on "Front Desk", regulated by how many hours they work the day before (this calculation not required for the current analysis). My anticipated output would
    be:

ShiftData$Shift <- c(1,1,0,2,0,
                     1,0,2,0,3,
                     1,1,1,0,2,
                     0,1,1,0,2)

My question is similar to this question except when there is a "Front Desk" I want a 0 and any activity afterward, to count sequentially up.

How do I please create this?

I know that I can include a 0 for "Front Desk" using:

ShiftData$Shift <- ifelse(ShiftData$Ward=='Front Desk', 0, NA)

But I am unsure how to include a sequential count for every other part of the column?

Body:
Note that your question is quite similar to this one.

So this is a way to solve it:

library(dplyr)

ShiftData %>%
  group_by(ID, Day) %>%
  mutate(Shift = cumsum(Ward != "Front Desk" & lag(Ward) %in% c("Front Desk", NA))) %>%
  mutate(Shift = ifelse(Ward == "Front Desk", 0, Shift))

# Source: local data frame [20 x 5]
# Groups: ID, Day [4]
#
#        ID     Day       Ward Duration Shift
#    <fctr>  <fctr>     <fctr>   <fctr> <dbl>
# 1  Nelson  Monday        Gen     5:35     1
# 2  Nelson  Monday    Anaesth     4:08     1
# 3  Nelson  Monday Front Desk     4:30     0
# 4  Nelson  Monday      PreOp     6:33     2
# 5  Nelson  Monday Front Desk     4:17     0
# 6  Justin  Monday      PreOp    15:35     1
# 7  Justin  Monday Front Desk     4:28     0
# 8  Justin  Monday    Anaesth     9:37     2
# 9  Justin  Monday Front Desk    18:33     0
# 10 Justin  Monday        Gen     4:20     3
# 11 Nelson Tuesday        Gen     9:45     1
# 12 Nelson Tuesday    Anaesth     8:28     1
# 13 Nelson Tuesday      PreOp     6:37     1
# 14 Nelson Tuesday Front Desk     2:34     0
# 15 Nelson Tuesday        Gen     4:27     2
# 16 Justin Tuesday Front Desk    19:35     0
# 17 Justin Tuesday      PreOp     4:20     1
# 18 Justin Tuesday     PostOp     9:47     1
# 19 Justin Tuesday Front Desk    11:33     0
# 20 Justin Tuesday    Anaesth     4:26     2

How it works: After grouping, we create the Shift column by adding 1 each time a non-Front Desk is preceded by a Front Desk. Then we replace Shift by 0 on all Front Desk rows.