问:
Why include the class name when referring to a static variable?
While doing some Java homework I answered a question by writing an instance method, in the method I made use of some static final variables that belonged to the class the method was in. I wrote the static variable names without prefixing them with the class' name, for example:

```<code>for(int i=0; i < MY_STATIC_VARIABLE; i++)
</code>```

instead of

```<code>for(int i=0; i < MyClass.MY_STATIC_VARIABLE; i++)
</code>```

This compliled and worked correctly. It was only later that I noticed I had forgotten to prefix the class' name. Does it matter whether I include the class name or not? Does a static final variable act like a global variable within the context of its class?

答:
A method can be static and non static. Similarly, inside a method, variables can be static and non static. Inside a it's own class and inside an other class also need to take into consideration. Let's see all the scenario now.

Inside a Static method

Static variable can be accessed by

In same class, either by variable name or class name.variable name.

In different class, only by class name.variable name.

Instance variable can be accessed by

In same class, by object of same class. (i.e) object.variable name.

In  different class, must be by object of relevant class. (i.e) object.variable name.

Inside a Instance method(Non static method)

Static variable can be accessed by

In same class, either by variable name or class name.variable name.

In different class, only by class name.variable name.

Instance variable can be accessed by

In same class, only by variable name.

In different class, must be by object of relevant class.
(i.e) object.variable name.

Body:
While doing some Java homework I answered a question by writing an instance method, in the method I made use of some static final variables that belonged to the class the method was in. I wrote the static variable names without prefixing them with the class' name, for example:

for(int i=0; i < MY_STATIC_VARIABLE; i++)

instead of

for(int i=0; i < MyClass.MY_STATIC_VARIABLE; i++)

This compliled and worked correctly. It was only later that I noticed I had forgotten to prefix the class' name. Does it matter whether I include the class name or not? Does a static final variable act like a global variable within the context of its class?

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
The "XamlCTask" task failed unexpectedly on visual studio for xamarin
When I am trying to run application on Xamarin on visual studio, I am getting error as mentioned below and not able to run the application on device or emulator:

```<code>The "XamlCTask" task failed unexpectedly.
Microsoft.Cci.Pdb.PdbDebugException: Unknown custom metadata item kind: 6
   at Microsoft.Cci.Pdb.PdbFunction.ReadCustomMetadata(BitAccess bits)
   at Microsoft.Cci.Pdb.PdbFunction..ctor(ManProcSym proc, BitAccess bits)
   at Microsoft.Cci.Pdb.PdbFunction.LoadManagedFunctions(BitAccess bits, UInt32 limit, Boolean readStrings)
   at Microsoft.Cci.Pdb.PdbFile.LoadFuncsFromDbiModule(BitAccess bits, DbiModuleInfo info, IntHashTable names, ArrayList funcList, Boolean readStrings, MsfDirectory dir, Dictionary`2 nameIndex, PdbReader reader)
   at Microsoft.Cci.Pdb.PdbFile.LoadFunctions(Stream read, Dictionary`2& tokenToSourceMapping, String& sourceServerData)
   at Mono.Cecil.Pdb.PdbReader.PopulateFunctions()
   at Mono.Cecil.Pdb.PdbReader.ProcessDebugHeader(ImageDebugDirectory directory, Byte[] header)
   at Mono.Cecil.ModuleDefinition.ProcessDebugHeader()
   at Mono.Cecil.ModuleDefinition.ReadSymbols(ISymbolReader reader)
   at Mono.Cecil.ModuleReader.ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
   at Mono.Cecil.ModuleReader.CreateModuleFrom(Image image, ReaderParameters parameters)
   at Mono.Cecil.ModuleDefinition.ReadModule(Stream stream, ReaderParameters parameters)
   at Mono.Cecil.ModuleDefinition.ReadModule(String fileName, ReaderParameters parameters)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Compile()
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__1.MoveNext()  MyFirstProject
</code>```

Before adding this "Xamarin.Forms.Maps" NuGet package, my application working but as I have added this suddenly application stops running and getting error.

Anybody could help me what causes this type of issue?

答: Updating Xamarin.Forms to the latest version on both android and iOS project and reopened the project worked for me. </p>

ContentLicense: CC BY-SA 3.0

Body:
When I am trying to run application on Xamarin on visual studio, I am getting error as mentioned below and not able to run the application on device or emulator:

The "XamlCTask" task failed unexpectedly.
Microsoft.Cci.Pdb.PdbDebugException: Unknown custom metadata item kind: 6
   at Microsoft.Cci.Pdb.PdbFunction.ReadCustomMetadata(BitAccess bits)
   at Microsoft.Cci.Pdb.PdbFunction..ctor(ManProcSym proc, BitAccess bits)
   at Microsoft.Cci.Pdb.PdbFunction.LoadManagedFunctions(BitAccess bits, UInt32 limit, Boolean readStrings)
   at Microsoft.Cci.Pdb.PdbFile.LoadFuncsFromDbiModule(BitAccess bits, DbiModuleInfo info, IntHashTable names, ArrayList funcList, Boolean readStrings, MsfDirectory dir, Dictionary`2 nameIndex, PdbReader reader)
   at Microsoft.Cci.Pdb.PdbFile.LoadFunctions(Stream read, Dictionary`2& tokenToSourceMapping, String& sourceServerData)
   at Mono.Cecil.Pdb.PdbReader.PopulateFunctions()
   at Mono.Cecil.Pdb.PdbReader.ProcessDebugHeader(ImageDebugDirectory directory, Byte[] header)
   at Mono.Cecil.ModuleDefinition.ProcessDebugHeader()
   at Mono.Cecil.ModuleDefinition.ReadSymbols(ISymbolReader reader)
   at Mono.Cecil.ModuleReader.ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
   at Mono.Cecil.ModuleReader.CreateModuleFrom(Image image, ReaderParameters parameters)
   at Mono.Cecil.ModuleDefinition.ReadModule(Stream stream, ReaderParameters parameters)
   at Mono.Cecil.ModuleDefinition.ReadModule(String fileName, ReaderParameters parameters)
   at Xamarin.Forms.Build.Tasks.XamlCTask.Compile()
   at Xamarin.Forms.Build.Tasks.XamlCTask.Execute()
   at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
   at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__1.MoveNext()  MyFirstProject

Before adding this "Xamarin.Forms.Maps" NuGet package, my application working but as I have added this suddenly application stops running and getting error.

Anybody could help me what causes this type of issue?


问:
adding multiplied numbers using javascript

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p></code>```

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p></code>```

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

答:
You just need for get value of text box and add it with result</p>

```<code>function multiplyBy()
{       var sum = 0;
        var num=0;
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
        num =parseInt(num1 * num2);
        num3=parseInt(document.getElementById("result").value);
        document.getElementById("result").value=(num + num3);

}
</script>
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value="0"/>
</p>
</code>```

Body:
function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
       document.getElementById("total").value = +num3 ;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

Total :

<input type="text" name="total" id="total" value=""/>

function multiplyBy()
{
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
       num3= document.getElementById("result").value = num1 * num2;
}

1st Number : <input type="text" id="firstNumber" value="" />

2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" />

The Result is :

<input type="text" name="result" id = "result" value=""/>

I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.

Body:
You just need for get value of text box and add it with result

function multiplyBy()
{       var sum = 0;
        var num=0;
        num1 = document.getElementById("firstNumber").value;
        num2 = document.getElementById("secondNumber").value;
        num =parseInt(num1 * num2);
        num3=parseInt(document.getElementById("result").value);
        document.getElementById("result").value=(num + num3);

}
</script>
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value="0"/>
</p>


问:
Aspectj Pointcut expression not working for one method and working for another method in single class
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

```<code>@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}
</code>```

I have written the aspect as below.

```<code>@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}
</code>```

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.

答:
You need to @RequestMapping(value = "URL", method = RequestMethod.POST) direct to
executeService then its work.</p>

Body:
I have written below code in controller.

For this controllerMethod method the aspectj Pointcut expression is working fine but for executeService method Aspect is not working.

@RequestMapping(value = "URL", method = RequestMethod.POST)
public ModelAndView controllerMethod(@ModelAttribute ModelAttribute reqModel, HttpServletRequest req, HttpServletResponse res) {

    try {
        response = executeService(param1, param2);

    } catch (Exception e) {

    }

    }
private ResponseObject executeService(String param1, String param2){
    //Code....
}

I have written the aspect as below.

@Before("execution(* com.*.*.Controller.executeService(..))")
public void logBefore(JoinPoint joinPoint) {
    logger.info("Before aspect: " + joinPoint.getSignature().getName());
}

Can you please let me know where is the issues. I need to execute aspect before calling executeService method.


问:
Why is javascript not part of the project architecture?
I recently came across a question where someone asked what architecture we use in the company and someone else replied LAMP.

I am not sure why we do not include javascript as a part of the architecture. Is it implied? Or is there something I am missing? What if someone is using say ECMA script or VB script instead of javascript?

答: LAMP refers to the major technologies used on the server side: Linux, Apache, MySQL, and PHP. There are many other pieces to a LAMP installation, but they are either of minor importance (such as the bash shell) or are client-side: HTML, JavaScript, CSS, and so forth.</p>

ContentLicense: CC BY-SA 2.5


问:
codeigniter The requested URL /User was not found on this server
i Have codeigniter 3.0.1 installed in ubuntu 14.04 apache 2.4.7, it was run normally in windows with wamp server but when i move it to the ubuntu server it keep getting that error,the rewrite module already enabled and this is my .htaccess file:

```<code>RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</code>```

and this is the configuration of config.php

```<code>$config['base_url'] = 'http://assets1.uofk.edu';
$config['index_page'] = 'index.php';
$config['uri_protocol'] = 'AUTO';
</code>```

this is routes.php configuration:

```<code>$route['default_controller'] = 'User';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
</code>```

Also i considered the ubuntu case sensitive matter of naming model but still getting not found error..please help

答:
Use this .htaccess

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php?x=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php/$1 [QSA,NC,L]
</code>```

and this is the configuration of config.php

```<code>$config['base_url'] = 'YOUR_URL';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';
</code>```

.htaccess RewriteRule Examples https://www.brontobytes.com/knowledgebase/149/htaccess-RewriteRule-Examples.html

Body:
i Have codeigniter 3.0.1 installed in ubuntu 14.04 apache 2.4.7, it was run normally in windows with wamp server but when i move it to the ubuntu server it keep getting that error,the rewrite module already enabled and this is my .htaccess file:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

and this is the configuration of config.php

$config['base_url'] = 'http://assets1.uofk.edu';
$config['index_page'] = 'index.php';
$config['uri_protocol'] = 'AUTO';

this is routes.php configuration:

$route['default_controller'] = 'User';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

Also i considered the ubuntu case sensitive matter of naming model but still getting not found error..please help

Body:
Use this .htaccess

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php?x=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteCond %{REQUEST_FILENAME} -s
RewriteRule ^(.*)$ index.php/$1 [QSA,NC,L]

and this is the configuration of config.php

$config['base_url'] = 'YOUR_URL';
$config['index_page'] = '';
$config['uri_protocol'] = 'REQUEST_URI';

.htaccess RewriteRule Examples https://www.brontobytes.com/knowledgebase/149/htaccess-RewriteRule-Examples.html


问:
Back button on Action Bar crashing app android
Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.

Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.

Please see the images:

MainActivity

Navigation Drawer

EditProfileActivity

App Crash on clicking the top left arrow

Here is my Manifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".EditProfileActivity"
            android:parentActivityName=".MainActivity" >
            <!-- The meta-data tag is required if you support API level 15 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>
</code>```

Here is my MainActivity.java

package com.example.example;

```<code>import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        Bundle inBundle = getIntent().getExtras();
        String first_name = inBundle.get("first_name").toString();
        String last_name = inBundle.get("last_name").toString();
        String imageUrl = inBundle.get("imageUrl").toString();

        TextView nameView = (TextView)findViewById(R.id.nameView);
        nameView.setText("" + first_name + " " + last_name);
        new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
        return true;
    }
    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if(id == R.id.nav_user_edit){
            Intent intent = new Intent(this, EditProfileActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}
</code>```

答:
In your toolbar.xml set an imageview. Do like this i your toolbar.xml

```<code> <ImageView
    android:id="@+id/tv_header_title2"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:src="@drawable/backbutton"
    android:layout_marginLeft="15dp"/>
</code>```

In MainActivity

```<code> ImageView img= (ImageView) findViewById(R.id.tv_header_title2);

and

  img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
</code>```

Body:
Synposis: I have 3 activity (LoginActivity, MainActivity and EditProfileActivity). After Facebook login in my LoginActivity I srart the MainActivity. (Till this point the app is working perfectly correct with no error). I have a NavigationDrawer for my navigations, When I click on Edit Profile link from the NavigationDrawer it starts the EditProfileActivity.

Problem: When I click on the LeftArrow in the Top blue bar, the app crashes.

Please see the images:

MainActivity

Navigation Drawer

EditProfileActivity

App Crash on clicking the top left arrow

Here is my Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.example">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />

                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
        <activity android:name=".LoginActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main"
            android:theme="@style/AppTheme.NoActionBar">
        </activity>
        <activity android:name=".EditProfileActivity"
            android:parentActivityName=".MainActivity" >

            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>

</manifest>

Here is my MainActivity.java

package com.example.example;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.InputStream;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        Bundle inBundle = getIntent().getExtras();
        String first_name = inBundle.get("first_name").toString();
        String last_name = inBundle.get("last_name").toString();
        String imageUrl = inBundle.get("imageUrl").toString();

        TextView nameView = (TextView)findViewById(R.id.nameView);
        nameView.setText("" + first_name + " " + last_name);
        new DownloadImage((ImageView)findViewById(R.id.imageView)).execute(imageUrl);
        return true;
    }
    public class DownloadImage extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImage(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
                mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        } else if(id == R.id.nav_user_edit){
            Intent intent = new Intent(this, EditProfileActivity.class);
            startActivity(intent);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Body:
In your toolbar.xml set an imageview. Do like this i your toolbar.xml

 <ImageView
    android:id="@+id/tv_header_title2"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_gravity="left"
    android:src="@drawable/backbutton"
    android:layout_marginLeft="15dp"/>

In MainActivity

 ImageView img= (ImageView) findViewById(R.id.tv_header_title2);

and

  img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });


问:
method in class cannot be applied to given types; required: HashMap<String,Integer>
I'm doing this program and I got this error:

Error:(93, 34) error: method getPostDataString in class MainActivity.DownloadTask cannot be applied to given types;
required: HashMap
found: String,int
reason: actual and formal argument lists differ in length

```<code>protected String doInBackground(Object... params) {
            URL url;
            String response = "";
            try {
                url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString("district", 1));
                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
    }
</code>```

With the following method:

```<code>private String getPostDataString(HashMap<String, Integer> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, Integer> entry:params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
        }
        return result.toString();
    }
</code>```

答:
You are passing a string and an integer while calling getPostDataString where as it expects a HashMap<String, Integer>. Java does not convert a string and integer to a map directly. You need to create a map in calling function and send it.

Replace the following statement

```<code> writer.write(getPostDataString("district", 1));
</code>```

with

```<code>Map<String, Integer> m = new HashMap<String, Integer>();
m.put("district",1);
writer.write(getPostDataString(m));
</code>```

Body:
I'm doing this program and I got this error:

Error:(93, 34) error: method getPostDataString in class MainActivity.DownloadTask cannot be applied to given types;
required: HashMap
found: String,int
reason: actual and formal argument lists differ in length

protected String doInBackground(Object... params) {
            URL url;
            String response = "";
            try {
                url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString("district", 1));
                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
    }

With the following method:

private String getPostDataString(HashMap<String, Integer> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, Integer> entry:params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
        }
        return result.toString();
    }

Body:
You are passing a string and an integer while calling getPostDataString where as it expects a HashMap<String, Integer>. Java does not convert a string and integer to a map directly. You need to create a map in calling function and send it.

Replace the following statement

 writer.write(getPostDataString("district", 1));

with

Map<String, Integer> m = new HashMap<String, Integer>();
m.put("district",1);
writer.write(getPostDataString(m));


问:
Mongo is not finding inserted data from Secondary
My Mongo has 2 shards and each shard has 1 primary and 3 secondary.
My service is writing data to primary and there is another worker(SQS worker) is querying to mongo for recent inserted data. But many times it is not able to find that data. How to fix this error.

Thanks in advance for any help.

答:
I hope your reading plays the trick, there is always a delay in updating the data from primary to all secondary nodes. Your scenario might be happening when you have write some data in primary and before the secondary gets the updated data, you are trying to reading it from the secondary.

There is a bunch of documentation related to configuring your secondary nodes. Please go thru them. Please see below some of the references related to replication.

Please check on the write concern for better results.

References:

https://docs.mongodb.com/v3.2/tutorial/configure-replica-set-secondary-sync-target/

https://docs.mongodb.com/manual/core/replica-set-secondary/

https://docs.mongodb.com/manual/replication/

https://docs.mongodb.com/v3.2/tutorial/resync-replica-set-member/

https://docs.mongodb.com/manual/core/replica-set-write-concern/


问:
A last part in query is not working
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

```<code><?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>
</code>```

答:
Try this I have modified my query

```<code>    $query_last  = "SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
    mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
    $new_last_qr ="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date) values (-- Set return values of $query_last --");
mysqli_query ($connect,$new_last_qr)or die (mysqli_error($connect));
</code>```

Thanks

Title: A last part in query is not working

Body:
I have some code, but $query_last is not working, previous  identica part $query  -without problems.

I Don't understand what the problem is.

<?php
    if ($_SERVER["REQUEST_METHOD"]=="POST"){
        require 'connect_k.php';
        createMessage();
    }

    function createMessage(){
        global $connect;
        $email = $_POST["email"];
        $price_main = $_POST["price_main"];
        $date = $_POST["date"];
        $order_number = $_POST["order_number"];
        $query="INSERT INTO final(email,name,size,quantity,price)SELECT email,name,size,quantity,price FROM items_cart WHERE email like ('$email');";
        $query_del="DELETE FROM items_cart WHERE email like ('$email');";
        $query_upd="UPDATE final SET price_main='$price_main',order_number='$order_number',date='$date' WHERE email like ('$email');";
----problem is here----
        $query_last="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date)SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
        mysqli_query ($connect,$query)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_del)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_upd)or die (mysqli_error($connect));
        mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
        mysqli_close($connect);
    }
?>

Body:
Try this I have modified my query

    $query_last  = "SELECT email,name,size,quantity,price,price_main,order_number,date FROM final WHERE email like ('$email');";
    mysqli_query ($connect,$query_last)or die (mysqli_error($connect));
    $new_last_qr ="INSERT INTO order(email,name,size,quantity,price,price_main,order_number,date) values (-- Set return values of $query_last --");
mysqli_query ($connect,$new_last_qr)or die (mysqli_error($connect));

Thanks


问:
UIPopover presenting modal view controller, need notification of it's dismissal
I have an iPad app where I present a UIPopoverController form the right bar button item in my navigation controller.  When an item is selected in the popover it displays a modal view controller.  I need notification in my main viewcontroller that this modal view controller called by my UIPopoverController was dismissed.

I was hoping a simple viewWillShow would work but it is not fired.  Do I have to do some nested type of delegation?  Where I have my dismissed modal notify my popover and then that pass it along down the line?  Was hoping for some simpler solution.

答:
Make the view controller which displays the popover the delegate of the popover and implement this method (see UIPopoverControllerDelegate protocol):</p>

```<code>- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    // Do what you need here and release the popover ivar if you don't need it any more
    [myPopoverController release];
    myPopoverController = nil;
}
</code>```

Body:
Make the view controller which displays the popover the delegate of the popover and implement this method (see UIPopoverControllerDelegate protocol):

- (void)popoverControllerDidDismissPopover:(UIPopoverController *)popoverController
{
    // Do what you need here and release the popover ivar if you don't need it any more
    [myPopoverController release];
    myPopoverController = nil;
}


问:
How to change property of more than one qlineedit at once
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

```<code>void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}
</code>```

答:
If you add all these widget through Qt Designer the objects will have the same name of the variable, so we can get them through findChild, then apply connect the signal ReturnPressed to a lambda function and not having to create a slot for each QLineEdit.

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int n = 100;

    for(int i=0; i<n; i++){
        QString name = QString("L%1").arg(i, 2, 10, QChar('0'));

        QLineEdit* w = findChild<QLineEdit *>(name);
        connect(w, &QLineEdit::returnPressed, [=](){

            QString c = w->text();
            char d = QString(c).at(0).toLatin1();
            if((d>=65&& d<=90)||(d>=97&&d<=122))
            {
                square[i]=d;
                ui->MessageBox->setText("Alphabet succesfully entered");
                w->setReadOnly(true);
                w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
            }
            else
            {
                ui->MessageBox->setText("Enter Alphabets Only");
                w->clear();
            }

        });
    }
}
</code>```

Note: I have considered that square[i] corresponds to the QLineEdit L-i.

Another solution is to connect all to the same slot and obtain the object through the function sender().

*.h

```<code>private slots:
    void onReturnPressed();
</code>```

*.cpp

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    for(QLineEdit* w: findChildren<QLineEdit *>()){
        connect(w, &QLineEdit::returnPressed, this, &MainWindow::onReturnPressed);
    }
}

void MainWindow::onReturnPressed()
{
    QLineEdit* w =qobject_cast<QLineEdit *>(sender());
    int i = w->objectName().remove(0, 1).toInt();
    QString c = w->text();
    char d = QString(c).at(0).toLatin1();
    if((d>=65&& d<=90)||(d>=97&&d<=122))
    {
        square[i]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        w->setReadOnly(true);
        w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        w->clear();
    }
}
</code>```

For old version:

*.h

```<code>private slots:
    void onReturnPressed();
</code>```

.cpp

```<code>MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int n = 100;

    for(int i=0; i<n; i++){
        QString name = QString("L%1").arg(i, 2, 10, QChar('0'));
        QLineEdit* w = findChild<QLineEdit *>(name);
        if(w)
            connect(w, SIGNAL(returnPressed()), this, SLOT(onReturnPressed()));
    }
}

void MainWindow::onReturnPressed()
{
    QLineEdit* w =qobject_cast<QLineEdit *>(sender());
    int i = w->objectName().remove(0, 1).toInt();
    QString c = w->text();
    char d = QString(c).at(0).toLatin1();
    if((d>=65&& d<=90)||(d>=97&&d<=122))
    {
        square[i]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        w->setReadOnly(true);
        w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        w->clear();
    }
}
</code>```

Body:
I have done some coding for L00 (name of my first QLineEdit).

I want to do the same for other 99 widgets (up to L99). I don't wanna copy paste it 100 hundred times.

void MainWindow::on_L00_returnPressed(){
    QString c = ui->L00->text();
    char d = QString(c).at(0).toLatin1();
    if(d>=65&&d<=90||d>=97&&d<=122)
    {
        square[0]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        ui->L00->setReadOnly(true);
        ui->L00->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        ui->L00->setText("");
    }
}

Body:
If you add all these widget through Qt Designer the objects will have the same name of the variable, so we can get them through findChild, then apply connect the signal ReturnPressed to a lambda function and not having to create a slot for each QLineEdit.

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int n = 100;

    for(int i=0; i<n; i++){
        QString name = QString("L%1").arg(i, 2, 10, QChar('0'));

        QLineEdit* w = findChild<QLineEdit *>(name);
        connect(w, &QLineEdit::returnPressed, [=](){

            QString c = w->text();
            char d = QString(c).at(0).toLatin1();
            if((d>=65&& d<=90)||(d>=97&&d<=122))
            {
                square[i]=d;
                ui->MessageBox->setText("Alphabet succesfully entered");
                w->setReadOnly(true);
                w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
            }
            else
            {
                ui->MessageBox->setText("Enter Alphabets Only");
                w->clear();
            }

        });
    }
}

Note: I have considered that square[i] corresponds to the QLineEdit L-i.

Another solution is to connect all to the same slot and obtain the object through the function sender().

*.h

private slots:
    void onReturnPressed();

*.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    for(QLineEdit* w: findChildren<QLineEdit *>()){
        connect(w, &QLineEdit::returnPressed, this, &MainWindow::onReturnPressed);
    }
}

void MainWindow::onReturnPressed()
{
    QLineEdit* w =qobject_cast<QLineEdit *>(sender());
    int i = w->objectName().remove(0, 1).toInt();
    QString c = w->text();
    char d = QString(c).at(0).toLatin1();
    if((d>=65&& d<=90)||(d>=97&&d<=122))
    {
        square[i]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        w->setReadOnly(true);
        w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        w->clear();
    }
}

For old version:

*.h

private slots:
    void onReturnPressed();

.cpp

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    int n = 100;

    for(int i=0; i<n; i++){
        QString name = QString("L%1").arg(i, 2, 10, QChar('0'));
        QLineEdit* w = findChild<QLineEdit *>(name);
        if(w)
            connect(w, SIGNAL(returnPressed()), this, SLOT(onReturnPressed()));
    }
}

void MainWindow::onReturnPressed()
{
    QLineEdit* w =qobject_cast<QLineEdit *>(sender());
    int i = w->objectName().remove(0, 1).toInt();
    QString c = w->text();
    char d = QString(c).at(0).toLatin1();
    if((d>=65&& d<=90)||(d>=97&&d<=122))
    {
        square[i]=d;
        ui->MessageBox->setText("Alphabet succesfully entered");
        w->setReadOnly(true);
        w->setStyleSheet("QLineEdit { background: rgb(0, 255, 255);}");
    }
    else
    {
        ui->MessageBox->setText("Enter Alphabets Only");
        w->clear();
    }
}


问:
Beginner error Python and Atom
Having trouble with Python code in Atom. I'm using 'Learn Python The Hard Way' to practice some coding. When I enter this code into Atom, there is no error but it just won't run (yes, I have Script installed and it works fine for other things). There is a little egg timer in the bottom of Atom but nothing else gives me any indication of what I may be doing wrong.

```<code>print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)
</code>```

When I type like this

```<code>print "How old are you?",
print "How tall are you?",
print "How much do you weigh?",

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)
</code>```

The code runs, but with an error just saying that age is not defined and that makes sense because the code isn't complete. Does that just show that there is no problem with the editor but with the code? So please help. I'm new to this.

答:
Try following

print "So, you're " + str(age) + " old, " + str(height) + " tall and " + str(weight) + " heavy."

Title: Beginner error Python and Atom

Body:
Having trouble with Python code in Atom. I'm using 'Learn Python The Hard Way' to practice some coding. When I enter this code into Atom, there is no error but it just won't run (yes, I have Script installed and it works fine for other things). There is a little egg timer in the bottom of Atom but nothing else gives me any indication of what I may be doing wrong.

print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?",
weight = raw_input()

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

When I type like this

print "How old are you?",
print "How tall are you?",
print "How much do you weigh?",

print "So, you're %r old, %r tall and %r heavy." % (
    age, height, weight)

The code runs, but with an error just saying that age is not defined and that makes sense because the code isn't complete. Does that just show that there is no problem with the editor but with the code? So please help. I'm new to this.


问:
accessing Jenkins HTML report
I have a Jenkins job which uses HTML publisher plugin and executes selenium automation cases and generates a HTML test result report link on Jenkins job details page. i want to pass this HTML report link to stakeholder who can view the report without logging in to Jenkins server but the problem is all the stakeholders  may not have Jenkins account/login setup so is there a way to bypass the authentication part and directly access the html report link(make the report public) which is on Jenkins.
any help highly appreciated..</p>

答:
you can configure this from global security setting in Jenkins. if you are Admin you will have access to this, if not you need to ask your Jenkins Admin for it.

```<code>http://<JenkinsHost>/configureSecurity/
</code>```

Give read-only permission to Anonymous Users for Job should fix the issue. I haven't tested it but it should work I guess.

Caveat: if Jenkins is deployed on public domain or cloud anyone having access to Jenkins URL will be able to see your job and all the important information mentioned in Job Config. So I would not suggest to do it. if it's on private domain, I don't see much risk.

Title: accessing Jenkins HTML report

Body:
you can configure this from global security setting in Jenkins. if you are Admin you will have access to this, if not you need to ask your Jenkins Admin for it.

http://<JenkinsHost>/configureSecurity/

Give read-only permission to Anonymous Users for Job should fix the issue. I haven't tested it but it should work I guess.

Caveat: if Jenkins is deployed on public domain or cloud anyone having access to Jenkins URL will be able to see your job and all the important information mentioned in Job Config. So I would not suggest to do it. if it's on private domain, I don't see much risk.


问:
How to implement conditional branches in Azure Data Factory pipelines
I am implementing a pipeline to insert data updates from csv files to SQL DB. Plan is to first insert the data to temporary SQL table for validation and transformation, and then move processed data to actual SQL table. I would like to branch the pipeline execution depending on the validation result. If data is OK, it will be inserted to target SQL table. If there are fatal fails, insertion activity should be skipped.

Tried to find instructions / guidance but no success so far. Any ideas if pipeline activity supports conditional execution, e.g. based on some properties in input dataset?

答:
The short answer is no.

I think its worth pointing out that ADF is just an orchestration tool to invoke other services. The current version can't do what you want because it does not have any of its own compute. Its not an SSIS data flow engine.

If you want this behaviour you'll need to code it into the SQL DB stored procedures with flags etc on the processed datasets.

Then maybe have some boiler plate code with a parameters that are passed from ADF to perform either the insert or update or divert operation.

Handy link for called stored procedure with params from ADF: https://learn.microsoft.com/en-us/azure/data-factory/data-factory-stored-proc-activity

Hope this helps.


问:
How to retrieve azure iot-hub storage account name
I am writing a PowerShell script that creates iot-hub account with storage account and a streamAnalytics job.

For updating the json file for the streamAnalytics job, I need to retrieve the storage account name that has just been created. Unfortunately, AzureRM has no function to retrieve storage account Name.
Any suggestions on how to do that?

My current script receives it as input from user, but I want the script to be automated and with no need for user input.

答:
got it, I just used:</p>
```<code>$storageAccountName = (Get-AzureRmStorageAccount -ResourceGroupName $IotHubResourceGroupName).storageAccountName
</code>```

Body:
got it, I just used:

$storageAccountName = (Get-AzureRmStorageAccount -ResourceGroupName $IotHubResourceGroupName).storageAccountName


问:
How to calculate max, min and average in postgresql
I want to separate jobs with color based on conversion of what I did as follow:

```<code>select count(ap.id),
       (count(ap.id)/cast(SUM(j.views) as float) * 100) as conversion,
       j.company_id
  from applications ap
          right join jobs j
            on ap.job_id = j.id
 where j.company_id = 61805
 group by j.id
</code>```

if conversion column is greater than 75% of total average of that result, I want to create new alias column and value will be green. if conversion column is between 35% and 75%, column value will be yellow and less than 35%, column value will be red.

Is can be possible do in postgres as above query I've mentioned? Thanks in advance.

答:
Window functions are your friend:

```<code>SELECT count,
       conversion,
       CASE
          WHEN conversion > avg_conv * 0.75
          THEN 'green'
          WHEN conversion < avg_conv * 0.35
          THEN 'red'
          ELSE 'yellow'
       END AS color,
       company_id
FROM (SELECT count,
             conversion,
             avg(conversion) OVER () AS avg_conv,
             company_id
      FROM (SELECT count(ap.id),
                   (count(ap.id)/cast(SUM(j.views) as float) * 100) AS conversion,
                   j.company_id
            FROM applications ap
               RIGHT JOIN jobs j
                  ON ap.job_id = j.id
            WHERE j.company_id = 61805
            GROUP BY j.company_id
           ) with_avg
     ) with_color;
</code>```

(untested)

Body:
I want to separate jobs with color based on conversion of what I did as follow:

select count(ap.id),
       (count(ap.id)/cast(SUM(j.views) as float) * 100) as conversion,
       j.company_id
  from applications ap
          right join jobs j
            on ap.job_id = j.id
 where j.company_id = 61805
 group by j.id

if conversion column is greater than 75% of total average of that result, I want to create new alias column and value will be green. if conversion column is between 35% and 75%, column value will be yellow and less than 35%, column value will be red.

Is can be possible do in postgres as above query I've mentioned? Thanks in advance.

Body:
Window functions are your friend:

SELECT count,
       conversion,
       CASE
          WHEN conversion > avg_conv * 0.75
          THEN 'green'
          WHEN conversion < avg_conv * 0.35
          THEN 'red'
          ELSE 'yellow'
       END AS color,
       company_id
FROM (SELECT count,
             conversion,
             avg(conversion) OVER () AS avg_conv,
             company_id
      FROM (SELECT count(ap.id),
                   (count(ap.id)/cast(SUM(j.views) as float) * 100) AS conversion,
                   j.company_id
            FROM applications ap
               RIGHT JOIN jobs j
                  ON ap.job_id = j.id
            WHERE j.company_id = 61805
            GROUP BY j.company_id
           ) with_avg
     ) with_color;

(untested)


问:
Python - convert .txt content into json format
```<code>Name: Donald J. Trump
Username: @realDonaldTrump
Post: I look forward to paying my respects to our brave men and women on this Memorial Day at Arlington National Cemetery later this morning.
post's link: https://twitter.com/realDonaldTrump/status/869170615881793536
Replies: 16,259 replies
Retweet: 15,103 retweets
Likes: 90,839 likes
Date: 5:36 AM - 29 May 2017
</code>```

Hi all, above is the format of each chunk of data in my first.txt file. I would like to read it and change it to to the json format like the one below, and store it to second.txt file.

```<code>def convert_to_json(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):
with open(path, 'a') as file:
    stringData = [{"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}]

    objData = json.load(stringData)
    file.write(stringData)
</code>```

The above code was suppose to take in data and then append it to second.txt file. However, my code did not manage to append the data i want into my second.txt file. No apparent error was shown at the console, and i seek suggestions and help from all of the experts here.

答:
Add all the data to the list (stringData) and finally write the stringData to the second file using

```<code>stringData = [] #init

def addToDataToBeWritten(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):

    row = {"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}
    stringData.append(raw)

''' Read and call the method here'''
with open(path, 'w') as file:
    file.write(json.dumps(stringData))
</code>```

Body:
Name: Donald J. Trump
Username: @realDonaldTrump
Post: I look forward to paying my respects to our brave men and women on this Memorial Day at Arlington National Cemetery later this morning.
post's link: https://twitter.com/realDonaldTrump/status/869170615881793536
Replies: 16,259 replies
Retweet: 15,103 retweets
Likes: 90,839 likes
Date: 5:36 AM - 29 May 2017

Hi all, above is the format of each chunk of data in my first.txt file. I would like to read it and change it to to the json format like the one below, and store it to second.txt file.

def convert_to_json(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):
with open(path, 'a') as file:
    stringData = [{"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}]

    objData = json.load(stringData)
    file.write(stringData)

The above code was suppose to take in data and then append it to second.txt file. However, my code did not manage to append the data i want into my second.txt file. No apparent error was shown at the console, and i seek suggestions and help from all of the experts here.

Body:
Add all the data to the list (stringData) and finally write the stringData to the second file using

stringData = [] #init

def addToDataToBeWritten(path, name, username, post, link, replies, retweets, likes, retweetby, date, domainname):

    row = {"ContentUrl": link,
    "Text": post,
    "PublishDate": date.strip(),
    "Title": "",
    "SourceUrl": domainname,
    "SocialNetwork": media,
    "Source": "",
    "Author": name,
    "Like_count": likes.strip(),
    "Replies_count": replies.strip(),
    "Retweets_count": retweets.strip(),
    "Schema": "SOCIAL_MEDIA"}
    stringData.append(raw)

''' Read and call the method here'''
with open(path, 'w') as file:
    file.write(json.dumps(stringData))


问:
how to convert an object into a String?
I am getting an output as object, but I want the record to be displayed in text.

答:
If you get the object, you can transform it to string of fly, outputing its properties like that:

```<code>$('#bs).html(result[1].id + result[1].title);
</code>```

corresponding to name of columns, you can also

```<code>console.log(result[1])
</code>```

and check in console correct property names of the object

Title: how to convert an object into a String?

Body:
If you get the object, you can transform it to string of fly, outputing its properties like that:

$('#bs).html(result[1].id + result[1].title);

corresponding to name of columns, you can also

console.log(result[1])

and check in console correct property names of the object


问:
How can I control table name when multiple tables are selected?
I'm using MySQL and I selected three tables in one statement like that:

```<code>SELECT * FROM tb_i, tb_s, tb_t
</code>```

But I need case control by their table names. If a row from tb_s it returns tb_s on additional column table_name.

How can I get table name from this statement?

答:
The way you add up your tables now is a JOIN - meaning that every row is a Cartesian product of three of them - so each row is returned from all the three tables.

If you would like to concatenate the data from the three tables you should use UNION ALL which assumes that the columns are of the same structure. Then you would able to mark the origin table, with an addition constant field.

For instance in your case:

```<code>SELECT tb_i.*,'tb_i' as source
FROM tb_i
UNION ALL
SELECT tb_s.*,'tb_s'
FROM tb_s
UNION ALL
SELECT tb_t.*,'tb_t'
FROM tb_t
</code>```

where the source column is a constant string per each table.

Body:
I'm using MySQL and I selected three tables in one statement like that:

SELECT * FROM tb_i, tb_s, tb_t

But I need case control by their table names. If a row from tb_s it returns tb_s on additional column table_name.

How can I get table name from this statement?

Body:
The way you add up your tables now is a JOIN - meaning that every row is a Cartesian product of three of them - so each row is returned from all the three tables.

If you would like to concatenate the data from the three tables you should use UNION ALL which assumes that the columns are of the same structure. Then you would able to mark the origin table, with an addition constant field.

For instance in your case:

SELECT tb_i.*,'tb_i' as source
FROM tb_i
UNION ALL
SELECT tb_s.*,'tb_s'
FROM tb_s
UNION ALL
SELECT tb_t.*,'tb_t'
FROM tb_t

where the source column is a constant string per each table.


问:
How to check if a file exists (regardless of its file type)?
Edit: The problem wasn't with my c++. The problem was with how I was calling the shared library in GameMaker Studio, which was why it wasn't working.

I'm trying to detect whether a file exists, and I've tried many methods over the internet and none of them seem to work. Here's an example:

```<code>double file_exists(char *filename)
{
    std::ifstream infile(filename);
    return infile.good();
}
</code>```

I assume it will only work with text files. for example, this won't work:

```<code>file_exists("/usr/bin/gedit");
</code>```

...because that is a Linux executable.

I want a means to check whether a file exists regardless of its file type.

On Windows, this can easily be achieved like so:

```<code>double file_exists(char* filename)
{
    DWORD fileAtt = GetFileAttributesA(filename);
    if(fileAtt == INVALID_FILE_ATTRIBUTES)
        throw GetLastError();

    return (bool)((fileAtt&FILE_ATTRIBUTE_DIRECTORY) == 0);
}
</code>```

But I'm on Linux and I need an equivalent of the above snippet that will work on Linux.

答:
If you are on Linux then GCC implements the filesystem Technical Specification, soon to be included in C++17.

You can use std::filesystem::exists.

```<code>#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

int main()
{
    if(fs::exists("/usr/bin/gedit"))
    {
        ...
        // use file here
    }
}
</code>```

Body:
Edit: The problem wasn't with my c++. The problem was with how I was calling the shared library in GameMaker Studio, which was why it wasn't working.

I'm trying to detect whether a file exists, and I've tried many methods over the internet and none of them seem to work. Here's an example:

double file_exists(char *filename)
{
    std::ifstream infile(filename);
    return infile.good();
}

I assume it will only work with text files. for example, this won't work:

file_exists("/usr/bin/gedit");

...because that is a Linux executable.

I want a means to check whether a file exists regardless of its file type.

On Windows, this can easily be achieved like so:

double file_exists(char* filename)
{
    DWORD fileAtt = GetFileAttributesA(filename);
    if(fileAtt == INVALID_FILE_ATTRIBUTES)
        throw GetLastError();

    return (bool)((fileAtt&FILE_ATTRIBUTE_DIRECTORY) == 0);
}

But I'm on Linux and I need an equivalent of the above snippet that will work on Linux.

Body:
If you are on Linux then GCC implements the filesystem Technical Specification, soon to be included in C++17.

You can use std::filesystem::exists.

#include <experimental/filesystem>

namespace fs = std::experimental::filesystem;

int main()
{
    if(fs::exists("/usr/bin/gedit"))
    {
        ...
        // use file here
    }
}


问:
Install and use Protocol Buffers for Java on Windows
The documentation for using Google Protobuf for Java in Windows environment is not very friendly, scattered and puts the new user into confusion. Here is a small attempt to assist the new explorers.</p>

答:
As a simpler approach, especially for occasional users, you could also just:

copy and paste your schema fragment here: https://protogen.marcgravell.com

select "(protoc) Java" (or whatever language you need), and click "generate"

copy out your code, or marvel at the in-editor errors and warnings in your schema fragment

Current limitations:

only a single input and output document is available - this is purely a UI issue (I need to get a tabbed editor working, hopefully this week)

which also means that "import" is heavily constrained - although a few inbuilt imports will work fine ("google/protobuf/duration.proto" for example, will resolve and work correctly)

currently, if the "non protoc" parser detects a syntax error and your schema includes the word "import", it won't invoke "protoc" - this is while I investigate whether protoc could ever be abused to access unexpected files


答:
You should pass map as a parameter in getPostDataString method </p>

```<code>protected String doInBackground(Object... params) {
        URL url;
        String response = "";
        try {
            url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            Map<String, Integer> inputMap = new HashMap<String, Integer>();
            map.put("district", 1);
            writer.write(getPostDataString(map);
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
}
</code>```

Title: method in class cannot be applied to given types; required: HashMap<String,Integer>

Body:
I'm doing this program and I got this error:

Error:(93, 34) error: method getPostDataString in class MainActivity.DownloadTask cannot be applied to given types;
required: HashMap
found: String,int
reason: actual and formal argument lists differ in length

protected String doInBackground(Object... params) {
            URL url;
            String response = "";
            try {
                url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(15000);
                conn.setConnectTimeout(15000);
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                OutputStream os = conn.getOutputStream();
                BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
                writer.write(getPostDataString("district", 1));
                writer.flush();
                writer.close();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpsURLConnection.HTTP_OK) {
                    String line;
                    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    while ((line = br.readLine()) != null) {
                        response += line;
                    }
                } else {
                    response = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return response;
    }

With the following method:

private String getPostDataString(HashMap<String, Integer> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, Integer> entry:params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
        }
        return result.toString();
    }

Body:
You should pass map as a parameter in getPostDataString method

protected String doInBackground(Object... params) {
        URL url;
        String response = "";
        try {
            url = new URL("http://app.iseemobile.com/imenu/getDistrictRestaurants.php");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            Map<String, Integer> inputMap = new HashMap<String, Integer>();
            map.put("district", 1);
            writer.write(getPostDataString(map);
            writer.flush();
            writer.close();
            os.close();
            int responseCode = conn.getResponseCode();
            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line = br.readLine()) != null) {
                    response += line;
                }
            } else {
                response = "";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response;
}


问:
Retrieve lists from Controller to View using Entity Framework
I am trying to retrieve the list of datas in view from controller in ASP.Net .
I have two models

```<code>public class TableGroupModel
{
    public int groupId { get; set; }
    public string groupName { get; set; }
    public string color { get; set; }
    public bool is_active { get; set; }
    public int groupPosition { get; set; }
}
</code>```

and another model

```<code>  public class TableModel
     {
         public int tableId { get; set; }
         public string  tableName { get; set; }
         public bool isReserved { get; set; }
         public int seats { get; set; }
         public string tableType { get; set; }
         //added from cafe_table_group

         List<Models.TableGroupModel> group { get; set; }
     }
</code>```

My controller is

```<code>  public ActionResult Index()
         {
             using(entity_framework.dbEntities e=new entity_framework.dbEntities())
             {

                 var tables = (from c in e.cafe_table
                              join d in e.cafe_table_group on c.cafe_table_group_id equals d.cafe_table_group_id
                              orderby c.cafe_table_group_id
                              select new
                              {
                                  c.cafe_table_id,
                                 c.table_name,
                                  c.seats,
                                   c.is_reserved,
                                  d.cafe_table_group_name,
                                d.color
                              }).ToList();
                 return View(tables);
             }
         }
</code>```

Now how can I use data list in view?

答:
Create ViewModel class and select using that class like this:

```<code>     select new MyViewModel
        {
          TableId=   c.cafe_table_id,
          TableName= c.table_name,
          Seats=     c.seats,
          IsReserved=c.is_reserved,
          GroupName= d.cafe_table_group_name,
          Color= d.color
          }).ToList();
</code>```

In your view(.cshtml file) in first line specify your viewModel like this:

```<code>@model MyViewModel
</code>```

and start using it like this for example:

```<code>  <div> @Model.IsReserved </div>
</code>```

Body:
I am trying to retrieve the list of datas in view from controller in ASP.Net .
I have two models

public class TableGroupModel
{
    public int groupId { get; set; }
    public string groupName { get; set; }
    public string color { get; set; }
    public bool is_active { get; set; }
    public int groupPosition { get; set; }
}

and another model

  public class TableModel
     {
         public int tableId { get; set; }
         public string  tableName { get; set; }
         public bool isReserved { get; set; }
         public int seats { get; set; }
         public string tableType { get; set; }
         //added from cafe_table_group

         List<Models.TableGroupModel> group { get; set; }
     }

My controller is

  public ActionResult Index()
         {
             using(entity_framework.dbEntities e=new entity_framework.dbEntities())
             {

                 var tables = (from c in e.cafe_table
                              join d in e.cafe_table_group on c.cafe_table_group_id equals d.cafe_table_group_id
                              orderby c.cafe_table_group_id
                              select new
                              {
                                  c.cafe_table_id,
                                 c.table_name,
                                  c.seats,
                                   c.is_reserved,
                                  d.cafe_table_group_name,
                                d.color
                              }).ToList();
                 return View(tables);
             }
         }

Now how can I use data list in view?

Body:
Create ViewModel class and select using that class like this:

     select new MyViewModel
        {
          TableId=   c.cafe_table_id,
          TableName= c.table_name,
          Seats=     c.seats,
          IsReserved=c.is_reserved,
          GroupName= d.cafe_table_group_name,
          Color= d.color
          }).ToList();

In your view(.cshtml file) in first line specify your viewModel like this:

@model MyViewModel

and start using it like this for example:

  <div> @Model.IsReserved </div>


问:
Defined but have not been rendered for the layout page in MVC
I get this error:

```<code>The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts".
</code>```

With the following code:

Create.cshtml

```<code>@model BabyStoreII.Models.Category

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Category</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
</code>```

_Layout.cshtml

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <!-- Bootstrap -->
    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Shop by Category", "Index", "Categories")</li>
                    <li>@Html.ActionLink("View all our Products", "Index", "Products")</li>
                </ul>
                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {
                    <div class="form-group">
                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="@Url.Content("/js/bootstrap.js")"></script>
    <script src="@Url.Content("/js/modern-business.js")"></script>
</body>
</html>
</code>```

And my client side validation does not work. It only works when I send the form to server but when I just lose focus an input box, the validation does not kick in. Below is my Model Validation:

Category.cs

```<code>using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BabyStoreII.Models
{
    public class Category
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "The Category name cannot be blank.")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Please enter a category name between 3 and 50 characters in length.")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Please enter a category beginning with a capital letter and made up of letters and spaces only.")]
        [Display(Name="Category Name")]
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}
</code>```

Your help is greatly appreciated.

答:
In you layout page you missing render script section.
So try

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <!-- Bootstrap -->
    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Shop by Category", "Index", "Categories")</li>
                    <li>@Html.ActionLink("View all our Products", "Index", "Products")</li>
                </ul>
                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {
                    <div class="form-group">
                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>© @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="@Url.Content("/js/bootstrap.js")"></script>
    <script src="@Url.Content("/js/modern-business.js")"></script>
    @RenderSection("scripts", false)
</body>
</html>
</code>```

And If you are not using _ViewStart.cshtml then use

```<code>@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create";
}
</code>```

In your create.cshtml page.

Body:
I get this error:

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts".

With the following code:

Create.cshtml

@model BabyStoreII.Models.Category

@{
    ViewBag.Title = "Create";
}

Create

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Category

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                <input type="submit" value="Create" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

_Layout.cshtml

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })

@Html.ActionLink("Home", "Index", "Home")

@Html.ActionLink("Shop by Category", "Index", "Categories")

@Html.ActionLink("View all our Products", "Index", "Products")

                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {

                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })

                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")

        @RenderBody()

© @DateTime.Now.Year - My ASP.NET Application

And my client side validation does not work. It only works when I send the form to server but when I just lose focus an input box, the validation does not kick in. Below is my Model Validation:

Category.cs

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace BabyStoreII.Models
{
    public class Category
    {
        public int ID { get; set; }
        [Required(ErrorMessage = "The Category name cannot be blank.")]
        [StringLength(50, MinimumLength = 3, ErrorMessage = "Please enter a category name between 3 and 50 characters in length.")]
        [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$", ErrorMessage = "Please enter a category beginning with a capital letter and made up of letters and spaces only.")]
        [Display(Name="Category Name")]
        public string Name { get; set; }
        public virtual ICollection<Product> Products { get; set; }
    }
}

Your help is greatly appreciated.

Body:
In you layout page you missing render script section.
So try

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Modern Business - @ViewBag.Title</title>

    <!-- Bootstrap -->
    <link href="@Url.Content("/css/bootstrap.css")" rel="stylesheet">
    <link href="@Url.Content("/css/modern-business.css")" rel="stylesheet">
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
      <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("Shop by Category", "Index", "Categories")</li>
                    <li>@Html.ActionLink("View all our Products", "Index", "Products")</li>
                </ul>
                @using (Html.BeginForm("Index", "Products", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
                {
                    <div class="form-group">
                        @Html.TextBox("Search", null, new { @class = "form-control", @placeholder = "Search Products" })
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                }
                @Html.Partial("_LoginPartial")
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="@Url.Content("/js/bootstrap.js")"></script>
    <script src="@Url.Content("/js/modern-business.js")"></script>
    @RenderSection("scripts", false)
</body>
</html>

And If you are not using _ViewStart.cshtml then use

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Create";
}

In your create.cshtml page.


问:
Why is javascript not part of the project architecture?
I recently came across a question where someone asked what architecture we use in the company and someone else replied LAMP.

I am not sure why we do not include javascript as a part of the architecture. Is it implied? Or is there something I am missing? What if someone is using say ECMA script or VB script instead of javascript?

答:
LAMP is the server architecture.

On the web, it's very much assumed that HTML, JavaScript and CSS comprise the client architecture.

Also, JavaScript is a dialect of ECMAScript with web-browser specific modifications.


问:
Generate a random number in a certain range in MATLAB
How can I generate a random number in MATLAB between 13 and 20?</p>

答:
if you are looking to generate all the number within a specific rang randomly then you can try

```<code>r = randi([a b],1,d)
</code>```

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a

Body:
if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a