问:
How do I set LINESIZE and PAGESIZE with a substitution variable?
I am trying to use a PL/SQL script in SQL*Plus to set the linesize and pagesize based on a developer input on whether a report should print in landscape or portrait orientation. If it is landscape, I want linesize 132 and pagesize 60. If it is portrait, I want 88 and 80 respectively.

I am trying to use substitution variables to do so like this:

```<code>DEFINE PRINT_ORIENTATION 'PORTRAIT'

COLUMN LINESIZE_VALUE NOPRINT new_value LINE
COLUMN PAGESIZE_VALUE NOPRINT new_value PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE
</code>```

However, the system then just prompts me to manually enter values for line and page. What do I need to do to use a substitution variable in the SET command?

答:
With the column .. new_value ... syntax:

```<code>COLUMN Q_LINE NEW_VALUE LINE
COLUMN Q_PAGE NEW_VALUE PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS Q_LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS Q_PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE
</code>```

That allows you to define a substitution value from a query result.

Body:
I am trying to use a PL/SQL script in SQL*Plus to set the linesize and pagesize based on a developer input on whether a report should print in landscape or portrait orientation. If it is landscape, I want linesize 132 and pagesize 60. If it is portrait, I want 88 and 80 respectively.

I am trying to use substitution variables to do so like this:

DEFINE PRINT_ORIENTATION 'PORTRAIT'

COLUMN LINESIZE_VALUE NOPRINT new_value LINE
COLUMN PAGESIZE_VALUE NOPRINT new_value PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE

However, the system then just prompts me to manually enter values for line and page. What do I need to do to use a substitution variable in the SET command?

Body:
With the column .. new_value ... syntax:

COLUMN Q_LINE NEW_VALUE LINE
COLUMN Q_PAGE NEW_VALUE PAGE

SELECT DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 88, 'LANDSCAPE', 132) AS Q_LINE,
       DECODE('&PRINT_ORIENTATION', 'PORTRAIT', 80, 'LANDSCAPE', 60) AS Q_PAGE
FROM DUAL
/

SET LINESIZE &LINE
SET PAGESIZE &PAGE

That allows you to define a substitution value from a query result.


来源: stackexchange

问:
Fetching descendant nodes always return null XML C#
I have an XML file that looks like this

```<code><modules>
<level4>
<module>
  <name>Programming Principles I</name>
  <credit>20</credit>
  <assessments>

    <assessment>
      <assessment_name>Course Work 1</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>
    <assessment>
      <assessment_name>Course Work 2</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>

  </assessments>
</module>
</level4>
</modules>
</code>```

Whilst, getting into assessment childs of parent assessments it returns null..

using this code

```<code>XDocument xml = XDocument.Load("module.xml");
var result = xml.Descendants("module")
                         .FirstOrDefault(x => (string)x.Element("name") == "Programming Principles I");
var assessments = result.Element("assessments");
var assessment = assessments.Descendants("assessment");
foreach(var a in assessment)
{
    a.Remove();
}
</code>```

At this assessment variable I am getting null value exception. The LINQ query works fine but the next two lines I am uncertain. I am actually, removing all the nodes present inside assessments node.

答:
Modifying a lazily-evaluated query while iterating over it is basically dangerous.

Two options:

Use the Remove extension method. Less code, and it'll work! Replace your whole loop with:

```<code>assessment.Remove();
</code>```

Evaluate the query before you start removing anything, storing the result as a list. At this point, it's fine to use foreach because removing the element from its parent won't remove it from the list:

```<code>foreach(var a in assessment.ToList())
{
    a.Remove();
}
</code>```

You still have a problem in your code though - you're using FirstOrDefault() when finding the module element, which means you're anticipating that you might not find it - but you're ignoring that possibility in the next line.

I'd probably rewrite the code to this:

```<code>var assessmentsToRemove = xml
    .Descendants("module")
    .Where(mod => (string) mod.Element("name") == "Programming Principles I")
    .Elements("assessments")
    .Elements("assessment");
assessmentsToRemove.Remove();
</code>```

You could do it all in a single statement if you want, but the above approach makes it easier to diagnose issues later in the debugger.

ContentLicense: CC BY-SA 3.0

Body:
I have an XML file that looks like this

<modules>
<level4>
<module>
  <name>Programming Principles I</name>
  <credit>20</credit>
  <assessments>

    <assessment>
      <assessment_name>Course Work 1</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>
    <assessment>
      <assessment_name>Course Work 2</assessment_name>
      <weight>50</weight>
      <passing>55</passing>
      <obtain>55</obtain>
    </assessment>

  </assessments>
</module>
</level4>
</modules>

Whilst, getting into assessment childs of parent assessments it returns null..

using this code

XDocument xml = XDocument.Load("module.xml");
var result = xml.Descendants("module")
                         .FirstOrDefault(x => (string)x.Element("name") == "Programming Principles I");
var assessments = result.Element("assessments");
var assessment = assessments.Descendants("assessment");
foreach(var a in assessment)
{
    a.Remove();
}

At this assessment variable I am getting null value exception. The LINQ query works fine but the next two lines I am uncertain. I am actually, removing all the nodes present inside assessments node.

Body:
Modifying a lazily-evaluated query while iterating over it is basically dangerous.

Two options:

Use the Remove extension method. Less code, and it'll work! Replace your whole loop with:

assessment.Remove();

Evaluate the query before you start removing anything, storing the result as a list. At this point, it's fine to use foreach because removing the element from its parent won't remove it from the list:

foreach(var a in assessment.ToList())
{
    a.Remove();
}

You still have a problem in your code though - you're using FirstOrDefault() when finding the module element, which means you're anticipating that you might not find it - but you're ignoring that possibility in the next line.

I'd probably rewrite the code to this:

var assessmentsToRemove = xml
    .Descendants("module")
    .Where(mod => (string) mod.Element("name") == "Programming Principles I")
    .Elements("assessments")
    .Elements("assessment");
assessmentsToRemove.Remove();

You could do it all in a single statement if you want, but the above approach makes it easier to diagnose issues later in the debugger.


问:
Application Crashes when using Intent
My application crashes after trying to login.
i created navigationActivity as CHome which i want my user to be directed to. But it keeps crashing :

Unfortnately your app has stopped working.

But when i disabled this lines below it shows the Toast and no crash.

Help please

```<code>Toast.makeText(LoginActivity.this, "CUSTOMER",Toast.LENGTH_SHORT).show();

Intent cHome = new Intent(LoginActivity.this, CHome.class);
Common.currentUser = user;
startActivity(cHome);
finish();
</code>```

and i have my manifest here

my CHome is as follows

```<code>package com.example.oracle.eliteafro;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.TextView;

//import com.example.oracle.eliteafro.Common.Common;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;

public class CHome extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //Init Firebase
    //FirebaseDatabase database;
    //    DatabaseReference salons;

  TextView loginName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chome);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Menu");
        setSupportActionBar(toolbar);

        //Init Firebase
       // database = FirebaseDatabase.getInstance();
        //salons = database.getReference("el_af_salon");

        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);

        //set name for user
        View headerView = navigationView.getHeaderView(0);
        loginName = (TextView) findViewById(R.id.loginName);
        loginName.setText("Beedy");
        //loginName.setText(Common.currentUser.getFullname());

    }

    @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.chome, menu);
        return true;
    }

    @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) {
//
//        }

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

答:
Declare CHome as activity in your AndroidManifest.xml

UPDATE

I saw your updated question, so the problem is on your CHome activity, you are not getting the reference of your TextView before set the text.

```<code>TextView yourTextView = findViewById(R.id.your_text_view_id);
yourTextView.setText("your text");
</code>```

UPDATE 2

Ok, I think that you need to pass parameters, you could pass parameters using extras.

```<code>Intent cHome = new Intent(LoginActivity.this, CHome.class);
cHome.putExtra("user", user);
startActivity(cHome);
finish();
</code>```

Then on your CHome activity class you need to receive the extra :

```<code>@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayout);
        User user = (User)  getIntent().getSerializableExtra("user");
        //now you can use your user object
       TextView yourTextView = findViewById(R.id.your_text_view_id);
       yourTextView.setText(user.getName()); // for example
    }
</code>```

Don't forget your User class has to implements Serializable

Title: Application Crashes when using Intent

Body:
My application crashes after trying to login.
i created navigationActivity as CHome which i want my user to be directed to. But it keeps crashing :

Unfortnately your app has stopped working.

But when i disabled this lines below it shows the Toast and no crash.

Help please

Toast.makeText(LoginActivity.this, "CUSTOMER",Toast.LENGTH_SHORT).show();

Intent cHome = new Intent(LoginActivity.this, CHome.class);
Common.currentUser = user;
startActivity(cHome);
finish();

and i have my manifest here

my CHome is as follows

package com.example.oracle.eliteafro;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.TextView;

//import com.example.oracle.eliteafro.Common.Common;
//import com.google.firebase.database.DatabaseReference;
//import com.google.firebase.database.FirebaseDatabase;

public class CHome extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    //Init Firebase
    //FirebaseDatabase database;
    //    DatabaseReference salons;

  TextView loginName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chome);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Menu");
        setSupportActionBar(toolbar);

        //Init Firebase
       // database = FirebaseDatabase.getInstance();
        //salons = database.getReference("el_af_salon");

        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);

        //set name for user
        View headerView = navigationView.getHeaderView(0);
        loginName = (TextView) findViewById(R.id.loginName);
        loginName.setText("Beedy");
        //loginName.setText(Common.currentUser.getFullname());

    }

    @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.chome, menu);
        return true;
    }

    @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) {
//
//        }

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

Body:
Declare CHome as activity in your AndroidManifest.xml

UPDATE

I saw your updated question, so the problem is on your CHome activity, you are not getting the reference of your TextView before set the text.

TextView yourTextView = findViewById(R.id.your_text_view_id);
yourTextView.setText("your text");

UPDATE 2

Ok, I think that you need to pass parameters, you could pass parameters using extras.

Intent cHome = new Intent(LoginActivity.this, CHome.class);
cHome.putExtra("user", user);
startActivity(cHome);
finish();

Then on your CHome activity class you need to receive the extra :

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yourlayout);
        User user = (User)  getIntent().getSerializableExtra("user");
        //now you can use your user object
       TextView yourTextView = findViewById(R.id.your_text_view_id);
       yourTextView.setText(user.getName()); // for example
    }

Don't forget your User class has to implements Serializable


问:
AngularJS: promise in a loop
I am unable to do the promise looping.

I make a service call to get list of providers, then for each provider, I make another service call to get a customer.

A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.

In other format I am trying to achieve:

```<code>*serviceA.getProvider(){

  foreach(providers){

   foreach(provider.customerID){

    serviceB.getCustomer(customerId)

   }

  }

}
.then(

  foreach(Customer){

   updateTheCustomer;

   addUpdatedCustomerToAList

  }

displayUpdatedCustomreList();

)*
</code>```

I have written following code, that isn't working

```<code>doTheJob(model: Object) {
    let A = [];
    let B = [];

let fetchP = function(obj) {
  obj.Service1.fetchAllP().then(function (response) {
    let P = cloneDeep(response.data);

    _.forEach(P, function(prov) {
      _.forEach(prov.CIds, function(Id) {
        A.push(Id);
      });
    });

    _.forEach(A, function(CId) {
      return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
                                        //So, clearly, returning promise inside loop isn't working
    });
  })
  .then(function(response) {
    B.push(response.data); //This response is undefined

    angular.forEach(B, function (value) {
      obj.updateAdr(value)
    });

    obj.dispay(B);
  });
};
fetchP(this);

}
</code>```

答:
```<code>_.forEach(A, function(CId) {
   return obj.Service2.getById(CId);
}
</code>```

as stated by @Ze Rubeus if you return inside a callback within a for loop that value will be lost, since it's not returned to the caller.

probably you wanted something like this

```<code>return Promise.all(A.map(function(CId){
   //collect each promise inside an array that will then be resolved
   return obj.Service2.getById(CId);
})
</code>```

Title: AngularJS: promise in a loop

Body:
I am unable to do the promise looping.

I make a service call to get list of providers, then for each provider, I make another service call to get a customer.

A provider has 1 or more customers. So eventual list of customer is to be decorated and displayed.

In other format I am trying to achieve:

*serviceA.getProvider(){

  foreach(providers){

   foreach(provider.customerID){

    serviceB.getCustomer(customerId)

   }

  }

}
.then(

  foreach(Customer){

   updateTheCustomer;

   addUpdatedCustomerToAList

  }

displayUpdatedCustomreList();

)*

I have written following code, that isn't working

doTheJob(model: Object) {
    let A = [];
    let B = [];

let fetchP = function(obj) {
  obj.Service1.fetchAllP().then(function (response) {
    let P = cloneDeep(response.data);

    _.forEach(P, function(prov) {
      _.forEach(prov.CIds, function(Id) {
        A.push(Id);
      });
    });

    _.forEach(A, function(CId) {
      return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
                                        //So, clearly, returning promise inside loop isn't working
    });
  })
  .then(function(response) {
    B.push(response.data); //This response is undefined

    angular.forEach(B, function (value) {
      obj.updateAdr(value)
    });

    obj.dispay(B);
  });
};
fetchP(this);

}

Body:
_.forEach(A, function(CId) {
   return obj.Service2.getById(CId);
}

as stated by @Ze Rubeus if you return inside a callback within a for loop that value will be lost, since it's not returned to the caller.

probably you wanted something like this

return Promise.all(A.map(function(CId){
   //collect each promise inside an array that will then be resolved
   return obj.Service2.getById(CId);
})


问:
How to save a structure array to a text file
In MATLAB how do I save a structure array to a text file so that it displays everything the structure array shows in the command window?</p>

答:
To convert any data type to a character vector as displayed in the MATLAB command window, use the function

```<code>str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(yourArray);
</code>```

You can then write the contents to a file

```<code>fid = fopen('myFile.txt', 'w');
fwrite(fid, str, '*char');
fclose(fid);
</code>```

Body:
To convert any data type to a character vector as displayed in the MATLAB command window, use the function

str = matlab.unittest.diagnostics.ConstraintDiagnostic.getDisplayableString(yourArray);

You can then write the contents to a file

fid = fopen('myFile.txt', 'w');
fwrite(fid, str, '*char');
fclose(fid);


问:
How can i continously move the view?
I want to create a simple app in which I want to make a road which is continuously animated. How can I do that?</p>

答:
I used a UIScrollView. Then, set up an NSTimer that runs the following:

```<code>
-(void)scroll{
    CGPoint currentPoint = playerStatsRect.contentOffset;
    CGPoint scrollPoint = CGPointMake(currentPoint.x, currentPoint.y + 1);
    [playerStatsRect setContentOffset:scrollPoint animated:NO];

    if(scrollPoint.y == playerStatsRect.contentSize.height+5)//If we've reached the bottom, reset slightly past top, to give ticker look
    {
        [playerStatsRect setContentOffset:CGPointMake (0,-125)];
    }
}
</code>```

Hope this helps :)

ContentLicense: CC BY-SA 2.5

Title: How can i continously move the view?

Body:
I used a UIScrollView. Then, set up an NSTimer that runs the following:

-(void)scroll{
    CGPoint currentPoint = playerStatsRect.contentOffset;
    CGPoint scrollPoint = CGPointMake(currentPoint.x, currentPoint.y + 1);
    [playerStatsRect setContentOffset:scrollPoint animated:NO];

    if(scrollPoint.y == playerStatsRect.contentSize.height+5)//If we've reached the bottom, reset slightly past top, to give ticker look
    {
        [playerStatsRect setContentOffset:CGPointMake (0,-125)];
    }
}

Hope this helps :)


问:
Reading the contents of several files into a list in Python
I have a shell script which pipes the files of a certain directory into a file titled "list.txt".
I am trying to write a python script that reads in the names of the files inside list.txt, opens them, and saves their contents to a list. Each file inside of list.txt contains two numbers on two different lines. So far, I have been able to read in the files of the names of the files in the directory, however I keep getting an error when trying to read in the contents of the files:

IndexError: list assignment index out of range

Below is the code I have written so far:

```<code>f = open("list.txt")
file = f.readlines()
f.close()
del file[0]
del file[0]
file = [w.replace('\n','') for w in file]
#print file

length_file = len(file)
data = []

for i in range(0,1):
        fa = open(file[i])
#       print fa
        data[i] = fa.read()
        fa.close()
        data[i] = [t.replace('\n','') for t in data]
#print i
#print data
#print data[1]
</code>```

The error occurs on the line data[i] = fa.read() statement.

Any help is greatly appreciated! Thanks in advance!

答:
After further research, I have found a solution that reads in the contents of each of my files, and stores both values in the file as an entry in data using this thread:

Python: How to read a directory of texts into a list

My edited code:

```<code>with open("list.txt") as f:
        file = f.readlines()
f.close()

del file[0]
del file[0]

file = [w.replace('\n','') for w in file]

length_file = len(file)
data = []

for i in range(0, length_file):
        with open(file[i]) as fa:
                data.append(fa.read())
        fa.close()
        data = [t.replace('\n','') for t in data]
#print data[0], data[1]
</code>```

****EDIT****

I now have the code functioning as needed. For others who might need to make a list of lists:

This code reads in the file names of a directory stored in list.txt. It loops through, opens each file by filename and saves the two values inside of the file to the variable data. data contains a list of lists.

```<code>    with open("list.txt") as f:
        file = f.readlines()
f.close()

del file[0]  #in my case removes the first two files in list.txt because they contain irrelevant info
del file[0]

file = [w.replace('\n','') for w in file]

length_file = len(file)
data = []

for i in range(0, length_file):
        with open(file[i]) as fa:
                data.append(fa.read().split('\n'))
        fa.close()
print data[0]
print data
</code>```

For example in this code:

data[0] = [value1 of file1 from list.txt, value2 of file1 from list.txt] and data = [[value1 of file 1 from list.txt , value2 of file1 from list.txt], [value1 of file2 from list.txt, value2 of file 2 from list.txt], ...etc.

Body:
I have a shell script which pipes the files of a certain directory into a file titled "list.txt".
I am trying to write a python script that reads in the names of the files inside list.txt, opens them, and saves their contents to a list. Each file inside of list.txt contains two numbers on two different lines. So far, I have been able to read in the files of the names of the files in the directory, however I keep getting an error when trying to read in the contents of the files:

IndexError: list assignment index out of range

Below is the code I have written so far:

f = open("list.txt")
file = f.readlines()
f.close()
del file[0]
del file[0]
file = [w.replace('\n','') for w in file]
#print file

length_file = len(file)
data = []

for i in range(0,1):
        fa = open(file[i])
#       print fa
        data[i] = fa.read()
        fa.close()
        data[i] = [t.replace('\n','') for t in data]
#print i
#print data
#print data[1]

The error occurs on the line data[i] = fa.read() statement.

Any help is greatly appreciated! Thanks in advance!

Body:
After further research, I have found a solution that reads in the contents of each of my files, and stores both values in the file as an entry in data using this thread:

Python: How to read a directory of texts into a list

My edited code:

with open("list.txt") as f:
        file = f.readlines()
f.close()

del file[0]
del file[0]

file = [w.replace('\n','') for w in file]

length_file = len(file)
data = []

for i in range(0, length_file):
        with open(file[i]) as fa:
                data.append(fa.read())
        fa.close()
        data = [t.replace('\n','') for t in data]
#print data[0], data[1]

****EDIT****

I now have the code functioning as needed. For others who might need to make a list of lists:

This code reads in the file names of a directory stored in list.txt. It loops through, opens each file by filename and saves the two values inside of the file to the variable data. data contains a list of lists.

    with open("list.txt") as f:
        file = f.readlines()
f.close()

del file[0]  #in my case removes the first two files in list.txt because they contain irrelevant info
del file[0]

file = [w.replace('\n','') for w in file]

length_file = len(file)
data = []

for i in range(0, length_file):
        with open(file[i]) as fa:
                data.append(fa.read().split('\n'))
        fa.close()
print data[0]
print data

For example in this code:

data[0] = [value1 of file1 from list.txt, value2 of file1 from list.txt] and data = [[value1 of file 1 from list.txt , value2 of file1 from list.txt], [value1 of file2 from list.txt, value2 of file 2 from list.txt], ...etc.


问:
VBA - Custom Function to close work book - not working
I am trying to write a simple function (in a module FileIO) which would take an instance of a work book, and just close it. This function is invoked from another module Business.
Below is the code snippet.

```<code>Public Function CloseExcelFile(wkBook As Workbook)
    If (wkBook Is Not Nothing) Then
        wkBook.Save
        wkBook.Close
    End If
End Function
</code>```

I invoke this method by using the command FileIO.CloseExcelFile(catWorkBook). Variable catWorkBook is the object reference to the workbook I created (in a step before).

When ever I try too invoke the custom function, I am getting the error

object does not support this method or property

The below command closes the work book with no errors.

```<code>catWorkBook.Close
</code>```

But the same does not happen when I use the custom function. What is going wrong here?

答:
You just have your Not in the wrong place. Try it like this:

```<code>Public Function CloseExcelFile(wkBook As Workbook)
    If Not wkBook Is Nothing Then
        wkBook.Save
        wkBook.Close
    End If
End Function
</code>```

Body:
I am trying to write a simple function (in a module FileIO) which would take an instance of a work book, and just close it. This function is invoked from another module Business.
Below is the code snippet.

Public Function CloseExcelFile(wkBook As Workbook)
    If (wkBook Is Not Nothing) Then
        wkBook.Save
        wkBook.Close
    End If
End Function

I invoke this method by using the command FileIO.CloseExcelFile(catWorkBook). Variable catWorkBook is the object reference to the workbook I created (in a step before).

When ever I try too invoke the custom function, I am getting the error

object does not support this method or property

The below command closes the work book with no errors.

catWorkBook.Close

But the same does not happen when I use the custom function. What is going wrong here?

Body:
You just have your Not in the wrong place. Try it like this:

Public Function CloseExcelFile(wkBook As Workbook)
    If Not wkBook Is Nothing Then
        wkBook.Save
        wkBook.Close
    End If
End Function


问:
Get underlined text with Markdown
How can I underline text in Markdown?</p>

答: In GitHub markdown text works just fine.

ContentLicense: CC BY-SA 4.0

Title: Get underlined text with Markdown

Body: How can I underline text in Markdown?

Body: In GitHub markdown <ins>text</ins> works just fine.


问:
escape dictionary key double quotes when doing println dictionary item in Swift
I've been playing around with Swift, and just came across an issue.
I have the following Dictionary in:

```<code>var locations:Dictionary<String,CLLocationCoordinate2D> = ["current":CLLocationCoordinate2D(latitude: lat, longitude: lng) ];

println("current locaition is \(locations["current"])")
</code>```

but the compiler is complaining about double quotes around current which represent the a key in my dictionary.

I tried escaping it with \ but it wasn't the right way.

Appreciate any help.

答: Since Swift 2.1 you can use double quotes on interpolation. println("current location is \(locations["current"])")

Body:
I've been playing around with Swift, and just came across an issue.
I have the following Dictionary in:

var locations:Dictionary<String,CLLocationCoordinate2D> = ["current":CLLocationCoordinate2D(latitude: lat, longitude: lng) ];

println("current locaition is \(locations["current"])")

but the compiler is complaining about double quotes around current which represent the a key in my dictionary.

I tried escaping it with \ but it wasn't the right way.

Appreciate any help.


问:
Java Jframe get input and write to file
I have one project that I want to get input from jframe. I have to input 3 people data in only one time when code was running and write that data into file name person.txt.Those data have Name Nickname Age and when i compile my code, It dosn't work and I just only write one data in person.txt file. Help me please? I can't get those in my project. what should i do ? </p>

```<code> public class JavaGui {
  public String data = "";
  JFrame f;
  JLabel l1, l2, l3;
  JTextField tf1, tf2, tf3;
  JButton b;
  JavaGui() {

   FileWriter fw = null;
   try {
    fw = new FileWriter("person.txt");
   } catch (IOException ex) {
    Logger.getLogger(JavaGui.class.getName()).log(Level.SEVERE, null, ex);
   }

   PrintWriter pw = new PrintWriter(fw);

   f = new JFrame("Java GUI");
   l1 = new JLabel("Name");
   l1.setBounds(20, 50, 80, 30);
   tf1 = new JTextField();
   tf1.setBounds(100, 50, 200, 30);

   l2 = new JLabel("Nickname");
   l2.setBounds(20, 100, 80, 30);
   tf2 = new JTextField();
   tf2.setBounds(100, 100, 200, 30);

   l3 = new JLabel("Age");
   l3.setBounds(20, 150, 80, 30);
   tf3 = new JTextField();
   tf3.setBounds(100, 150, 200, 30);

   b = new JButton("Save");
   b.setBounds(100, 200, 70, 30);

   f.add(l1);
   f.add(tf1);
   f.add(l2);
   f.add(tf2);
   f.add(l3);
   f.add(tf3);
   f.add(b);
   f.setSize(350, 350);
   f.setLayout(null);
   f.setLocationRelativeTo(null);
   f.setResizable(false);
   f.setVisible(true);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   for (int i = 0; i < 3; i++) {
    b.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {

      String name = "";
      String nickname = "";
      String ageS = "";
      int age = 0;
      try {
       name = "Name : " + tf1.getText();
       nickname = "Nickname : " + tf2.getText();
       age = Integer.parseInt(tf3.getText());

       if (age > 0 && age < 100) {
        ageS = "Age : " + age;
       } else {
        JOptionPane.showMessageDialog(null, "Please Enter Age field by Positive number Or Less than 100");
       }
      } catch (NumberFormatException ex) {
       JOptionPane.showMessageDialog(null, "Please enter Age field by number type");

      }

      data += name + " " + nickname + " " + ageS;

      pw.println(data);
      pw.close();

     }

    });
   }

  }

  public static void main(String[] args) {
   new JavaGui();
  }

 }
</code>```

答:
I want to add more than one person's data in

You want to write to the file using a FileWriter (not a PrintWriter).

Then when you create the FileWriter you can "append" data to the file. Read the FileWriter API for the appropriate constructor to use.

Title: Java Jframe get input and write to file

Body:
I have one project that I want to get input from jframe. I have to input 3 people data in only one time when code was running and write that data into file name person.txt.Those data have Name Nickname Age and when i compile my code, It dosn't work and I just only write one data in person.txt file. Help me please? I can't get those in my project. what should i do ?

 public class JavaGui {
  public String data = "";
  JFrame f;
  JLabel l1, l2, l3;
  JTextField tf1, tf2, tf3;
  JButton b;
  JavaGui() {

   FileWriter fw = null;
   try {
    fw = new FileWriter("person.txt");
   } catch (IOException ex) {
    Logger.getLogger(JavaGui.class.getName()).log(Level.SEVERE, null, ex);
   }

   PrintWriter pw = new PrintWriter(fw);

   f = new JFrame("Java GUI");
   l1 = new JLabel("Name");
   l1.setBounds(20, 50, 80, 30);
   tf1 = new JTextField();
   tf1.setBounds(100, 50, 200, 30);

   l2 = new JLabel("Nickname");
   l2.setBounds(20, 100, 80, 30);
   tf2 = new JTextField();
   tf2.setBounds(100, 100, 200, 30);

   l3 = new JLabel("Age");
   l3.setBounds(20, 150, 80, 30);
   tf3 = new JTextField();
   tf3.setBounds(100, 150, 200, 30);

   b = new JButton("Save");
   b.setBounds(100, 200, 70, 30);

   f.add(l1);
   f.add(tf1);
   f.add(l2);
   f.add(tf2);
   f.add(l3);
   f.add(tf3);
   f.add(b);
   f.setSize(350, 350);
   f.setLayout(null);
   f.setLocationRelativeTo(null);
   f.setResizable(false);
   f.setVisible(true);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   for (int i = 0; i < 3; i++) {
    b.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {

      String name = "";
      String nickname = "";
      String ageS = "";
      int age = 0;
      try {
       name = "Name : " + tf1.getText();
       nickname = "Nickname : " + tf2.getText();
       age = Integer.parseInt(tf3.getText());

       if (age > 0 && age < 100) {
        ageS = "Age : " + age;
       } else {
        JOptionPane.showMessageDialog(null, "Please Enter Age field by Positive number Or Less than 100");
       }
      } catch (NumberFormatException ex) {
       JOptionPane.showMessageDialog(null, "Please enter Age field by number type");

      }

      data += name + " " + nickname + " " + ageS;

      pw.println(data);
      pw.close();

     }

    });
   }

  }

  public static void main(String[] args) {
   new JavaGui();
  }

 }


问:
Images are being squished in Microsoft Edge 16 - Small images in Edge
There is a bug in Microsoft Edge 16 (that has been reported several times and been confirmed here: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7778808/ .

It squishes the image to a height of 30 pixels. Here is an example:

Why does this occur and how do one fix it?

答: What about the Picturefill polyfill?</p>

Body: What about the Picturefill polyfill?


问:
VSSDK: can't build solution with mixed style csproj-projects containing VSIX-projects
I have a solution containing several projects target both net461 and netcoreapp2.0. Also the solution contains VSIX projects with my DslTools extension. VSIX projects use old csproj format while other projects use new csproj format (SDK). But all projects use PackageReference format for nuget references.

So no packages.config, no project.json.

The VSIX project depends on Microsoft.VSSDK.BuildTools nuget package and other packages from VSExtensibility family.

For DSL Tools I have to copy required assets from DSL SDK (Modeling SDK) into my project and reference them explicitly.

The solution is being built in VS2017 just fine.

When I build it via dotnet CLI (dotnet build) I get such an error:

```<code>D:\..\src\packages\microsoft.vssdk.buildtools\15.5.72\tools\VSSDK\Microsoft.VsSDK.targets(82,5): error MSB4062: The "CompareCommonBuildTaskVersion" task could not be loaded from the assembly D:...\src\packages\microsoft.vssdk.buildtools\15.5.72\tools\VSSDL\Microsoft.VisualStudio.Sdk.BuildTasks.dll. Could not load file or assembly 'System.IO.Packaging, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
</code>```

Probably MSBuild under dotnet CLI can't load Microsoft.VisualStudio.Sdk.BuildTasks.dll from VSSDK.

So a VSIX project cannot be built with dotnet CLI.

Then I try to build via msbuild.exe. It should work as it works in VS but it doesn't.

At this time I'm getting:

```<code>"D:..\Src\DslDesigner\Dsl\Dsl.csproj" (default target) (2) ->
(ResolveNuGetPackageAssets target) ->
Z:\Prog\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\NuGet\15.0\Microsoft.NuGet.targets(184,5): error : Your project.json doesn't have a runtimes section. You should add '"runtimes": { "win": { } }' to your project.json and then re-run NuGet restore. [D:...\Src\DslDesigner\Dsl\Dsl.csproj]
</code>```

It's kinda obsolete message in NuGet according this issue. But it's about the message not about an error.

VSIX-csproj's have:
ToolsVersion="15.0"
TargetFrameworkVersion=4.6.1

So I have no idea how to build my solution in command line. Any suggestion?

答:
What helped to resolve the issue - I added the following property into ALL my (old format) csproj-s related to VSIX:</p>

```<code><RuntimeIdentifiers>win</RuntimeIdentifiers>
</code>```

Body:
I have a solution containing several projects target both net461 and netcoreapp2.0. Also the solution contains VSIX projects with my DslTools extension. VSIX projects use old csproj format while other projects use new csproj format (SDK). But all projects use PackageReference format for nuget references.

So no packages.config, no project.json.

The VSIX project depends on Microsoft.VSSDK.BuildTools nuget package and other packages from VSExtensibility family.

For DSL Tools I have to copy required assets from DSL SDK (Modeling SDK) into my project and reference them explicitly.

The solution is being built in VS2017 just fine.

When I build it via dotnet CLI (dotnet build) I get such an error:

D:\..\src\packages\microsoft.vssdk.buildtools\15.5.72\tools\VSSDK\Microsoft.VsSDK.targets(82,5): error MSB4062: The "CompareCommonBuildTaskVersion" task could not be loaded from the assembly D:...\src\packages\microsoft.vssdk.buildtools\15.5.72\tools\VSSDL\Microsoft.VisualStudio.Sdk.BuildTasks.dll. Could not load file or assembly 'System.IO.Packaging, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Probably MSBuild under dotnet CLI can't load Microsoft.VisualStudio.Sdk.BuildTasks.dll from VSSDK.

So a VSIX project cannot be built with dotnet CLI.

Then I try to build via msbuild.exe. It should work as it works in VS but it doesn't.

At this time I'm getting:

"D:..\Src\DslDesigner\Dsl\Dsl.csproj" (default target) (2) ->
(ResolveNuGetPackageAssets target) ->
Z:\Prog\Microsoft Visual Studio\2017\Enterprise\MSBuild\Microsoft\NuGet\15.0\Microsoft.NuGet.targets(184,5): error : Your project.json doesn't have a runtimes section. You should add '"runtimes": { "win": { } }' to your project.json and then re-run NuGet restore. [D:...\Src\DslDesigner\Dsl\Dsl.csproj]

It's kinda obsolete message in NuGet according this issue. But it's about the message not about an error.

VSIX-csproj's have:
ToolsVersion="15.0"
TargetFrameworkVersion=4.6.1

So I have no idea how to build my solution in command line. Any suggestion?

Body:
What helped to resolve the issue - I added the following property into ALL my (old format) csproj-s related to VSIX:

<RuntimeIdentifiers>win</RuntimeIdentifiers>


问:
jQuery disabled buttons
```<code><div id="notattending"><input type="submit" value="Not Attending" /></div>
</code>```

notattending is defined as a jQuery buttonset.

Which attribute or how can I grey it out as if it was disabled? I tried adding disabled="disabled" but it didn't change anything visually.

Thanks

答:
```<code><input type="submit" value="Not Attending" id="mybutton"/>
$('#mybutton').attr('disabled', true);
</code>```

BTW, I don't mean to be offensive, but if you search google with "jquery disable button" you would have found the answer for less than a minute.

Also disabled="disabled" should work:

```<code><input type="submit" value="Not Attending" disabled="disabled"/>
</code>```

Title: jQuery disabled buttons

Body:
<input type="submit" value="Not Attending" />

notattending is defined as a jQuery buttonset.

Which attribute or how can I grey it out as if it was disabled? I tried adding disabled="disabled" but it didn't change anything visually.

Thanks

Body:
<input type="submit" value="Not Attending" id="mybutton"/>
$('#mybutton').attr('disabled', true);

BTW, I don't mean to be offensive, but if you search google with "jquery disable button" you would have found the answer for less than a minute.

Also disabled="disabled" should work:

<input type="submit" value="Not Attending" disabled="disabled"/>


问:
Missing argument In my controller
Hey I am trying to update user profile by sending an id to controller. Every time I submit my form it gives me error missing argument. I have defined route and included id parameter in my controller function but then tooo I get the error.

Code for my controller is

```<code> public function update_avatar(Request $request,$id)
{
    $this->validateInput($request);
    $u = User::findOrFail($id);
    dd($u);
    //Handle the user upload of avatar
    if($request->hasFile('avatar'))
    {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(300,300)->save(public_path('/uploads/'.$filename));

    }
     $user = Auth::user();
        $user->name = $request->name;
        dd($user->name);
        $user->email = $request->email;
        if($request->password == null)
        {
            $user->password = $u->password;
        }
        $user->password = $request->password;
        $user->avatar = $filename;
        $user->role = 'admin';
        $user->save();
    return view('/adminPanel/adminProfile',array('user' => Auth::user()));
}
</code>```

code of my view

```<code>  <form class="form-horizontal" role="form" enctype="multipart/form-data" action="{{ route('profile', ['id' => $user->id]) }}" method="post">
</code>```

And my route is

```<code>  Route::post('/adminPanel/id/adminProfile',
'AdminProfileController@update_avatar')
 ->name('profile')->middleware('admin');;
</code>```

答:
In your route use. You missing parenthesis. When you pass id or any value using route, you have must use parenthesis for this.</p>

```<code>Route::post('/adminPanel/{id}/adminProfile','AdminProfileController@update_avatar')->name('profile')->middleware('admin');
</code>```

Title: Missing argument In my controller

Body:
Hey I am trying to update user profile by sending an id to controller. Every time I submit my form it gives me error missing argument. I have defined route and included id parameter in my controller function but then tooo I get the error.

Code for my controller is

 public function update_avatar(Request $request,$id)
{
    $this->validateInput($request);
    $u = User::findOrFail($id);
    dd($u);
    //Handle the user upload of avatar
    if($request->hasFile('avatar'))
    {
        $avatar = $request->file('avatar');
        $filename = time() . '.' . $avatar->getClientOriginalExtension();
        Image::make($avatar)->resize(300,300)->save(public_path('/uploads/'.$filename));

    }
     $user = Auth::user();
        $user->name = $request->name;
        dd($user->name);
        $user->email = $request->email;
        if($request->password == null)
        {
            $user->password = $u->password;
        }
        $user->password = $request->password;
        $user->avatar = $filename;
        $user->role = 'admin';
        $user->save();
    return view('/adminPanel/adminProfile',array('user' => Auth::user()));
}

code of my view

  <form class="form-horizontal" role="form" enctype="multipart/form-data" action="{{ route('profile', ['id' => $user->id]) }}" method="post">

And my route is

  Route::post('/adminPanel/id/adminProfile',
'AdminProfileController@update_avatar')
 ->name('profile')->middleware('admin');;

Body:
In your route use. You missing parenthesis. When you pass id or any value using route, you have must use parenthesis for this.

Route::post('/adminPanel/{id}/adminProfile','AdminProfileController@update_avatar')->name('profile')->middleware('admin');


问:
Dynamic SQL Procedure with Pivot displaying counts based on Date Range

I have a table which contains multiple user entries.
I want to pull counts of user entries based on date range passed to a stored procedure.

start date: 11/9/2017
end date: 11/11/2017

However the response needs to be dynamic based on amount of days in the date range.

Here is a desired format:

答:
If you are using MySQL this will make what you want:</p>

```<code>SELECT  UserID,
        UserName,
        SUM(Date = '2017-11-09') '2017-11-09',
        SUM(Date = '2017-11-10') '2017-11-10',
        SUM(Date = '2017-11-11') '2017-11-11'
FROM src
GROUP BY UserID
</code>```

Body:
If you are using MySQL this will make what you want:

SELECT  UserID,
        UserName,
        SUM(Date = '2017-11-09') '2017-11-09',
        SUM(Date = '2017-11-10') '2017-11-10',
        SUM(Date = '2017-11-11') '2017-11-11'
FROM src
GROUP BY UserID


问:
Python decorator with arbitrary positioned parameter of decorated function
What would be the way for python decorator to become "polymorphic"? What I mean is it seeks for one exact parameter of decorated function, does something to/with it, then passes the modified parameter to the function. However, this parameter with common name has arbitrary position in any decorated function.</p>

```<code>def decorator(func):
    def wrapper(exactly_this_param, *args):
        new = do_smth(exactly_this_param)
        return func(exactly_this_param=new, *args)
    return wrapper

@decorator
def func1(a, b, exactly_this_param, c):
    # does something

@decorator
def func2(exactly_this_param):
    # does something

@decorator
def func3(a, b, c, d, e, exactly_this_param, *args, **kwargs):
    # does something
</code>```

答:
With keyword arguments (kwargs) this would be easy since *kwargs gives you the names and values of keyword arguments inside the decorator.
So you would receive something like this:

```<code>func3(1,2,3,4,5,6,7,test="hallo")
</code>```

would give you:

```<code>kwargs{'test': 'hallo'}
</code>```

So you could just search for "exactly_this_param" and change it ..

BUT you chose to use normal args. This is one step more but also possible.

So here is a possible solution: (I used python 3)

With "non keyword arguments" (args) you can use the combination of:

args -> gives you a tuple of the actual values of this func call

func.code.co_varnames -> gives you the argument names as in the function definition

I assigned them to the varaible func_params

```<code>func_params = func.__code__.co_varnames
</code>```

So you can look for the index of "exactly_this_param" in func.code.co_varnames and change the value in args at exactly this index as well.  This is this block:

```<code>new_args[func_params.index("exactly_this_param")]=999
</code>```

You also have to convert args to a list (new_args) and back to a tuple, since tuples are immutable in python.

This results in something like this (example code - but running):

```<code>def decorator(func):
def wrapped(*args, **kwargs):
    # a tuple of the names of the parameters that func accepts
    print("    ... decorator magic ....")
    print("    .... args" + str(args))
    print("    .... kwargs" + str(kwargs))
    func_params = func.__code__.co_varnames
    print("    .... param_names:" + str(func_params))
    # grab all of the kwargs that are not accepted by func
    new_args=list(args)
    new_args[func_params.index("exactly_this_param")]=999
    args=tuple(new_args)
    print("    .... new_args" + str(args))
    return func(*args, **kwargs)
return wrapped

@decorator
def func1(a, b, exactly_this_param, c):
    # does something
    print("func1 => exactly_this_slightly_different_param: " + str(exactly_this_param))

@decorator
def func2(exactly_this_param):
    # does something
    print("func2 =>  exactly_this_slightly_different_param: " + str(exactly_this_param))

@decorator
def func3(a, b, c, d, e, exactly_this_param, *args, **kwargs):
    # does something
    print("func3 =>  exactly_this_slightly_different_param: " + str(exactly_this_param))

if __name__ == "__main__":
    func1(1,2,3,4)
    func2(12)
    func3(1,2,3,4,5,6,7,test="hallo")
</code>```

The resulting output shows that the paramter is always found and changed to 999.

```<code>c:\khz\devel>python test_dec.py
    ... decorator magic ....
    .... args(1, 2, 3, 4)
    .... kwargs{}
    .... param_names:('a', 'b', 'exactly_this_param', 'c')
    .... new_args(1, 2, 999, 4)
func1 => exactly_this_slightly_different_param: 999
    ... decorator magic ....
    .... args(12,)
    .... kwargs{}
    .... param_names:('exactly_this_param',)
    .... new_args(999,)
func2 =>  exactly_this_slightly_different_param: 999
    ... decorator magic ....
    .... args(1, 2, 3, 4, 5, 6, 7)
    .... kwargs{'test': 'hallo'}
    .... param_names:('a', 'b', 'c', 'd', 'e', 'exactly_this_param', 'args', 'kwargs')
    .... new_args(1, 2, 3, 4, 5, 999, 7)
func3 =>  exactly_this_slightly_different_param: 999
</code>```

Answer based on this SO question.

Body:
What would be the way for python decorator to become "polymorphic"? What I mean is it seeks for one exact parameter of decorated function, does something to/with it, then passes the modified parameter to the function. However, this parameter with common name has arbitrary position in any decorated function.

def decorator(func):
    def wrapper(exactly_this_param, *args):
        new = do_smth(exactly_this_param)
        return func(exactly_this_param=new, *args)
    return wrapper

@decorator
def func1(a, b, exactly_this_param, c):
    # does something

@decorator
def func2(exactly_this_param):
    # does something

@decorator
def func3(a, b, c, d, e, exactly_this_param, *args, **kwargs):
    # does something

Body:
With keyword arguments (kwargs) this would be easy since *kwargs gives you the names and values of keyword arguments inside the decorator.
So you would receive something like this:

func3(1,2,3,4,5,6,7,test="hallo")

would give you:

kwargs{'test': 'hallo'}

So you could just search for "exactly_this_param" and change it ..

BUT you chose to use normal args. This is one step more but also possible.

So here is a possible solution: (I used python 3)

With "non keyword arguments" (args) you can use the combination of:

args -> gives you a tuple of the actual values of this func call

func.code.co_varnames -> gives you the argument names as in the function definition

I assigned them to the varaible func_params

func_params = func.__code__.co_varnames

So you can look for the index of "exactly_this_param" in func.code.co_varnames and change the value in args at exactly this index as well.  This is this block:

new_args[func_params.index("exactly_this_param")]=999

You also have to convert args to a list (new_args) and back to a tuple, since tuples are immutable in python.

This results in something like this (example code - but running):

def decorator(func):
def wrapped(*args, **kwargs):
    # a tuple of the names of the parameters that func accepts
    print("    ... decorator magic ....")
    print("    .... args" + str(args))
    print("    .... kwargs" + str(kwargs))
    func_params = func.__code__.co_varnames
    print("    .... param_names:" + str(func_params))
    # grab all of the kwargs that are not accepted by func
    new_args=list(args)
    new_args[func_params.index("exactly_this_param")]=999
    args=tuple(new_args)
    print("    .... new_args" + str(args))
    return func(*args, **kwargs)
return wrapped

@decorator
def func1(a, b, exactly_this_param, c):
    # does something
    print("func1 => exactly_this_slightly_different_param: " + str(exactly_this_param))

@decorator
def func2(exactly_this_param):
    # does something
    print("func2 =>  exactly_this_slightly_different_param: " + str(exactly_this_param))

@decorator
def func3(a, b, c, d, e, exactly_this_param, *args, **kwargs):
    # does something
    print("func3 =>  exactly_this_slightly_different_param: " + str(exactly_this_param))

if __name__ == "__main__":
    func1(1,2,3,4)
    func2(12)
    func3(1,2,3,4,5,6,7,test="hallo")

The resulting output shows that the paramter is always found and changed to 999.

c:\khz\devel>python test_dec.py
    ... decorator magic ....
    .... args(1, 2, 3, 4)
    .... kwargs{}
    .... param_names:('a', 'b', 'exactly_this_param', 'c')
    .... new_args(1, 2, 999, 4)
func1 => exactly_this_slightly_different_param: 999
    ... decorator magic ....
    .... args(12,)
    .... kwargs{}
    .... param_names:('exactly_this_param',)
    .... new_args(999,)
func2 =>  exactly_this_slightly_different_param: 999
    ... decorator magic ....
    .... args(1, 2, 3, 4, 5, 6, 7)
    .... kwargs{'test': 'hallo'}
    .... param_names:('a', 'b', 'c', 'd', 'e', 'exactly_this_param', 'args', 'kwargs')
    .... new_args(1, 2, 3, 4, 5, 999, 7)
func3 =>  exactly_this_slightly_different_param: 999

Answer based on this SO question.


问:
Doctrine entity manager find by empty array collection
I have an entity called Cycle, with a OneToMany association to CycleActeur (see code below).

I'd like to be able to fetch all Cycle objets in database with no CycleActeur objects associated, using a simple doctrine findBy* method from my controller.

That is to say something like this :

```<code>$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$cyclesWithNoCycleActeur = $cycleManager->findBy('acteurs', null);
</code>```

Is there a way to do this without having to write a specific method in the CycleRepository ?

Extract from the Cycle class code

```<code>class Cycle {
  /**
   * @ORM\OneToMany(
   *      targetEntity="CycleActeur",
   *      mappedBy="cycle",
   *      orphanRemoval=true)
   */
  private $acteurs;
}
</code>```

Extract from the Cycle class code

```<code>class CycleActeur {
 /**
  * @var Cycle Le cycle concerné
  *
  * @ORM\ManyToOne(targetEntity="Cycle", inversedBy="acteurs")
  * @ORM\JoinColumn(name="cycle_id", referencedColumnName="id")
  *
  */
  private $cycle;
}
</code>```

答:
There's a DQL function SIZE(), which according to Doctrine documentation:

SIZE(collection) - Return the number of elements in the specified collection

So you can use it as a condition like:

```<code>SIZE(acteurs) = 0
</code>```

I'm not sure if it will work with a findBy method, but I would recommend to create a custom method in ESI67Zen2Bundle:Cycle's repository, to make it explicit what the code is doing. Its will work both for DQL Query and Query Builder.

Body:
I have an entity called Cycle, with a OneToMany association to CycleActeur (see code below).

I'd like to be able to fetch all Cycle objets in database with no CycleActeur objects associated, using a simple doctrine findBy* method from my controller.

That is to say something like this :

$manager = $this->getContainer()->get('doctrine.orm.entity_manager');
$cycleManager =  $manager->getRepository('ESI67Zen2Bundle:Cycle');
$cyclesWithNoCycleActeur = $cycleManager->findBy('acteurs', null);

Is there a way to do this without having to write a specific method in the CycleRepository ?

Extract from the Cycle class code

class Cycle {
  /**
   * @ORM\OneToMany(
   *      targetEntity="CycleActeur",
   *      mappedBy="cycle",
   *      orphanRemoval=true)
   */
  private $acteurs;
}

Extract from the Cycle class code

class CycleActeur {
 /**
  * @var Cycle Le cycle concerné
  *
  * @ORM\ManyToOne(targetEntity="Cycle", inversedBy="acteurs")
  * @ORM\JoinColumn(name="cycle_id", referencedColumnName="id")
  *
  */
  private $cycle;
}

Body:
There's a DQL function SIZE(), which according to Doctrine documentation:

SIZE(collection) - Return the number of elements in the specified collection

So you can use it as a condition like:

SIZE(acteurs) = 0

I'm not sure if it will work with a findBy method, but I would recommend to create a custom method in ESI67Zen2Bundle:Cycle's repository, to make it explicit what the code is doing. Its will work both for DQL Query and Query Builder.


问:
VBA, search HTML ElementIDs for text string
During a web data scrape I have the following line which works:

```<code>IE.document.GetElementById("ct175_tocAccept").Click
</code>```

The problem is that the company frequently updates their site at inconsistent intervals and changes the above ct# every time.  Personally, I don't mind updating it frequently, but realistically that's not an option since I have coworkers who often need these results immediately and are unable to resolve the problem on their own.

Is there a way for me to search all ElementIds on that site for the text "tocAccept" and then click that result?  The item does not have a name for me use as an alternative.  All suggestions and solutions are greatly appreciated.

Edit:
Source:

```<code><div class="checkbox">
            <label for="ctl00_ctl76_g_22c8fb90_9788_4417_b231_10df683e9930_ctl00_tocAccept" class="required" aria-required="true">
                <input name="ctl00$ctl76$g_22c8fb90_9788_4417_b231_10df683e9930$ctl00$tocAccept" type="checkbox" id="ctl00_ctl76_g_22c8fb90_9788_4417_b231_10df683e9930_ctl00_tocAccept" aria-required="true" hasvalidation="true" data-rule-required="true" data-msg-required="Yes, I have read, understand and agree to these terms and conditions is required.">
                Yes, I have read, understand and agree to these terms and conditions</label>
        </div>
</code>```

The major problem I'm having is that almost every elementid and name on the page uses the ct175 (now updated to ct176) portion.  Also, to clarify, I said in the original post that the element does not have a name.  The source code I provided does have a name, but there are multiple others that I need to work with that do not have one.

答:
Obviously was unable to test this without having the site in front of me, but you have two objects you can iterate through, and click the one that meets all criteria, which appears to:

Have a parent class of checkbox

Has a tagname of label

Code:

```<code>Option Explicit

Sub TEST()

    ' Code Above

    Dim objCheckbox As Object, objCheckboxes As Object
    Dim objLabel As Object, objLabels As Object
    Set objCheckboxes = ie.document.getElementsByClassName("checkbox")

    For Each objCheckbox In objCheckboxes
        Set objLabels = Nothing
        On Error Resume Next
        Set objLabels = objCheckbox.getElementsByTagName("label")
        On Error GoTo 0
        For Each objLabel In objLabels
            If objLabel.innerText Like "*Yes, I have read, understand and agree*" Then
                objLabel.Click
                Exit For
            End If
        Next objLabel
    Next objCheckbox

End Sub
</code>```

Body:
During a web data scrape I have the following line which works:

IE.document.GetElementById("ct175_tocAccept").Click

The problem is that the company frequently updates their site at inconsistent intervals and changes the above ct# every time.  Personally, I don't mind updating it frequently, but realistically that's not an option since I have coworkers who often need these results immediately and are unable to resolve the problem on their own.

Is there a way for me to search all ElementIds on that site for the text "tocAccept" and then click that result?  The item does not have a name for me use as an alternative.  All suggestions and solutions are greatly appreciated.

Edit:
Source:

                <input name="ctl00$ctl76$g_22c8fb90_9788_4417_b231_10df683e9930$ctl00$tocAccept" type="checkbox" id="ctl00_ctl76_g_22c8fb90_9788_4417_b231_10df683e9930_ctl00_tocAccept" aria-required="true" hasvalidation="true" data-rule-required="true" data-msg-required="Yes, I have read, understand and agree to these terms and conditions is required.">
                Yes, I have read, understand and agree to these terms and conditions

The major problem I'm having is that almost every elementid and name on the page uses the ct175 (now updated to ct176) portion.  Also, to clarify, I said in the original post that the element does not have a name.  The source code I provided does have a name, but there are multiple others that I need to work with that do not have one.

Body:
Obviously was unable to test this without having the site in front of me, but you have two objects you can iterate through, and click the one that meets all criteria, which appears to:

Have a parent class of checkbox

Has a tagname of label

Code:

Option Explicit

Sub TEST()

    ' Code Above

    Dim objCheckbox As Object, objCheckboxes As Object
    Dim objLabel As Object, objLabels As Object
    Set objCheckboxes = ie.document.getElementsByClassName("checkbox")

    For Each objCheckbox In objCheckboxes
        Set objLabels = Nothing
        On Error Resume Next
        Set objLabels = objCheckbox.getElementsByTagName("label")
        On Error GoTo 0
        For Each objLabel In objLabels
            If objLabel.innerText Like "*Yes, I have read, understand and agree*" Then
                objLabel.Click
                Exit For
            End If
        Next objLabel
    Next objCheckbox

End Sub


问:
Determining the available amount of RAM on an iOS device
You've likely seen the many "System Info" apps out there which display things like remaining battery life, and even system info like memory, etc.

In a similar manner, is there any way to retrieve the current amount of available RAM from my app so that I can make better decisions on when it's best to dump or keep certain views to avoid memory warnings?

答:
This works in Swift 4.

The really important difference here is: It casts to Int64 before multiplying, because otherwise you get quickly overflows, especially if you run it in a simulator where it uses the PC Memory.

```<code>var pagesize: vm_size_t = 0

let host_port: mach_port_t = mach_host_self()
var host_size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<vm_statistics_data_t>.stride / MemoryLayout<integer_t>.stride)
host_page_size(host_port, &pagesize)

var vm_stat: vm_statistics = vm_statistics_data_t()
withUnsafeMutablePointer(to: &vm_stat) { (vmStatPointer) -> Void in
    vmStatPointer.withMemoryRebound(to: integer_t.self, capacity: Int(host_size)) {
        if (host_statistics(host_port, HOST_VM_INFO, $0, &host_size) != KERN_SUCCESS) {
            NSLog("Error: Failed to fetch vm statistics")
        }
    }
}

/* Stats in bytes */
let mem_used: Int64 = Int64(vm_stat.active_count +
        vm_stat.inactive_count +
        vm_stat.wire_count) * Int64(pagesize)
let mem_free: Int64 = Int64(vm_stat.free_count) * Int64(pagesize)
</code>```

Body:
This works in Swift 4.

The really important difference here is: It casts to Int64 before multiplying, because otherwise you get quickly overflows, especially if you run it in a simulator where it uses the PC Memory.

var pagesize: vm_size_t = 0

let host_port: mach_port_t = mach_host_self()
var host_size: mach_msg_type_number_t = mach_msg_type_number_t(MemoryLayout<vm_statistics_data_t>.stride / MemoryLayout<integer_t>.stride)
host_page_size(host_port, &pagesize)

var vm_stat: vm_statistics = vm_statistics_data_t()
withUnsafeMutablePointer(to: &vm_stat) { (vmStatPointer) -> Void in
    vmStatPointer.withMemoryRebound(to: integer_t.self, capacity: Int(host_size)) {
        if (host_statistics(host_port, HOST_VM_INFO, $0, &host_size) != KERN_SUCCESS) {
            NSLog("Error: Failed to fetch vm statistics")
        }
    }
}

/* Stats in bytes */
let mem_used: Int64 = Int64(vm_stat.active_count +
        vm_stat.inactive_count +
        vm_stat.wire_count) * Int64(pagesize)
let mem_free: Int64 = Int64(vm_stat.free_count) * Int64(pagesize)


问:
How to include external javascripts clientside with socket.io?
I am trying to include "howler" into the http served by socket i.o. to clients. so that if an event gets triggered and distributed to the clients they get a sound notification.

i tried with the basic example from socket ios getting started page (the chat) from https://socket.io/get-started/chat/ and tried to include howler into the base index.html like this

```<code><!doctype html>
<html>
  <head>
    <title>Socket.IO chat with sound at load</title>
  </head>

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>

  $(function () {

    var socket = io();

    $('form').submit(function(){
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });

  });

</script>
  <body>

    <ul id="messages"></ul>
    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

  <script src="./howler.js"></script>

  <script>

    var sound = new Howl({
      src: ['sound.mp3']
    });

    sound.play();

  </script>

  </body>

</html>
</code>```

but i get a 404 not found Error for localhost:/howler.js

makes sense. for i seem to only serve one file through socket io:

```<code>var app = require('express')();
var http = require('http').Server(app);
var howler = require("howler");
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
  console.log(__dirname);
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
</code>```

my first fix would be to serve the client via /howler.js> but for that i would have to run another http server.

is it possible to include external scripts via the socket io server?

答:
```<code>var app = require('express')();
var http = require('http').Server(app);
var howler = require("howler");
var io = require('socket.io')(http);

app.get('/howler.js', function(req, res){
  res.sendFile(__dirname + '/howler.js');
});

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
  console.log(__dirname);
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});
</code>```

Body:
I am trying to include "howler" into the http served by socket i.o. to clients. so that if an event gets triggered and distributed to the clients they get a sound notification.

i tried with the basic example from socket ios getting started page (the chat) from https://socket.io/get-started/chat/ and tried to include howler into the base index.html like this

<!doctype html>

    <title>Socket.IO chat with sound at load</title>

    <form action="">
      <input id="m" autocomplete="off" /><button>Send</button>
    </form>

but i get a 404 not found Error for localhost:/howler.js

makes sense. for i seem to only serve one file through socket io:

var app = require('express')();
var http = require('http').Server(app);
var howler = require("howler");
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
  console.log(__dirname);
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

my first fix would be to serve the client via /howler.js> but for that i would have to run another http server.

is it possible to include external scripts via the socket io server?


问:
I am getting an error while building grade file
I am trying to build my gradle after adding the following lines

```<code>implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"
</code>```

I get the following error

```<code>Error:(32, 0) Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
<a href="openFile:C:\Users\Sagar\Desktop\SickLab\app\build.gradle">Open File</a>
</code>```

My entire grade file is as follows

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.sagar.sicklab"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation("com.mikepenz:materialdrawer:6.0.1@aar") {
        transitive = true
    }

    implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:support-v4:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.google.android.gms:play-services-ads:11.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'com.github.apl-devs:appintro:v4.2.2'
    compile 'eu.long1:spacetablayout:1.0.4'

}
</code>```

答:
The problem is you haven't defined a objected named "versions" that gradle can access. The error message says that it couldn't find it.

Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

You need to define an object named versions that has a variable called "supportLib" and holds the value of the support library you want to use.

I'm never done this before, so it maybe be completely wrong, but here is some pseudocode that may help you define your object:

```<code>version = new Version(supportLib: "26.1.0")

class Version {
    String supportLib

    String toString() {
        supportLib
    }
}
</code>```

You define this in you same build.gradle file. What will happen when gradle is executed, it will instantiate the versions object and read the version string value from the supportLib field and append it to the support library String. With that being said, I've never seen the "implementation "com.android.support:recyclerview-v7:${versions.supportLib}" syntax before so you definitely will need to experiment. Here is the website that gave me the pseudocode.

Body:
I am trying to build my gradle after adding the following lines

implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

I get the following error

Error:(32, 0) Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Open File

My entire grade file is as follows

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.sagar.sicklab"
        minSdkVersion 21
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:support-v4:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'

    implementation("com.mikepenz:materialdrawer:6.0.1@aar") {
        transitive = true
    }

    implementation "com.android.support:appcompat-v7:${versions.supportLib}"

    implementation "com.android.support:recyclerview-v7:${versions.supportLib}"

    implementation "com.android.support:support-annotations:${versions.supportLib}"

    implementation "com.android.support:design:${versions.supportLib}"

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support:support-v4:26.+'
    compile 'com.android.support:design:26.+'
    compile 'com.google.android.gms:play-services-ads:11.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'

    compile 'com.github.apl-devs:appintro:v4.2.2'
    compile 'eu.long1:spacetablayout:1.0.4'

}

Body:
The problem is you haven't defined a objected named "versions" that gradle can access. The error message says that it couldn't find it.

Could not get unknown property 'versions' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler

You need to define an object named versions that has a variable called "supportLib" and holds the value of the support library you want to use.

I'm never done this before, so it maybe be completely wrong, but here is some pseudocode that may help you define your object:

version = new Version(supportLib: "26.1.0")

class Version {
    String supportLib

    String toString() {
        supportLib
    }
}

You define this in you same build.gradle file. What will happen when gradle is executed, it will instantiate the versions object and read the version string value from the supportLib field and append it to the support library String. With that being said, I've never seen the "implementation "com.android.support:recyclerview-v7:${versions.supportLib}" syntax before so you definitely will need to experiment. Here is the website that gave me the pseudocode.


问:
Rails: Hide "Edit" and "Destroy" unless logged in as Admin
I'm brand new to rails, and am creating a simple glossary app using Rails 5 with gems Devise and Pundit. I generated an Admin model with Devise; that's the only role that needs to be logged in. I installed Pundit to create policies that would allow me to hide the "Edit," "Destroy," and "New" buttons unless logged in as admin.
Glossary App Index

After adding the below policy code to my index.html.erb file to hide the 'Edit' and 'Destroy' buttons, I'm getting an "Undefined method 'current_user'" error.

```<code><tbody>
      <% @terms.each do |term| %>
        <tr>
          <td><%= term.name %></td>
          <td><%= term.category %></td>
          <td><%= term.definition %></td>
          <td><%= link_to 'Show', term, class: 'btn btn-mini' %></td>
          <td>
            <% if policy(@term).edit? %>
              <%= link_to 'Edit', edit_term_path(term), class: 'btn btn-mini' %>
            <% end %>
          </td>
          <td>
            <% if policy(@term).destroy? %>
              <%= link_to 'Destroy', term, method: :delete, class: 'btn btn-mini', data: { confirm: 'Are you sure?' } %>
            <% end %>
          </td>
        </tr>
      <% end %>
    </tbody>
</code>```

Since I didn't generate a "User" model with Devise, but generated an "Admin" model instead, it seemed logical that the error was referring to the word "user" in my new policies. So I replaced "user" with "admin" in my application_policy.rb and terms_policy.rb. Clearly I don't understand what "user" means in this error, as I'm still getting it.

I don't know what exactly you need to see, so here are my models, controllers, and policies:

application_record.rb

```<code>class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end
</code>```

admin.rb

```<code>class Admin < ApplicationRecord
  has_many :terms
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :trackable, :timeoutable, :lockable
end
</code>```

term.rb

```<code>class Term < ApplicationRecord
  belongs_to :admin

  def self.search(search)
    if search
      where(["name LIKE ?","%#{search}%"])
    else
      all
    end
  end

end
</code>```

application_controller.rb

```<code>class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery with: :exception
  before_action :set_current_user

  def set_current_user
    Term.current_user = current_user
  end
end
</code>```

terms_controller.rb

```<code>class TermsController < ApplicationController
  before_action :set_term, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, :only => [:new, :edit, :create, :destroy]

  # GET /terms
  # GET /terms.json
  def index
    @terms = Term.search(params[:search])
  end

  # GET /terms/1
  # GET /terms/1.json
  def show
  end

  # GET /terms/new
  def new
    @term = Term.new
  end

  # GET /terms/1/edit
  def edit
    @hide_edit_button = true
  end

  # POST /terms
  # POST /terms.json
  def create
    @term = Term.new(term_params)

    respond_to do |format|
      if @term.save
        format.html { redirect_to @term, notice: 'Term was successfully created.' }
        format.json { render :show, status: :created, location: @term }
      else
        format.html { render :new }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /terms/1
  # PATCH/PUT /terms/1.json
  def update
    respond_to do |format|
      if @term.update(term_params)
        format.html { redirect_to @term, notice: 'Term was successfully updated.' }
        format.json { render :show, status: :ok, location: @term }
      else
        format.html { render :edit }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /terms/1
  # DELETE /terms/1.json
  def destroy
    @term.destroy
    respond_to do |format|
      format.html { redirect_to terms_url, notice: 'Term was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_term
      @term = Term.find(params[:id])
    end

# Never trust parameters from the scary internet, only allow the white list through.
def term_params
  params.require(:term).permit(:name, :category, :definition)
end

def verify_is_admin
      (current_admin.nil?) ? redirect_to(root_path) :
(redirect_to(root_path) unless current_admin.admin?)
    end
end
</code>```

application_policy.rb

```<code>class ApplicationPolicy
  attr_reader :admin, :record

  def initialize(admin, record)
    @admin = admin
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(admin, record.class)
  end

  class Scope
    attr_reader :admin, :scope

    def initialize(admin, scope)
      @admin = admin
      @scope = scope
    end

    def resolve
      scope
    end
  end
end
</code>```

terms_policy.rb

```<code>class TermPolicy < ApplicationPolicy
  def index?
    true
  end

  def create?
    user.present?
  end

  def update?
    return true if user.present?
  end

  def edit?
    user.admin?
  end

  def destroy?
    user.admin?
  end
end
</code>```

I've tried implementing suggestions from Access to current_user from within a model in Ruby on Rails, undefined local variable or method `current_user' using devise & rails 3.2, https://code.tutsplus.com/tutorials/authorization-with-pundit--cms-28202, and a smattering of other sources. I'm sure these are all great resources, but at this stage I need something a little more targeted to my project and level of familiarity with Rails.

Let me know what else I can provide. Thanks for your help!

答:
Pundit looks to current_user in your controller to get the user record. You can configure this with the pundit_user method. Override it in  application_controller.rb to return your Admin record.

```<code>def pundit_user
  Admin.find_however_you're_doing_that
end
</code>```

For what it's worth, you're likely going about this a painful way if you intend to add additional roles (non-admin users). You likely want a single Devise model with roles defined as an attribute.

Body:
I'm brand new to rails, and am creating a simple glossary app using Rails 5 with gems Devise and Pundit. I generated an Admin model with Devise; that's the only role that needs to be logged in. I installed Pundit to create policies that would allow me to hide the "Edit," "Destroy," and "New" buttons unless logged in as admin.
Glossary App Index

After adding the below policy code to my index.html.erb file to hide the 'Edit' and 'Destroy' buttons, I'm getting an "Undefined method 'current_user'" error.

      <% @terms.each do |term| %>

          <%= term.name %>
          <%= term.category %>
          <%= term.definition %>
          <%= link_to 'Show', term, class: 'btn btn-mini' %>

            <% if policy(@term).edit? %>
              <%= link_to 'Edit', edit_term_path(term), class: 'btn btn-mini' %>
            <% end %>

            <% if policy(@term).destroy? %>
              <%= link_to 'Destroy', term, method: :delete, class: 'btn btn-mini', data: { confirm: 'Are you sure?' } %>
            <% end %>

      <% end %>

Since I didn't generate a "User" model with Devise, but generated an "Admin" model instead, it seemed logical that the error was referring to the word "user" in my new policies. So I replaced "user" with "admin" in my application_policy.rb and terms_policy.rb. Clearly I don't understand what "user" means in this error, as I'm still getting it.

I don't know what exactly you need to see, so here are my models, controllers, and policies:

application_record.rb

class ApplicationRecord < ActiveRecord::Base
  self.abstract_class = true
end

admin.rb

class Admin < ApplicationRecord
  has_many :terms
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :trackable, :timeoutable, :lockable
end

term.rb

class Term < ApplicationRecord
  belongs_to :admin

  def self.search(search)
    if search
      where(["name LIKE ?","%#{search}%"])
    else
      all
    end
  end

end

application_controller.rb

class ApplicationController < ActionController::Base
  include Pundit
  protect_from_forgery with: :exception
  before_action :set_current_user

  def set_current_user
    Term.current_user = current_user
  end
end

terms_controller.rb

class TermsController < ApplicationController
  before_action :set_term, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_admin!, :only => [:new, :edit, :create, :destroy]

  # GET /terms
  # GET /terms.json
  def index
    @terms = Term.search(params[:search])
  end

  # GET /terms/1
  # GET /terms/1.json
  def show
  end

  # GET /terms/new
  def new
    @term = Term.new
  end

  # GET /terms/1/edit
  def edit
    @hide_edit_button = true
  end

  # POST /terms
  # POST /terms.json
  def create
    @term = Term.new(term_params)

    respond_to do |format|
      if @term.save
        format.html { redirect_to @term, notice: 'Term was successfully created.' }
        format.json { render :show, status: :created, location: @term }
      else
        format.html { render :new }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /terms/1
  # PATCH/PUT /terms/1.json
  def update
    respond_to do |format|
      if @term.update(term_params)
        format.html { redirect_to @term, notice: 'Term was successfully updated.' }
        format.json { render :show, status: :ok, location: @term }
      else
        format.html { render :edit }
        format.json { render json: @term.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /terms/1
  # DELETE /terms/1.json
  def destroy
    @term.destroy
    respond_to do |format|
      format.html { redirect_to terms_url, notice: 'Term was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_term
      @term = Term.find(params[:id])
    end

# Never trust parameters from the scary internet, only allow the white list through.
def term_params
  params.require(:term).permit(:name, :category, :definition)
end

def verify_is_admin
      (current_admin.nil?) ? redirect_to(root_path) :
(redirect_to(root_path) unless current_admin.admin?)
    end
end

application_policy.rb

class ApplicationPolicy
  attr_reader :admin, :record

  def initialize(admin, record)
    @admin = admin
    @record = record
  end

  def index?
    false
  end

  def show?
    scope.where(:id => record.id).exists?
  end

  def create?
    false
  end

  def new?
    create?
  end

  def update?
    false
  end

  def edit?
    update?
  end

  def destroy?
    false
  end

  def scope
    Pundit.policy_scope!(admin, record.class)
  end

  class Scope
    attr_reader :admin, :scope

    def initialize(admin, scope)
      @admin = admin
      @scope = scope
    end

    def resolve
      scope
    end
  end
end

terms_policy.rb

class TermPolicy < ApplicationPolicy
  def index?
    true
  end

  def create?
    user.present?
  end

  def update?
    return true if user.present?
  end

  def edit?
    user.admin?
  end

  def destroy?
    user.admin?
  end
end

I've tried implementing suggestions from Access to current_user from within a model in Ruby on Rails, undefined local variable or method `current_user' using devise & rails 3.2, https://code.tutsplus.com/tutorials/authorization-with-pundit--cms-28202, and a smattering of other sources. I'm sure these are all great resources, but at this stage I need something a little more targeted to my project and level of familiarity with Rails.

Let me know what else I can provide. Thanks for your help!

Body:
Pundit looks to current_user in your controller to get the user record. You can configure this with the pundit_user method. Override it in  application_controller.rb to return your Admin record.

def pundit_user
  Admin.find_however_you're_doing_that
end

For what it's worth, you're likely going about this a painful way if you intend to add additional roles (non-admin users). You likely want a single Devise model with roles defined as an attribute.


问:
EXSLT template date:format-date works incorrectly after template date:add
The following code

```<code><td>
    <xsl:call-template name="date:add">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "duration"   select = "'PT1H'" />
    </xsl:call-template>
  </td>
  <td>
    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>
  </td>
</code>```

outputs something like

```<code><td>2011-01-18T07:27:24-00:00</td><td>18,  2011</td>
</code>```

The second cell doesn't contain name of month (MMM in pattern)

At the same time code below works fine

```<code> <td>
    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>
  </td>
</code>```

i.e. without date:add call before I get right date in output:

```<code><td>18, Jan 2011</td>
</code>```

Is it defect in EXSLT? Or I do something wrong?

I use EXSLT extensions to XSLT and all necessary templates are imported.

Here are full text of test files:
XSLT:

```<code> <?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:date="http://exslt.org/dates-and-times"
    xmlns:hml="http://schemas.test/hml"
    extension-element-prefixes="date"
    exclude-result-prefixes = "hml"
    >

<xsl:import href="date.add.template.xsl" />
<xsl:import href="date.format-date.template.xsl" />
<xsl:import href="str.padding.template.xsl" />

<xsl:output omit-xml-declaration="yes" />
<xsl:output method="html" indent="no" />

 <xsl:template match="/">
    <td>
    <xsl:call-template name="date:add">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "duration"   select = "'PT1H'" />
    </xsl:call-template>
  </td>
  <td>
    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>
  </td>
  </xsl:template>
</xsl:stylesheet>
</code>```

and XML:

```<code><hml:LT xmlns:hml="http://schemas.test/hml">2011-01-19T02:16:06-00:00</hml:LT>
</code>```

答:
I tested your samples with Saxon 6.5.5 and xsltproc on Windows and the output both times is as follows:

```<code><td>2011-01-19T03:16:06-00:00</td><td>19, Jan 2011</td>
</code>```

So I don't think there is a problem with the templates for the EXSLT functions I took from http://www.exslt.org/, it looks more like a Xalan bug if you don't get the correct output with some version of Xalan.

Body:
The following code

    <xsl:call-template name="date:add">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "duration"   select = "'PT1H'" />
    </xsl:call-template>

    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>

outputs something like

2011-01-18T07:27:24-00:00	18,  2011

The second cell doesn't contain name of month (MMM in pattern)

At the same time code below works fine

    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>

i.e. without date:add call before I get right date in output:

18, Jan 2011

Is it defect in EXSLT? Or I do something wrong?

I use EXSLT extensions to XSLT and all necessary templates are imported.

Here are full text of test files:
XSLT:

 <?xml version="1.0"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:date="http://exslt.org/dates-and-times"
    xmlns:hml="http://schemas.test/hml"
    extension-element-prefixes="date"
    exclude-result-prefixes = "hml"
    >

<xsl:import href="date.add.template.xsl" />
<xsl:import href="date.format-date.template.xsl" />
<xsl:import href="str.padding.template.xsl" />

<xsl:output omit-xml-declaration="yes" />
<xsl:output method="html" indent="no" />

 <xsl:template match="/">

    <xsl:call-template name="date:add">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "duration"   select = "'PT1H'" />
    </xsl:call-template>

    <xsl:call-template name="date:format-date">
      <xsl:with-param name = "date-time"  select ="hml:LT" />
      <xsl:with-param name = "pattern"   select = "'dd, MMM yyyy'" />
    </xsl:call-template>

  </xsl:template>
</xsl:stylesheet>

and XML:

<hml:LT xmlns:hml="http://schemas.test/hml">2011-01-19T02:16:06-00:00</hml:LT>

Body:
I tested your samples with Saxon 6.5.5 and xsltproc on Windows and the output both times is as follows:

<td>2011-01-19T03:16:06-00:00</td><td>19, Jan 2011</td>

So I don't think there is a problem with the templates for the EXSLT functions I took from http://www.exslt.org/, it looks more like a Xalan bug if you don't get the correct output with some version of Xalan.