问:
Trying to change the position of characters of two different numbers
I was trying to do an exercise which is "Type 2 numbers and each character in a pair position swap it with the equivalent of the character in the same position of the second number, and the characters in an impair position swap them with the character in the same position of the first number"

But I haven't worked with characters before so I'm not sure what I'm doing wrong, this is the code i have so far, it throws random stuff out instead of the numbers changed.
I have this code so far:

```<code>public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] n1, n2;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();

            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }
            n1 = chars1;
            n2 = chars2;
            txvRes.setText("the first number is: "+n1+" and the second number is: "+n2);
        }
    };}
</code>```

答:
I'm not sure what you're trying to do here.

Type 2 numbers and each character in a odd position swap it with the
  equivalent character in the same position of the second number, and
  the characters in an odd position swap them with the character in the
  same position of the first number

If you're gonna overwrite odd positions and even positions, your end numbers will be the same ?

In the case that you swap they will be the same numbers but reversed. Would you post an input and output cases of what you want to achieve ?

In any case, you don't need to create an if for length.

```<code>        int minLength = Math.min(chars1.length, chars2.length);
        for(int i = 0; i < minLength; i++){
            if(i % 2 == 0){
            } else {
            }
        }
</code>```

Plus num modulus 2 has only 2 outcomes, 1 or 0, so you don't need another if in that condition.
Also in your current code it's not executing if the length is the same. That may cover some edge cases.

Body:
I was trying to do an exercise which is "Type 2 numbers and each character in a pair position swap it with the equivalent of the character in the same position of the second number, and the characters in an impair position swap them with the character in the same position of the first number"

But I haven't worked with characters before so I'm not sure what I'm doing wrong, this is the code i have so far, it throws random stuff out instead of the numbers changed.
I have this code so far:

public class MainActivity extends AppCompatActivity {
    EditText edtNum1, edtNum2;
    TextView txvRes;
    Button btnEjecutar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnEjecutar = (Button) findViewById(R.id.btnEjecutar);
        btnEjecutar.setOnClickListener(ButtonClickListener);
    }

    public View.OnClickListener ButtonClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            txvRes = (TextView) findViewById(R.id.txvRes);
            int a, b;
            char[] n1, n2;
            edtNum1 = (EditText) findViewById(R.id.edtNum1);
            edtNum2 = (EditText) findViewById(R.id.edtNum2);
            a = Integer.parseInt(edtNum1.getText().toString());
            b = Integer.parseInt(edtNum2.getText().toString());
            char [] chars1 = String.valueOf(a).toCharArray();
            char [] chars2 = String.valueOf(b).toCharArray();

            if(chars1.length > chars2.length){
                for(int i = 0;i < chars2.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }else if(chars1.length < chars2.length){
                for(int i = 0;i < chars1.length;i++){
                    if(i % 2 != 0){
                        chars2[i] = chars1[i];
                    }else if(i % 2 == 0){
                        chars1[i] = chars2[i];
                    }
                }
            }
            n1 = chars1;
            n2 = chars2;
            txvRes.setText("the first number is: "+n1+" and the second number is: "+n2);
        }
    };}

Body:
I'm not sure what you're trying to do here.

Type 2 numbers and each character in a odd position swap it with the
  equivalent character in the same position of the second number, and
  the characters in an odd position swap them with the character in the
  same position of the first number

If you're gonna overwrite odd positions and even positions, your end numbers will be the same ?

In the case that you swap they will be the same numbers but reversed. Would you post an input and output cases of what you want to achieve ?

In any case, you don't need to create an if for length.

        int minLength = Math.min(chars1.length, chars2.length);
        for(int i = 0; i < minLength; i++){
            if(i % 2 == 0){
            } else {
            }
        }

Plus num modulus 2 has only 2 outcomes, 1 or 0, so you don't need another if in that condition.
Also in your current code it's not executing if the length is the same. That may cover some edge cases.


来源: stackexchange

问:
Facebook Analytics shows two different event source groups
Facebook Analytics is showing two different event source groups. One for my page activity and one for the pixel activity. How can I merge them?</p>

答:
Since event source group are entities that combine event sources (Page, Pixel, etc), one cannot combine event source groups. Instead, you can create a new event source group that contains the event sources in the event source groups that you want to combine.

Event Source Groups can be created from Facebook Analytics or Business Manager and can be used to combine Apps, Pixels, Pages and Offline Event Sets. You can view analytics on these event source groups in Facebook Analytics.

ContentLicense: CC BY-SA 3.0


问:
How to handle association table and cascade constraints in MYSQL
I think this is a common problem but I was not able to find correct keywords to perform a search on StackOverflow.

In mysql, I have two entites : organization and scale.
One organization can only have one scale but a scale can belong to many organizations.

So I created a third entity organization_scale.

for instance :

```<code>organization
------------
org_id | name
     1 | Mickey
     2 | Donald
     3 | Dingo

scale
----------
 sc_id | name
     1 | miniScale
     2 | maxiScale

organization_scale
--------------
org_id | sc_id
     1 | 1
     2 | 1
     3 | 2
</code>```

Both fields of the organization_scale entity are foreign keys + cascade on update and delete

The problem is the following:

If I delete from organization where org_id = 3,the third line from organization_scale are properly deleted (since org_id = 3 does not exist anymore)

BUT

the scale with sc_id = 2 is not deleted. And I do not understand why. No one references to this scale, and this should be removed otherwise, with a big amount of data, a lot of "scales" will be orphean.

(same thing happens if I do not use an extra table, and I add a scale_id column directly in organization)

答:
I think the problem is this: The ON DELTE CASCADE in the definition of the organization_scale table only works in one direction: when deleting something in scale or organization then don't ask and delete the rows in organization_scale.

But you seem to want the other direction: When deleting something in organization_scale delete the row in scale if there is no reference to it anymore.

This works for me: I added a trigger on organization.

```<code>DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;

CREATE TABLE organization (org_id INT UNSIGNED PRIMARY KEY, name VARCHAR(255));
CREATE TABLE scale (sc_id INT UNSIGNED PRIMARY KEY, name VARCHAR(255));
CREATE TABLE organization_scale (org_id INT UNSIGNED, sc_id INT UNSIGNED,
    FOREIGN KEY (org_id)
        REFERENCES organization(org_id)
        ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (sc_id)
        REFERENCES scale(sc_id)
        ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TRIGGER delete_unused_sc_id AFTER DELETE ON organization FOR EACH ROW DELETE FROM scale WHERE NOT EXISTS (SELECT * FROM organization_scale WHERE organization_scale.sc_id = scale.sc_id);

INSERT INTO organization VALUES
(1,"Mickey"),
(2,"Donald"),
(3,"Dingo");

INSERT INTO scale VALUES
(1,"miniScale"),
(2,"maxiScale");

INSERT INTO organization_scale VALUES
(1,1),
(2,1),
(3,2);

SELECT * FROM organization_scale;
SELECT * FROM scale;

DELETE FROM organization WHERE org_id=3;

SELECT * FROM organization_scale;
SELECT * FROM scale;

DROP DATABASE test;
</code>```

Body:
I think this is a common problem but I was not able to find correct keywords to perform a search on StackOverflow.

In mysql, I have two entites : organization and scale.
One organization can only have one scale but a scale can belong to many organizations.

So I created a third entity organization_scale.

for instance :

organization
------------
org_id | name
     1 | Mickey
     2 | Donald
     3 | Dingo

scale
----------
 sc_id | name
     1 | miniScale
     2 | maxiScale

organization_scale
--------------
org_id | sc_id
     1 | 1
     2 | 1
     3 | 2

Both fields of the organization_scale entity are foreign keys + cascade on update and delete

The problem is the following:

If I delete from organization where org_id = 3,the third line from organization_scale are properly deleted (since org_id = 3 does not exist anymore)

BUT

the scale with sc_id = 2 is not deleted. And I do not understand why. No one references to this scale, and this should be removed otherwise, with a big amount of data, a lot of "scales" will be orphean.

(same thing happens if I do not use an extra table, and I add a scale_id column directly in organization)

Body:
I think the problem is this: The ON DELTE CASCADE in the definition of the organization_scale table only works in one direction: when deleting something in scale or organization then don't ask and delete the rows in organization_scale.

But you seem to want the other direction: When deleting something in organization_scale delete the row in scale if there is no reference to it anymore.

This works for me: I added a trigger on organization.

DROP DATABASE IF EXISTS test;
CREATE DATABASE test;
USE test;

CREATE TABLE organization (org_id INT UNSIGNED PRIMARY KEY, name VARCHAR(255));
CREATE TABLE scale (sc_id INT UNSIGNED PRIMARY KEY, name VARCHAR(255));
CREATE TABLE organization_scale (org_id INT UNSIGNED, sc_id INT UNSIGNED,
    FOREIGN KEY (org_id)
        REFERENCES organization(org_id)
        ON UPDATE CASCADE ON DELETE CASCADE,
    FOREIGN KEY (sc_id)
        REFERENCES scale(sc_id)
        ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE TRIGGER delete_unused_sc_id AFTER DELETE ON organization FOR EACH ROW DELETE FROM scale WHERE NOT EXISTS (SELECT * FROM organization_scale WHERE organization_scale.sc_id = scale.sc_id);

INSERT INTO organization VALUES
(1,"Mickey"),
(2,"Donald"),
(3,"Dingo");

INSERT INTO scale VALUES
(1,"miniScale"),
(2,"maxiScale");

INSERT INTO organization_scale VALUES
(1,1),
(2,1),
(3,2);

SELECT * FROM organization_scale;
SELECT * FROM scale;

DELETE FROM organization WHERE org_id=3;

SELECT * FROM organization_scale;
SELECT * FROM scale;

DROP DATABASE test;


问:
Add required parameter values for perform GET and POST request in PHP
I'm trying to figure out how to make more useful and complex my actual Slim php app (yes, I'm trying to perform something like a very simple APIrest service) in which I have performed some different kinds of request, some as GET request and some as POST request:

GET request for retrieve all the books object

```<code>$app->get('/api/books', function () {
require_once('db/connector_test.php');

    $statement = $pdo->prepare("SELECT * FROM books ORDER BY id");
    $statement->execute();
    $data = $statement->fetchAll(PDO::FETCH_OBJ);

    if (isset($data)) {
       echo "```";
       header('Content-Type: application/json');
       print json_encode($data);
       echo "```";
       }
});
</code>```

In this case I have already done another GET request for retrieve a specific book object data following the specific '/api/books/{id}'url in the GET request and this is the result very simple result:

POST request for insert new records

```<code>$app->post('/api/books', function ($request) {
    require_once('db/connector_test.php');

    $statement = $pdo->prepare("INSERT INTO `books` (`title`, `author`, `amazon_url`) VALUES (:stitle,:sauthor,:samazon_url)");
    //$statement->bindParam(':title',':author',':amazon_url', $title, $author, $amazon_url);

    $statement->execute(array(
    "stitle" => $request->getParsedBody()['title'],
    "sauthor" => $request->getParsedBody()['author'],
    "samazon_url" => $request->getParsedBody()['amazon_url']
    ));
</code>```

In this case I have just test it with Postman client by adding as Body Parameter the three parameters (title, author, amazon_url) with the values that I want to add in the database performing the POST request.

What I need to do now? (and this the point of this question)

I have thought about something that can make these HTTP requests more secure, maybe by adding some required parameters in each of these request in order to add a better control to the use of these resources...like an authkey or some specific parameters that are mandatory. So the common user that wants to make a GET and a POST request to those resources needs to know which kind of parameter values are needed.

Someone can suggest me how to include this logic both in Slim and in PHP in general? Since I think that if I understand this concept in PHP I can easily understand it also for Slim framework.

答:
So you want to make some sort of authentication over your API
this can be done using middleware in slim  Middleware in Slim

Where you can build an access gate around your whole  API or a specific route only
In this middeleware you can check for Token like JWT token using this
Slim-JWT

And also you can check for some paramters Values form the user

Edit to Adding example

First  you need to create a route to generate JWT Token like

```<code>$app->get('/JWTToken',function($req,$res){
$MyJWT=$this->JWT;
    $now = new DateTime();
    $future = new DateTime("now +10 minutes");
   // $server = $request->getServerParams();
    $payload = [
        "iat" => $now->getTimeStamp(),
        "exp" => $future->getTimeStamp(),
        "sub" =>"test for JWT",
    ];
    $secret = "supersecretkeyyoushouldnotcommittogithub";
    $token = $MyJWT->encode($payload, $secret, "HS512");
    $data["status"] = "ok";
    $data["token"] = $token;
    return $res->withStatus(201)
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
</code>```

This route will generate a JWT token valid for 10 minutes only

Second Adding middleware to check Token validation

```<code>$app->add(new \Slim\Middleware\JwtAuthentication([
     "path" => ["/"],
    "passthrough" => ["/JWTToken"],
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "error" => function ($request, $response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));
</code>```

This middleware will check for token if its a valid or not
If true will call your GET or POST route if not will Send unauthorized Error back

You need to update your Composer with theses requirements

```<code>"firebase/php-jwt": "^4.0",
"tuupola/slim-jwt-auth": "^2.3"
</code>```

Edit#2
To send any request you need to send this header

```<code>Authorization: Bearer  "Token String"
</code>```

Example from postman

Body:
I'm trying to figure out how to make more useful and complex my actual Slim php app (yes, I'm trying to perform something like a very simple APIrest service) in which I have performed some different kinds of request, some as GET request and some as POST request:

GET request for retrieve all the books object

$app->get('/api/books', function () {
require_once('db/connector_test.php');

    $statement = $pdo->prepare("SELECT * FROM books ORDER BY id");
    $statement->execute();
    $data = $statement->fetchAll(PDO::FETCH_OBJ);

    if (isset($data)) {
       echo "
";
       header('Content-Type: application/json');
       print json_encode($data);
       echo "
";
       }
});

In this case I have already done another GET request for retrieve a specific book object data following the specific '/api/books/{id}'url in the GET request and this is the result very simple result:

POST request for insert new records

$app->post('/api/books', function ($request) {
    require_once('db/connector_test.php');

    $statement = $pdo->prepare("INSERT INTO `books` (`title`, `author`, `amazon_url`) VALUES (:stitle,:sauthor,:samazon_url)");
    //$statement->bindParam(':title',':author',':amazon_url', $title, $author, $amazon_url);

    $statement->execute(array(
    "stitle" => $request->getParsedBody()['title'],
    "sauthor" => $request->getParsedBody()['author'],
    "samazon_url" => $request->getParsedBody()['amazon_url']
    ));

In this case I have just test it with Postman client by adding as Body Parameter the three parameters (title, author, amazon_url) with the values that I want to add in the database performing the POST request.

What I need to do now? (and this the point of this question)

I have thought about something that can make these HTTP requests more secure, maybe by adding some required parameters in each of these request in order to add a better control to the use of these resources...like an authkey or some specific parameters that are mandatory. So the common user that wants to make a GET and a POST request to those resources needs to know which kind of parameter values are needed.

Someone can suggest me how to include this logic both in Slim and in PHP in general? Since I think that if I understand this concept in PHP I can easily understand it also for Slim framework.

Body:
So you want to make some sort of authentication over your API
this can be done using middleware in slim  Middleware in Slim

Where you can build an access gate around your whole  API or a specific route only
In this middeleware you can check for Token like JWT token using this
Slim-JWT

And also you can check for some paramters Values form the user

Edit to Adding example

First  you need to create a route to generate JWT Token like

$app->get('/JWTToken',function($req,$res){
$MyJWT=$this->JWT;
    $now = new DateTime();
    $future = new DateTime("now +10 minutes");
   // $server = $request->getServerParams();
    $payload = [
        "iat" => $now->getTimeStamp(),
        "exp" => $future->getTimeStamp(),
        "sub" =>"test for JWT",
    ];
    $secret = "supersecretkeyyoushouldnotcommittogithub";
    $token = $MyJWT->encode($payload, $secret, "HS512");
    $data["status"] = "ok";
    $data["token"] = $token;
    return $res->withStatus(201)
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});

This route will generate a JWT token valid for 10 minutes only

Second Adding middleware to check Token validation

$app->add(new \Slim\Middleware\JwtAuthentication([
     "path" => ["/"],
    "passthrough" => ["/JWTToken"],
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "error" => function ($request, $response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

This middleware will check for token if its a valid or not
If true will call your GET or POST route if not will Send unauthorized Error back

You need to update your Composer with theses requirements

"firebase/php-jwt": "^4.0",
"tuupola/slim-jwt-auth": "^2.3"

Edit#2
To send any request you need to send this header

Authorization: Bearer  "Token String"

Example from postman


问:
storing the contents in a array and displaying
I have written code to generate a prime number within a range. And then trying to store the generated prime number in an array:

```<code> if(prime)
   printf("\n%d", n);
 prime_array[k]=n;
 k++;
</code>```

Then trying to print the contents of array:

```<code>for(z=0;z<6;z++)
  printf("%d\n",prime_array[z]);
</code>```

The output that I get is incorrect. What is wrong?

答:
in the code you've posted, you are trying to cast an integer (n) in something that seems to be a char (prime_array[k]), it can't work because 'n' and 'prime_array[k]' dont have the same type and also because you can't cast an integer in an array like that.

If you want to put an integer in an array, you can use the function sprintf from stdio.h.
Man of this function : http://man.cx/sprintf%283%29

Anhuin.

ContentLicense: CC BY-SA 2.5

Body:
I have written code to generate a prime number within a range. And then trying to store the generated prime number in an array:

 if(prime)
   printf("\n%d", n);
 prime_array[k]=n;
 k++;

Then trying to print the contents of array:

for(z=0;z<6;z++)
  printf("%d\n",prime_array[z]);

The output that I get is incorrect. What is wrong?


问:
Object relationships in Ember without using Ember-Data
We don't use Ember-Data in our project. We got a scenario where each model has an id of another type model. In fact we don't have models as well. We are using plain Ajax.

Let's take 2 models Test and Application. A test will contain the application id to which that test is created for. When I retrieve a Test, I also want the application data. Ember-Data does this by default when we use relationships. How can I achieve this without Ember-Data. There might 2 tests for same application. Once the application data is retrieved, I don't want to make a request again for the same application data.

答:
My answer - create your own in-memory store (Service looks like Ember-way solution) for storing already loaded records. For example it could have structure like this:

```<code>// app/services/store.js

export default Ember.Service.extend({
    ajax: Ember.inject.service(),

    store: {
        applications: [],
        tests: []
    },

    getTest(id) {
        const store = this.get('store');

        return new Ember.RSVP.Promise(resolve => {
            const loadedTest = store.tests.findBy('id', id);
            if (loadedTest) {
                return resolve(loadedTest);
            }

            this.get('ajax').getRequest(urlForGettingTestWithConcreteId).then(test => {
                if (test.application) {
                    const application = store.applications.findBy('id', test.application);

                    if (application) {
                        test.application = application;

                        store.tests.pushObject(test);

                        return resolve(test);
                    }

                    this.get('ajax').getRequest(test.application).then(application => {
                        test.application = application;

                        store.applications.pushObject(application);
                        store.tests.pushObject(test);

                        resolve(test);
                    });
                }
            });
        });
    }
});
</code>```

It's mixed pseudo-code and code that should work, but you should easily get it working with your application. :)

Body:
My answer - create your own in-memory store (Service looks like Ember-way solution) for storing already loaded records. For example it could have structure like this:

// app/services/store.js

export default Ember.Service.extend({
    ajax: Ember.inject.service(),

    store: {
        applications: [],
        tests: []
    },

    getTest(id) {
        const store = this.get('store');

        return new Ember.RSVP.Promise(resolve => {
            const loadedTest = store.tests.findBy('id', id);
            if (loadedTest) {
                return resolve(loadedTest);
            }

            this.get('ajax').getRequest(urlForGettingTestWithConcreteId).then(test => {
                if (test.application) {
                    const application = store.applications.findBy('id', test.application);

                    if (application) {
                        test.application = application;

                        store.tests.pushObject(test);

                        return resolve(test);
                    }

                    this.get('ajax').getRequest(test.application).then(application => {
                        test.application = application;

                        store.applications.pushObject(application);
                        store.tests.pushObject(test);

                        resolve(test);
                    });
                }
            });
        });
    }
});

It's mixed pseudo-code and code that should work, but you should easily get it working with your application. :)


问:
CSS for long (scrolling) dropdown menu
I'm trying to create a nested dropdown menu that may potentially be very long and overflow off the page.

What I'd like to do is, when the menu is too long it will display a scroll bar.  I'm doing this with overflow: auto.  However, when I do this, it traps any submenus within the same 'scroll space' as defined by the first scroll bar.

I've also tried various iterations of overflow: none with the :not(:hover) selector, but nothing I've tried seems to work.

What I'd like it to do is show the scrollbar on each level, only if necessary (i.e. that submenu would scroll off the page).  Each submenu should 'pop' out of the previous scroll bar, if any, as if it was not there.

I'd like to do this in all CSS, but I'm open to a JS solution as well.

I have a code pen showing the issue here:
https://codepen.io/mcmurphy510/pen/ZyGLKd

答:
I'm not sure if I'm understanding your question correctly, but try isolating your desired element by using ID or CLASS. See the third level menu.

#primary_nav_wrap {
  margin-top: 15px
}

#primary_nav_wrap ul {
  list-style: none;
  position: relative;
  float: left;
  margin: 0;
  padding: 0;
}

#primary_nav_wrap ul a {
  display: block;
  color: #333;
  text-decoration: none;
  font-weight: 700;
  font-size: 12px;
  line-height: 32px;
  padding: 0 15px;
  font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}

#primary_nav_wrap ul li {
  position: relative;
  float: left;
  margin: 0;
  padding: 0;
}

#primary_nav_wrap ul li.current-menu-item {
  background: #ddd
}

#primary_nav_wrap ul li:hover {
  background: #f6f6f6
}

#primary_nav_wrap ul ul {
  display: none;
  position: absolute;
  top: 100%;
  left: 0;
  background: #fff;
  padding: 0;
}

#primary_nav_wrap ul ul li {
  float: none;
  width: 200px
}

#primary_nav_wrap ul ul a {
  line-height: 120%;
  padding: 10px 15px
}

#primary_nav_wrap ul ul ul {
  top: 0;
  left: 100%
}

#primary_nav_wrap ul li:hover > ul {
  display: block;
  height: 200px;
}

#primary_nav_wrap ul li ul li:not(:hover) {
}

/* ul li ul li ul li {
  overflow: auto;
} */

#subdeep {
  overflow: auto;
  height: 50px !important;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>Simple Pure CSS Drop Down Menu</h1>
<nav id="primary_nav_wrap">
<ul>
  <li>Menu 1
    <ul>
      <li>Sub Menu 1</li>
      <li>Sub Menu 2</li>
      <li>Sub Menu 3</li>
      <li>Sub Menu 4
        <ul>
          <li>Deep Menu 1
            <ul id="subdeep">
              <li>Sub Deep 1</li>
              <li>Sub Deep 2</li>
              <li>Sub Deep 3</li>
                <li>Sub Deep 4</li>
            </ul>
          </li>
          <li>Deep Menu 2</li>
        </ul>
      </li>
      <li>Sub Menu 5</li>
    </ul>
  </li>
</ul>
</nav></code>```

Title: CSS for long (scrolling) dropdown menu

Body:
I'm not sure if I'm understanding your question correctly, but try isolating your desired element by using ID or CLASS. See the third level menu.

#primary_nav_wrap {
  margin-top: 15px
}

#primary_nav_wrap ul {
  list-style: none;
  position: relative;
  float: left;
  margin: 0;
  padding: 0;
}

#primary_nav_wrap ul a {
  display: block;
  color: #333;
  text-decoration: none;
  font-weight: 700;
  font-size: 12px;
  line-height: 32px;
  padding: 0 15px;
  font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif
}

#primary_nav_wrap ul li {
  position: relative;
  float: left;
  margin: 0;
  padding: 0;
}

#primary_nav_wrap ul li.current-menu-item {
  background: #ddd
}

#primary_nav_wrap ul li:hover {
  background: #f6f6f6
}

#primary_nav_wrap ul ul {
  display: none;
  position: absolute;
  top: 100%;
  left: 0;
  background: #fff;
  padding: 0;
}

#primary_nav_wrap ul ul li {
  float: none;
  width: 200px
}

#primary_nav_wrap ul ul a {
  line-height: 120%;
  padding: 10px 15px
}

#primary_nav_wrap ul ul ul {
  top: 0;
  left: 100%
}

#primary_nav_wrap ul li:hover > ul {
  display: block;
  height: 200px;
}

#primary_nav_wrap ul li ul li:not(:hover) {
}

/* ul li ul li ul li {
  overflow: auto;
} */

#subdeep {
  overflow: auto;
  height: 50px !important;
}

<h1>Simple Pure CSS Drop Down Menu</h1>
<nav id="primary_nav_wrap">
<ul>
  <li><a href="#">Menu 1</a>
    <ul>
      <li><a href="#">Sub Menu 1</a></li>
      <li><a href="#">Sub Menu 2</a></li>
      <li><a href="#">Sub Menu 3</a></li>
      <li><a href="#">Sub Menu 4</a>
        <ul>
          <li><a href="#">Deep Menu 1</a>
            <ul id="subdeep">
              <li><a href="#">Sub Deep 1</a></li>
              <li><a href="#">Sub Deep 2</a></li>
              <li><a href="#">Sub Deep 3</a></li>
                <li><a href="#">Sub Deep 4</a></li>
            </ul>
          </li>
          <li><a href="#">Deep Menu 2</a></li>
        </ul>
      </li>
      <li><a href="#">Sub Menu 5</a></li>
    </ul>
  </li>
</ul>
</nav>


问:
Spring cloud registering multiple instances of same service
I am developing a microservice, using Spring Boot, that exposes REST Endpoint. Because of scalability, I have to run multiple instances of this services on a different port. What will be the configurations for the applications so that it can register with eureka and requests are load balanced? I am using Spring cloud config, Eureka server and zuul.</p>

答:
Attaching following entries in the client properties file will do the trick.  This is for Spring cloud config dalston </p>

```<code>eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}
</code>```

Body:
Attaching following entries in the client properties file will do the trick.  This is for Spring cloud config dalston

eureka.instance.instanceId=${spring.application.name}:${spring.application.instance_id:${random.value}}


问:
Installing Groovy
Recently I downloaded Groovy-2.3.6 and try to install it on Linux system. I follow the instruction from http://groovy-lang.org/install.html. I set my GROOVY_HOME variable.

```<code>export GROOVY_HOME=/home/work/Software/groovy-2.3.6
</code>```

Then I set my environment path variable to the Groovy bin folder

```<code>  export PATH=$PATH:/home/work/Software/groovy-2.3.6/bin
</code>```

The JAVA_HOME variable is already created.

Now when I'm trying to run any command of Groovy, It generate following error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/groo/tool/GroovyStarter
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.tools.GroovyStarter
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: org.codehaus.groovy.tools.GroovyStarter.  Program will exit.
</code>```

I was going through some website to solve that problem. I find that if I set wrong path to GROOVY_HOME then it can happen. I can't figure out what should be the right path for that variable. Can anyone help me with this please.
 Thanks

答:
I had the same error message and found out after much trial and error, the GROOVY_HOME variable was not set correctly.

The groovy application relies on the GROOVY_HOME path pointing to the correct directory, or else you will see the error above.

I see an answer above that recommends removing periods from the directory name and adding it to the path. This will work but could be done in a cleaner way using a symlink.

Follow the link below or follow my summary:

https://www.packtpub.com/mapt/book/All%20Books/9781849519366/1/ch01lvl1sec11/Installing+Groovy+on+Linux+and+OS+X

Create a symlink named current that points to the main groovy directory (e.g. /usr/share/groovy/groovy-2.1.6). The symlink could be located in the same directory that holds the groovy-x.y.z directory. This approach has the advantages of avoiding invalid characters in PATH and it can be redirected to a new version of groovy after an upgrade. Here is an example that assumes groovy is installed in /usr/share/groovy/ and groovy version 2.1.6.

sudo ln -s /usr/share/groovy/groovy-2.1.6 current

Use the new symlink to define the GROOVY_HOME variable in the login script (e.g. .profile):

export GROOVY_HOME=/usr/share/groovy/current

Add GROOVY_HOME/bin to the PATH variable in the login script:

export PATH=$GROOVY_HOME/bin:$PATH

NOTE: It's best to log out and log in before testing to ensure the initialization script sets the environment variables properly

Test by executing groovy -v

I hope this works well for whomever stumbles upon this link.

Title: Installing Groovy

Body:
Recently I downloaded Groovy-2.3.6 and try to install it on Linux system. I follow the instruction from http://groovy-lang.org/install.html. I set my GROOVY_HOME variable.

export GROOVY_HOME=/home/work/Software/groovy-2.3.6

Then I set my environment path variable to the Groovy bin folder

  export PATH=$PATH:/home/work/Software/groovy-2.3.6/bin

The JAVA_HOME variable is already created.

Now when I'm trying to run any command of Groovy, It generate following error

Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/groo/tool/GroovyStarter
Caused by: java.lang.ClassNotFoundException: org.codehaus.groovy.tools.GroovyStarter
      at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
      at java.security.AccessController.doPrivileged(Native Method)
      at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
      at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
      at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Could not find the main class: org.codehaus.groovy.tools.GroovyStarter.  Program will exit.

I was going through some website to solve that problem. I find that if I set wrong path to GROOVY_HOME then it can happen. I can't figure out what should be the right path for that variable. Can anyone help me with this please.
 Thanks


问:
Calculate MD5 Checksum Efficiently
I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.

```<code>MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB

byte [] buffer = new byte [blockSize];
int numRead;
do
{
 numRead = is.read(buffer);
 if (numRead > 0)
 {
  md.update(buffer, 0, numRead);
 }
} while (numRead != -1);

byte[] digest = md.digest();
</code>```

What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)

regards,
Kingsley Reuben J

答:
You could use the Thread.setPriority(int newPriority) method to reduce the thread's priority. This will result in other higher-priority threads being executed more often. However, your MD5 will not be calculated as quickly as if you left the priority alone -- why wouldn't you want this calculation to complete as quickly as possible?

EDIT: Here is a "Fast MD5" implementation, which boasts a significant performance increase (26% faster on average) over Java's default java.security.MessageDigest implementation. See the author's page for detailed information, including code examples and benchmarks. The code is available under the GNU LGPL 2.1 license.

Title: Calculate MD5 Checksum Efficiently

Body:
I'm using following code to get the Checksum of a file. It uses 50% of CPU during calculations.

MessageDigest md = MessageDigest.getInstance("MD5");
InputStream is = new FileInputStream("C:\\Temp\\Small\\Movie.mp4"); // Size 700 MB

byte [] buffer = new byte [blockSize];
int numRead;
do
{
 numRead = is.read(buffer);
 if (numRead > 0)
 {
  md.update(buffer, 0, numRead);
 }
} while (numRead != -1);

byte[] digest = md.digest();

What can be done to reduce the code from using maximum CPU other than Thread.sleep(ms)

regards,
Kingsley Reuben J


问:
Can I use the feature plugin today for my installable app only?
I want to start modularizing my project but haven't worked out the use-cases for my instant app yet. Can I start refactoring my code using com.android.feature plugin for my installable app today and build my instant app later when I'm ready with product features that I want to ship as an instant app.</p>

答:
Feature plugin allows you to slice your app by features and build it as a library or apk. When consumed by com.android.application module, the output is aar and when consumed by an instant app module (com.android.instantapp) , the output is an apk.

You can start slicing your installable app today using feature plugin. All the code that needs to be used only by an installable app can be refactored into a library project. When you are ready to ship your instant app, add an instant app module and include the features that you want.

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

dependencies {
    implementation project(":myFeature")
}
</code>```

Instant App Documentation: Project structure for Instant Apps

Body:
Feature plugin allows you to slice your app by features and build it as a library or apk. When consumed by com.android.application module, the output is aar and when consumed by an instant app module (com.android.instantapp) , the output is an apk.

You can start slicing your installable app today using feature plugin. All the code that needs to be used only by an installable app can be refactored into a library project. When you are ready to ship your instant app, add an instant app module and include the features that you want.

apply plugin: 'com.android.instantapp'

dependencies {
    implementation project(":myFeature")
}

Instant App Documentation: Project structure for Instant Apps


问:
C++ detection idiom without void_t
How I can implement C++ detection idiom without using void_t? In other words, can I implement C++17 std::is_detected etc using only C++03-features?

UPD Detection idiom requires C++11 by definition. In my question I just meant that I want to implement is_detected somehow without void_t. My problem is in it: unused parameters in alias templates were not guaranteed to ensure SFINAE and could be ignored, ans VS 2013 has this defect; another tries (like on cppreference) leads to compiler crash (yep, cl is the greatest compiler in the world).

UPD2 I suppose that VS 2013 can break any C++ metaprogramming techniques (and programmer's brains too).

答:
Since the question was modified and C++ 11 is allowed, I post almost a copy-paste from cppreference, no credit taken.</p>

```<code>namespace detail {
struct nonesuch {
  nonesuch() = delete;
  ~nonesuch() = delete;
  nonesuch(nonesuch const&) = delete;
  void operator=(nonesuch const&) = delete;
};

template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>
struct detector {
  using value_t = std::false_type;
  using type = Default;
};

template <typename... Ts>
struct my_make_void {
  typedef void type;
};

template <typename... Ts>
using my_void_t = typename my_make_void<Ts...>::type;

template <class Default, template <class...> class Op, class... Args>
struct detector<Default, my_void_t<Op<Args...>>, Op, Args...> {
  using value_t = std::true_type;
  using type = Op<Args...>;
};

} // namespace detail

template <template <class...> class Op, class... Args>
using is_detected =
  typename detail::detector<detail::nonesuch, void, Op, Args...>::value_t;

template <class T>
using copy_assign_t = decltype(std::declval<T&>() = std::declval<const T&>());

struct Meow {};
struct Purr {
  void operator=(const Purr&) = delete;
};

int main() {
  cerr << is_detected<copy_assign_t, Meow>::value << endl;
  return 0;
}
</code>```

Title: C++ detection idiom without void_t

Body:
Since the question was modified and C++ 11 is allowed, I post almost a copy-paste from cppreference, no credit taken.

namespace detail {
struct nonesuch {
  nonesuch() = delete;
  ~nonesuch() = delete;
  nonesuch(nonesuch const&) = delete;
  void operator=(nonesuch const&) = delete;
};

template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>
struct detector {
  using value_t = std::false_type;
  using type = Default;
};

template <typename... Ts>
struct my_make_void {
  typedef void type;
};

template <typename... Ts>
using my_void_t = typename my_make_void<Ts...>::type;

template <class Default, template <class...> class Op, class... Args>
struct detector<Default, my_void_t<Op<Args...>>, Op, Args...> {
  using value_t = std::true_type;
  using type = Op<Args...>;
};

} // namespace detail

template <template <class...> class Op, class... Args>
using is_detected =
  typename detail::detector<detail::nonesuch, void, Op, Args...>::value_t;

template <class T>
using copy_assign_t = decltype(std::declval<T&>() = std::declval<const T&>());

struct Meow {};
struct Purr {
  void operator=(const Purr&) = delete;
};

int main() {
  cerr << is_detected<copy_assign_t, Meow>::value << endl;
  return 0;
}


问:
searching a degenerate string in python
I am am trying to search for an exact pattern match to a degenerate or very slightly "fuzzy" string.

```<code>pattern = 'VGSGSGSGSAS' can be 10-50 characters long
string = "VGSGSGGSGSGSGSGSERGSAS" or "VGSGSGSGSGSGAGERSAS"  #it's actually 400 character long string
string[11] = S|A
re.search(pattern, string) #does not work
</code>```

so string[11] is either S or A. In this sample, I'm searching for the pattern in 2 defined strings, But, I don't want to make 2 separate strings, because there are actually multiple (at least 4) position in the 400 character string that have up to 3 different options each for a character. So I would be looking at making and searching in 24 different strings. And that's for just one sequence. Some of my sequences would turn into 64 different strings. Once I find the result of the search, I want to figure out where it starts and ends, and which string[11] character (S or A) it actually matches. Any ideas how I could do this pattern matching? Thank you!

答:
You don't need regex for that, simple str.find() is enough to find it:

```<code>pattern = "KVTMQNL"  # substring to find
your_strings = ["VGSEKVTMQNLNDRLAS", "VGSEKVTMQKLNDRLAS"]  # just a list of strings
for source in your_strings:  # go through each string in our list
    print("String: {}\nEleventh character: {}".format(source, source[11]))
    if source[11] in ("N", "K"):  # check if it has `N` or `K` on its 11th position
        index = source.find(pattern)  # search for the pattern
        if index > -1:  # if the pattern is found anywhere in the string...
            print("Pattern start: {}\nPattern end: {}".format(index, index + len(pattern)))
        else:
            print("No match!")
    print("---")
</code>```

Which will print out:

```<code>String: VGSEKVTMQNLNDRLAS
Eleventh character: N
Pattern start: 4
Pattern end: 11
---
String: VGSEKVTMQKLNDRLAS
Eleventh character: N
No match!
---
</code>```

Not sure if that's exactly what you're looking for, tho, your question is a bit confusing.

Title: searching a degenerate string in python

Body:
I am am trying to search for an exact pattern match to a degenerate or very slightly "fuzzy" string.

pattern = 'VGSGSGSGSAS' can be 10-50 characters long
string = "VGSGSGGSGSGSGSGSERGSAS" or "VGSGSGSGSGSGAGERSAS"  #it's actually 400 character long string
string[11] = S|A
re.search(pattern, string) #does not work

so string[11] is either S or A. In this sample, I'm searching for the pattern in 2 defined strings, But, I don't want to make 2 separate strings, because there are actually multiple (at least 4) position in the 400 character string that have up to 3 different options each for a character. So I would be looking at making and searching in 24 different strings. And that's for just one sequence. Some of my sequences would turn into 64 different strings. Once I find the result of the search, I want to figure out where it starts and ends, and which string[11] character (S or A) it actually matches. Any ideas how I could do this pattern matching? Thank you!

Body:
You don't need regex for that, simple str.find() is enough to find it:

pattern = "KVTMQNL"  # substring to find
your_strings = ["VGSEKVTMQNLNDRLAS", "VGSEKVTMQKLNDRLAS"]  # just a list of strings
for source in your_strings:  # go through each string in our list
    print("String: {}\nEleventh character: {}".format(source, source[11]))
    if source[11] in ("N", "K"):  # check if it has `N` or `K` on its 11th position
        index = source.find(pattern)  # search for the pattern
        if index > -1:  # if the pattern is found anywhere in the string...
            print("Pattern start: {}\nPattern end: {}".format(index, index + len(pattern)))
        else:
            print("No match!")
    print("---")

Which will print out:

String: VGSEKVTMQNLNDRLAS
Eleventh character: N
Pattern start: 4
Pattern end: 11
---
String: VGSEKVTMQKLNDRLAS
Eleventh character: N
No match!
---

Not sure if that's exactly what you're looking for, tho, your question is a bit confusing.


问:
How to force crosstab to ignore width with Java code?
This method below export me a report to xlsx (excel) using JasperReport, but i have a problem. I need to set the property (ignore width == true), i need to set on java because i have another method that export me to PDF. I have tried so many forms but no luck. Any suggestion?

The property i need is called "Property_ignore_width", i need to know
  how to set this property on java.

```<code>public void exportexcel() throws JRException, IOException {
        conexion con = new conexion();
        Map<String, Object> parametros = new HashMap<String, Object>();
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
        parametros.put("movimiento", movimiento);
        parametros.put("desde", desde);
        parametros.put("hasta", hasta);

        String reporte = movimiento.equals("Descarga") ? "GeneralNaves.jasper" : "GeneralNavesExport.jasper";

        String dirReporte = servleContext.getRealPath("/reportes/" + reporte);
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=ReporteNaves_A_Naves.xlsx");
        response.setContentType("application/xlsx");

        JasperPrint impres = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
        JRXlsxExporter expor = new JRXlsxExporter();
        expor.setExporterInput(new SimpleExporterInput(impres));
        expor.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

        SimpleXlsxReportConfiguration config = new SimpleXlsxReportConfiguration();
        config.setCollapseRowSpan(Boolean.FALSE);
        config.setWhitePageBackground(Boolean.FALSE);
        config.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);
        expor.setConfiguration(config);
        expor.exportReport();
        context.responseComplete();
    }
</code>```

答:
We can change the value of net.sf.jasperreports.crosstab.ignore.width property with help of JasperReports API.

This property should be set for Crosstab element, not for the whole report.
It means that we should get the Crosstab element and use its method JRCrosstab.setIgnoreWidth(boolean)

Example

We can use the simple template with crosstab at Summary band with csv datasource.

Datasource

The csv datasource is using in example.

```<code>language,framework
Java,Guava
Java,Lombok
Java,JasperReports
Java,Spring
Java,Vaadin
C#,ASP.NET MVC
C#,NancyFX
C#,Automapper
JavaScript,AngularJS
JavaScript,React
JavaScript,jQuery
</code>```

The name of data adapter for this datasource in the example below is frameworks.csv. The first line from the file is skipped - it is contains the column's name.

Report template

The Crosstab is using the main dataset.

```<code><?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Crosstab with dynamic width" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="731dbfe4-e4ef-4631-8a59-1952b5bf048c">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="frameworks.csv"/>
    <field name="language" class="java.lang.String"/>
    <field name="framework" class="java.lang.String"/>
    <summary>
        <band height="120">
            <crosstab ignoreWidth="false">
                <reportElement x="90" y="30" width="200" height="90" uuid="8cc82b0a-4e26-4cc6-b0e2-e5d13a5190df">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                </reportElement>
                <rowGroup name="language" width="60" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{language}]]></bucketExpression>
                    </bucket>
                    <crosstabRowHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="449ab423-ade7-4962-804c-dc39f326eaa6"/>
                                <textFieldExpression><![CDATA[$V{language}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabRowHeader>
                    <crosstabTotalRowHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="f3873d23-8f90-46ec-8e4a-7ea5635eb3aa"/>
                                <text><![CDATA[Total language]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalRowHeader>
                </rowGroup>
                <columnGroup name="framework" height="20" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{framework}]]></bucketExpression>
                    </bucket>
                    <crosstabColumnHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="4ec3e655-ea93-406a-b5b9-b56a46c12b19"/>
                                <textFieldExpression><![CDATA[$V{framework}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabColumnHeader>
                    <crosstabTotalColumnHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4f9b4bdc-24fb-4df9-ab5f-423c82939535"/>
                                <text><![CDATA[Total framework]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalColumnHeader>
                </columnGroup>
                <measure name="language_MEASURE" class="java.lang.Integer" calculation="Count">
                    <measureExpression><![CDATA[$F{language}]]></measureExpression>
                </measure>
                <crosstabCell width="60" height="20">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" uuid="5e9cc753-3f32-4ab8-b79d-073fc574c85f"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="1ec48067-6435-463e-9688-768be0dd33be"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4208c8c9-fffa-48c3-acaa-6aeccc72c141"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="efb32f08-a362-4b68-b9ed-ba36a944d385"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
            </crosstab>
        </band>
    </summary>
</jasperReport>
</code>```

At Jaspersoft Studio the report's design looks like:

Java code

The main idea is to get crosstab element at Summary band and modify its property.

The Java 8 based code for setting property:

```<code>JasperReport jasperReport;
try (InputStream inputStream = JRLoader.getResourceInputStream(report.getTemplateName())) {
    jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
    Arrays.stream(jasperReport.getSummary().getElements()).filter(element -> element instanceof JRCrosstab)
            .forEach(jrElement -> ((JRCrosstab) jrElement).setIgnoreWidth(true)); // get all crosstabs and set PROPERTY_IGNORE_WIDTH property
}

try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("frameworks.csv")) {
    Map<String, Object> params = new HashMap<>();
    JRCsvDataSource ds = new JRCsvDataSource(inputStream);
    ds.setUseFirstRowAsHeader(true);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, ds);

    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    SimpleOutputStreamExporterOutput exporterOutput = null;
    try {
        exporterOutput = new SimpleOutputStreamExporterOutput(file);
        exporter.setExporterOutput(exporterOutput);
        exporter.exportReport();
    } finally {
        if (exporterOutput != null) {
            exporterOutput.close();
        }
    }
}
</code>```

Output result

The result generated by code will be:

If we commented string of code with setIgnoreWidth calling (net.sf.jasperreports.crosstab.ignore.width == false) the result will be:

Body:
This method below export me a report to xlsx (excel) using JasperReport, but i have a problem. I need to set the property (ignore width == true), i need to set on java because i have another method that export me to PDF. I have tried so many forms but no luck. Any suggestion?

The property i need is called "Property_ignore_width", i need to know
  how to set this property on java.

public void exportexcel() throws JRException, IOException {
        conexion con = new conexion();
        Map<String, Object> parametros = new HashMap<String, Object>();
        FacesContext context = FacesContext.getCurrentInstance();
        ServletContext servleContext = (ServletContext) context.getExternalContext().getContext();
        parametros.put("RutaImagen", servleContext.getRealPath("/reportes/"));
        parametros.put("movimiento", movimiento);
        parametros.put("desde", desde);
        parametros.put("hasta", hasta);

        String reporte = movimiento.equals("Descarga") ? "GeneralNaves.jasper" : "GeneralNavesExport.jasper";

        String dirReporte = servleContext.getRealPath("/reportes/" + reporte);
        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
        response.addHeader("Content-disposition", "attachment;filename=ReporteNaves_A_Naves.xlsx");
        response.setContentType("application/xlsx");

        JasperPrint impres = JasperFillManager.fillReport(dirReporte, parametros, con.getConnection());
        JRXlsxExporter expor = new JRXlsxExporter();
        expor.setExporterInput(new SimpleExporterInput(impres));
        expor.setExporterOutput(new SimpleOutputStreamExporterOutput(response.getOutputStream()));

        SimpleXlsxReportConfiguration config = new SimpleXlsxReportConfiguration();
        config.setCollapseRowSpan(Boolean.FALSE);
        config.setWhitePageBackground(Boolean.FALSE);
        config.setRemoveEmptySpaceBetweenRows(Boolean.TRUE);
        expor.setConfiguration(config);
        expor.exportReport();
        context.responseComplete();
    }

Body:
We can change the value of net.sf.jasperreports.crosstab.ignore.width property with help of JasperReports API.

This property should be set for Crosstab element, not for the whole report.
It means that we should get the Crosstab element and use its method JRCrosstab.setIgnoreWidth(boolean)

Example

We can use the simple template with crosstab at Summary band with csv datasource.

Datasource

The csv datasource is using in example.

language,framework
Java,Guava
Java,Lombok
Java,JasperReports
Java,Spring
Java,Vaadin
C#,ASP.NET MVC
C#,NancyFX
C#,Automapper
JavaScript,AngularJS
JavaScript,React
JavaScript,jQuery

The name of data adapter for this datasource in the example below is frameworks.csv. The first line from the file is skipped - it is contains the column's name.

Report template

The Crosstab is using the main dataset.

<?xml version="1.0" encoding="UTF-8"?>
<jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="Crosstab with dynamic width" pageWidth="595" pageHeight="842" whenNoDataType="AllSectionsNoDetail" columnWidth="555" leftMargin="20" rightMargin="20" topMargin="20" bottomMargin="20" uuid="731dbfe4-e4ef-4631-8a59-1952b5bf048c">
    <property name="com.jaspersoft.studio.data.defaultdataadapter" value="frameworks.csv"/>
    <field name="language" class="java.lang.String"/>
    <field name="framework" class="java.lang.String"/>
    <summary>
        <band height="120">
            <crosstab ignoreWidth="false">
                <reportElement x="90" y="30" width="200" height="90" uuid="8cc82b0a-4e26-4cc6-b0e2-e5d13a5190df">
                    <property name="com.jaspersoft.studio.layout" value="com.jaspersoft.studio.editor.layout.VerticalRowLayout"/>
                </reportElement>
                <rowGroup name="language" width="60" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{language}]]></bucketExpression>
                    </bucket>
                    <crosstabRowHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="449ab423-ade7-4962-804c-dc39f326eaa6"/>
                                <textFieldExpression><![CDATA[$V{language}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabRowHeader>
                    <crosstabTotalRowHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="f3873d23-8f90-46ec-8e4a-7ea5635eb3aa"/>
                                <text><![CDATA[Total language]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalRowHeader>
                </rowGroup>
                <columnGroup name="framework" height="20" totalPosition="End">
                    <bucket class="java.lang.String">
                        <bucketExpression><![CDATA[$F{framework}]]></bucketExpression>
                    </bucket>
                    <crosstabColumnHeader>
                        <cellContents mode="Opaque">
                            <textField>
                                <reportElement x="0" y="0" width="60" height="20" uuid="4ec3e655-ea93-406a-b5b9-b56a46c12b19"/>
                                <textFieldExpression><![CDATA[$V{framework}]]></textFieldExpression>
                            </textField>
                        </cellContents>
                    </crosstabColumnHeader>
                    <crosstabTotalColumnHeader>
                        <cellContents mode="Opaque">
                            <staticText>
                                <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4f9b4bdc-24fb-4df9-ab5f-423c82939535"/>
                                <text><![CDATA[Total framework]]></text>
                            </staticText>
                        </cellContents>
                    </crosstabTotalColumnHeader>
                </columnGroup>
                <measure name="language_MEASURE" class="java.lang.Integer" calculation="Count">
                    <measureExpression><![CDATA[$F{language}]]></measureExpression>
                </measure>
                <crosstabCell width="60" height="20">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" uuid="5e9cc753-3f32-4ab8-b79d-073fc574c85f"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="1ec48067-6435-463e-9688-768be0dd33be"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="4208c8c9-fffa-48c3-acaa-6aeccc72c141"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
                <crosstabCell width="60" height="20" rowTotalGroup="language" columnTotalGroup="framework">
                    <cellContents mode="Opaque">
                        <textField>
                            <reportElement x="0" y="0" width="60" height="20" forecolor="#FFFFFF" uuid="efb32f08-a362-4b68-b9ed-ba36a944d385"/>
                            <textFieldExpression><![CDATA[$V{language_MEASURE}]]></textFieldExpression>
                        </textField>
                    </cellContents>
                </crosstabCell>
            </crosstab>
        </band>
    </summary>
</jasperReport>

At Jaspersoft Studio the report's design looks like:

Java code

The main idea is to get crosstab element at Summary band and modify its property.

The Java 8 based code for setting property:

JasperReport jasperReport;
try (InputStream inputStream = JRLoader.getResourceInputStream(report.getTemplateName())) {
    jasperReport = JasperCompileManager.compileReport(JRXmlLoader.load(inputStream));
    Arrays.stream(jasperReport.getSummary().getElements()).filter(element -> element instanceof JRCrosstab)
            .forEach(jrElement -> ((JRCrosstab) jrElement).setIgnoreWidth(true)); // get all crosstabs and set PROPERTY_IGNORE_WIDTH property
}

try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("frameworks.csv")) {
    Map<String, Object> params = new HashMap<>();
    JRCsvDataSource ds = new JRCsvDataSource(inputStream);
    ds.setUseFirstRowAsHeader(true);

    JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, params, ds);

    exporter.setExporterInput(new SimpleExporterInput(jasperPrint));
    SimpleOutputStreamExporterOutput exporterOutput = null;
    try {
        exporterOutput = new SimpleOutputStreamExporterOutput(file);
        exporter.setExporterOutput(exporterOutput);
        exporter.exportReport();
    } finally {
        if (exporterOutput != null) {
            exporterOutput.close();
        }
    }
}

Output result

The result generated by code will be:

If we commented string of code with setIgnoreWidth calling (net.sf.jasperreports.crosstab.ignore.width == false) the result will be:


问:
How to select particular account while making oauth api call in google?
For Eg: Using google drive api i made an API call to get permission from user and generate access token and got user details using that token. In that case before getting permission from user if i logged in into multiple google accounts in my browser and i tried through particular mail Id through my app. I need to display only that mail id for permission , Not to display all the logged in mail ids. How to filter for particular mail id through api call.

My sample api call:

https://accounts.google.com/o/oauth2/auth?client_id=CLIENT_ID +&redirect_uri=REDIRECT_URI &scope=email+profile+https://www.googleapis.com/auth/drive&response_type=code&access_type=offline

I just removed prompt=select_account keyword from this api call. but it still display all accounts. How to filter for particular mail id?

答: You add the login_hint parameter with an account value to the authentication request.


问:
Get all lattice points lying inside a Shapely polygon
I need to find all the lattice points inside and on a polygon.

Input:

```<code>from shapely.geometry import Polygon, mapping
sh_polygon = Polygon(((0,0), (2,0), (2,2), (0,2)))
</code>```

Output:

```<code>(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)
</code>```

Please suggest if there is a way to get the expected result with or without using Shapely.

I have written this piece of code that gives points inside the polygon, but it doesn't give points on it. Also is there a better way to do the same thing:

```<code>from shapely.geometry import Polygon, Point

def get_random_point_in_polygon(poly):
    (minx, miny, maxx, maxy) = poly.bounds
    minx = int(minx)
    miny = int(miny)
    maxx = int(maxx)
    maxy = int(maxy)
    print("poly.bounds:", poly.bounds)
    a = []
    for x in range(minx, maxx+1):
        for y in range(miny, maxy+1):
            p = Point(x, y)
            if poly.contains(p):
                a.append([x, y])
    return a

p = Polygon([(0,0), (2,0), (2,2), (0,2)])
point_in_poly = get_random_point_in_polygon(p)

print(len(point_in_poly))
print(point_in_poly)
</code>```

Output:

```<code>poly.bounds: (0.0, 0.0, 2.0, 2.0)
1
[[1, 1]]
</code>```

I have simplified my problem. Actually, I need to find all points inside and on a square with corners: (77,97), (141,101), (136,165), (73,160).

答:
Is there not a function that will find lattice points that lie on a line?  Those are the only ones you're missing.  They are simply solutions to the line segment's defining equation.  If not, it's easy enough to write the algorithm yourself, finding the points by brute force.

Do the following for each edge (p1, p2) of the polygon.

```<code>p1 = (x1, y1)
p2 = (x2, y2)
xdiff = x2 - x1
ydiff = y2 - y1

# Find the line's equation, y = mx + b
m = ydiff / xdiff
b = y1 - m*x1

for xval in range(x1+1, x2):
    yval = m * xval + b
    if int(yval) == yval:
        # add (xval, yval) to your list of points
</code>```

I've left details up to you: make sure that x1 < x2 (or adapt otherwise), handle a vertical segment, etc.  This isn't particularly elegant, but it's fast, easy to implement, and easy to debug.

ContentLicense: CC BY-SA 4.0

Body:
I need to find all the lattice points inside and on a polygon.

Input:

from shapely.geometry import Polygon, mapping
sh_polygon = Polygon(((0,0), (2,0), (2,2), (0,2)))

Output:

(0, 0), (1, 0), (2, 0), (0, 1), (1, 1), (2, 1), (0, 2), (1, 2), (2, 2)

Please suggest if there is a way to get the expected result with or without using Shapely.

I have written this piece of code that gives points inside the polygon, but it doesn't give points on it. Also is there a better way to do the same thing:

from shapely.geometry import Polygon, Point

def get_random_point_in_polygon(poly):
    (minx, miny, maxx, maxy) = poly.bounds
    minx = int(minx)
    miny = int(miny)
    maxx = int(maxx)
    maxy = int(maxy)
    print("poly.bounds:", poly.bounds)
    a = []
    for x in range(minx, maxx+1):
        for y in range(miny, maxy+1):
            p = Point(x, y)
            if poly.contains(p):
                a.append([x, y])
    return a

p = Polygon([(0,0), (2,0), (2,2), (0,2)])
point_in_poly = get_random_point_in_polygon(p)

print(len(point_in_poly))
print(point_in_poly)

Output:

poly.bounds: (0.0, 0.0, 2.0, 2.0)
1
[[1, 1]]

I have simplified my problem. Actually, I need to find all points inside and on a square with corners: (77,97), (141,101), (136,165), (73,160).

Body:
Is there not a function that will find lattice points that lie on a line?  Those are the only ones you're missing.  They are simply solutions to the line segment's defining equation.  If not, it's easy enough to write the algorithm yourself, finding the points by brute force.

Do the following for each edge (p1, p2) of the polygon.

p1 = (x1, y1)
p2 = (x2, y2)
xdiff = x2 - x1
ydiff = y2 - y1

# Find the line's equation, y = mx + b
m = ydiff / xdiff
b = y1 - m*x1

for xval in range(x1+1, x2):
    yval = m * xval + b
    if int(yval) == yval:
        # add (xval, yval) to your list of points

I've left details up to you: make sure that x1 < x2 (or adapt otherwise), handle a vertical segment, etc.  This isn't particularly elegant, but it's fast, easy to implement, and easy to debug.


问:
Docker build seems to not see requirements.txt even though it's in same directory
I'm setting up a website, I have the backend set up using Django and Gunicorn, and I am trying to package the whole thing in a docker container. I am using docker 17.05.0-ce edge on Ubuntu 17.04 Zesty. For some reason, even though the directory mysite has the Dockerfile, Django app, requirements.txt, start.sh (on github here), the docker build stops at ADD requirements.txt /app/src/requirements.txt.

```<code># Dockerfile

# FROM base image to build upon
FROM phusion/baseimage

# RUN install python and pip
RUN apt-get update
RUN apt-get install -y python python-pip python-dev

# ADD requirements.txt and RUN pip to install them
ADD requirements.txt /app/src/requirements.txt
WORKDIR /app/src
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD execute start.sh to start the server running.

WORKDIR /app/src/mysite
CMD ["/start.sh"]
# done!
</code>```

I navigate to 'mysite', run docker build - < Dockerfile and it stops on the line where it copies requirements.txt and i get the following error:

```<code>Sending build context to Docker daemon  2.048kB
Step 1/9 : FROM phusion/baseimage
 ---> 877509368a8d
Step 2/9 : RUN apt-get update
 ---> Using cache
 ---> adcb4b9e8b08
Step 3/9 : RUN apt-get install -y python python-pip python-dev
 ---> Using cache
 ---> 8dbbd3e010d5
Step 4/9 : ADD requirements.txt /app/src/requirements.txt
lstat requirements.txt: no such file or directory
</code>```

Which, to me, says that I'm doing this all wrong.

答:
You are not sending a context to the docker daemon to build your project.

Use this:

```<code>docker build -t invent_an_image_name /path/to/mysite
</code>```

Body:
I'm setting up a website, I have the backend set up using Django and Gunicorn, and I am trying to package the whole thing in a docker container. I am using docker 17.05.0-ce edge on Ubuntu 17.04 Zesty. For some reason, even though the directory mysite has the Dockerfile, Django app, requirements.txt, start.sh (on github here), the docker build stops at ADD requirements.txt /app/src/requirements.txt.

# Dockerfile

# FROM base image to build upon
FROM phusion/baseimage

# RUN install python and pip
RUN apt-get update
RUN apt-get install -y python python-pip python-dev

# ADD requirements.txt and RUN pip to install them
ADD requirements.txt /app/src/requirements.txt
WORKDIR /app/src
RUN pip install -r requirements.txt

# EXPOSE port 8000 to allow communication to/from server
EXPOSE 8000

# CMD execute start.sh to start the server running.

WORKDIR /app/src/mysite
CMD ["/start.sh"]
# done!

I navigate to 'mysite', run docker build - < Dockerfile and it stops on the line where it copies requirements.txt and i get the following error:

Sending build context to Docker daemon  2.048kB
Step 1/9 : FROM phusion/baseimage
 ---> 877509368a8d
Step 2/9 : RUN apt-get update
 ---> Using cache
 ---> adcb4b9e8b08
Step 3/9 : RUN apt-get install -y python python-pip python-dev
 ---> Using cache
 ---> 8dbbd3e010d5
Step 4/9 : ADD requirements.txt /app/src/requirements.txt
lstat requirements.txt: no such file or directory

Which, to me, says that I'm doing this all wrong.

Body:
You are not sending a context to the docker daemon to build your project.

Use this:

docker build -t invent_an_image_name /path/to/mysite


问:
Why does oci_connect() throw an "undefined function" exception even though function_exists('oci_connect') returns true?
I have been struggling for the last few days to get PHP to connect to an oracle DB. I have been doing this with a MAMP stack installed on a window machine (it is available for windows and ensures a uniform development stack for our team). After struggling with the common problems related to the OCI8 installation I finally got it to show in phpinfo() with the following information OCI8 PHP info section

I can also see it as an installed module using the php -m command, the options using the php --ri oci8 command, and can find the installed dll files from the
oracle instant client using where oci*

It appears to be installed and I have a PATH variable linked to the instant client folder. There are no errors besides the call to undefined function in the MAMP log files.

I have not set the ORACLE_HOME, TNS_ADMIN or other oracle variables as they are not needed with the instant client libraries (my understanding)

I have uncommented the lines for the extension_dir and the extension=php_oci8_12c.dll in the php.ini file and have confirmed that I have been editing the correct file.

I have ran a simple php script in an index.php file containing the following lines

```<code><?php
    If(function_exists('oci_connect')){
      echo 'oci_connect exists';
      $conn = oci_connect();
    }
?>
</code>```

This is a simple test which should give me a warning complaining about improper parameters however the output of the script is

oci_connect exists
Fatal error: Uncaught Error: Call to undefined function  oci_connect() in C:\MAMP\htdocs\Oracle_Connection\index.php:16 Stack trace: #0 {main} thrown in C:\MAMP\htdocs\Oracle_Connection\index.php on line 16

I have run out of ideas on what might be wrong, none of the documentation in reference to setting up the OCI8 functionality seems to run into this issue.

Any help would be welcome.
Thanks

Output from cmd

```<code>C:\Users\geoff>php -m
[PHP Modules]
bcmath
calendar
com_dotnet
Core
ctype
date
dom
filter
hash
iconv
json
libxml
mcrypt
mysqlnd
oci8
odbc
openssl
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
soap
sockets
SPL
standard
tidy
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib
[Zend Modules]

C:\Users\geoff>php function_exists
Could not open input file: function_exists

C:\Users\geoff>php --ri oci8

oci8

OCI8 Support => enabled
OCI8 DTrace Support => disabled
OCI8 Version => 2.1.4
Revision => $Id: 03698b2e9b50593039b7ca292b2e3cf9eaf064b9 $
Oracle Run-time Client Library Version => 12.2.0.1.0
Oracle Compile-time Instant Client Version => 12.1

Directive => Local Value => Master Value
oci8.max_persistent => -1 => -1
oci8.persistent_timeout => -1 => -1
oci8.ping_interval => 60 => 60
oci8.privileged_connect => Off => Off
oci8.statement_cache_size => 20 => 20
oci8.default_prefetch => 100 => 100
oci8.old_oci_close_semantics => Off => Off
oci8.connection_class => no value => no value
oci8.events => Off => Off

Statistics =>
Active Persistent Connections => 0
Active Connections => 0

C:\Users\geoff>where oci*
C:\Oracle\instantclient_12_2\oci.dll
C:\Oracle\instantclient_12_2\oci.sym
C:\Oracle\instantclient_12_2\ocijdbc12.dll
C:\Oracle\instantclient_12_2\ocijdbc12.sym
C:\Oracle\instantclient_12_2\ociw32.dll
C:\Oracle\instantclient_12_2\ociw32.sym
</code>```

答:
You are calling oci_connect() with no parameters.

Pass the username and password for your database to the function as stated in the documentation

Body:
I have been struggling for the last few days to get PHP to connect to an oracle DB. I have been doing this with a MAMP stack installed on a window machine (it is available for windows and ensures a uniform development stack for our team). After struggling with the common problems related to the OCI8 installation I finally got it to show in phpinfo() with the following information OCI8 PHP info section

I can also see it as an installed module using the php -m command, the options using the php --ri oci8 command, and can find the installed dll files from the
oracle instant client using where oci*

It appears to be installed and I have a PATH variable linked to the instant client folder. There are no errors besides the call to undefined function in the MAMP log files.

I have not set the ORACLE_HOME, TNS_ADMIN or other oracle variables as they are not needed with the instant client libraries (my understanding)

I have uncommented the lines for the extension_dir and the extension=php_oci8_12c.dll in the php.ini file and have confirmed that I have been editing the correct file.

I have ran a simple php script in an index.php file containing the following lines

<?php
    If(function_exists('oci_connect')){
      echo 'oci_connect exists';
      $conn = oci_connect();
    }
?>

This is a simple test which should give me a warning complaining about improper parameters however the output of the script is

oci_connect exists
Fatal error: Uncaught Error: Call to undefined function  oci_connect() in C:\MAMP\htdocs\Oracle_Connection\index.php:16 Stack trace: #0 {main} thrown in C:\MAMP\htdocs\Oracle_Connection\index.php on line 16

I have run out of ideas on what might be wrong, none of the documentation in reference to setting up the OCI8 functionality seems to run into this issue.

Any help would be welcome.
Thanks

Output from cmd

C:\Users\geoff>php -m
[PHP Modules]
bcmath
calendar
com_dotnet
Core
ctype
date
dom
filter
hash
iconv
json
libxml
mcrypt
mysqlnd
oci8
odbc
openssl
pcre
PDO
pdo_mysql
Phar
Reflection
session
SimpleXML
soap
sockets
SPL
standard
tidy
tokenizer
wddx
xml
xmlreader
xmlwriter
zip
zlib
[Zend Modules]

C:\Users\geoff>php function_exists
Could not open input file: function_exists

C:\Users\geoff>php --ri oci8

oci8

OCI8 Support => enabled
OCI8 DTrace Support => disabled
OCI8 Version => 2.1.4
Revision => $Id: 03698b2e9b50593039b7ca292b2e3cf9eaf064b9 $
Oracle Run-time Client Library Version => 12.2.0.1.0
Oracle Compile-time Instant Client Version => 12.1

Directive => Local Value => Master Value
oci8.max_persistent => -1 => -1
oci8.persistent_timeout => -1 => -1
oci8.ping_interval => 60 => 60
oci8.privileged_connect => Off => Off
oci8.statement_cache_size => 20 => 20
oci8.default_prefetch => 100 => 100
oci8.old_oci_close_semantics => Off => Off
oci8.connection_class => no value => no value
oci8.events => Off => Off

Statistics =>
Active Persistent Connections => 0
Active Connections => 0

C:\Users\geoff>where oci*
C:\Oracle\instantclient_12_2\oci.dll
C:\Oracle\instantclient_12_2\oci.sym
C:\Oracle\instantclient_12_2\ocijdbc12.dll
C:\Oracle\instantclient_12_2\ocijdbc12.sym
C:\Oracle\instantclient_12_2\ociw32.dll
C:\Oracle\instantclient_12_2\ociw32.sym


问:
How to understand this C++ palindrome code?
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?</p>

```<code>#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}
</code>```

答:
string::rbegin (reverse begin) is iterator to begin of your reverse string (last character of your string), and string::rend (reverse end) is the iterator to end of your reverse string (first character of your string).

The string constructor can expect two iterators to create a new string, first one, will be the begin of your string and the second one the end.

When you pass to the constructor the reverse begin and reverse end of inputString it is creating a reverse string of inputString.

Body:
I recently came to the solution of the palindrome problem, but I do not understand how this part of code works (with rbegin and rend). Can someone explain it to me?

#include <iostream>
#include <string>

using namespace std;
bool checkPalindrome(string);
int main()
{
    string inputString = "palindrom";
    cout << checkPalindrome(inputString);
return 0;
}

bool checkPalindrome(std::string inputString)
{
   return (inputString == string(inputString.rbegin(), inputString.rend()));
}


问:
Laravel 5.4 getting third table information eloquent relationships
So there are three tables:

Schema::create('files_urls', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('file_id')->unsigned();
         $table->foreign('file_id')->references('id')->on('files');
         $table->string('filename');
         $table->timestamps();
        });

public function up()
    {
     Schema::create('files', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamp('date');
      $table->string('name');
      $table->string('description');
      $table->integer('group_id');
      $table->timestamps();
     });
    }

Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('course_id');
            $table->timestamp('start_date')->nullable();
            $table->timestamp('end_date')->nullable();
            $table->timestamps();
        });```
</div>
</div>
</p>

<p>Landing page controller looks like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>public function listFiles($id){
  $group = Group::find($id);
  $data ['gInfo'] = $group;
  $files = Group::find($id)->file;
  $data ['fInfo'] = $files;
  return view('upload.files', $data);
 }</code>```

loop in the blade file:

@foreach ($fInfo as $file)

     {{$file->date}}
     {{$file->name}}
     {{$file->description}}
     @foreach($file->file as $url)
      {{$url->file->filename}}
     @endforeach

   @endforeach```
</div>
</div>
</p>

<p>Basically, i want to print all information from the file(probably the name is not right here - should be called lesson or something). However, 1 lesson (file) can have a few names (from files_urls table). So it should print date, name, description and all names that it has in the files_urls table in one row for each lesson(file).</p>

<p>relationships are like this:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>class FilesUrl extends Model
{
 protected $fillable = ['file_id', 'filename'];

 public function file()
 {
  return $this->belongsTo('App\File');
 }
}

public function file(){
  return $this->hasMany('App\File');
 }</code>```

Thank you in advance.

答:
It doesn't look as though your model relationships are set up correctly, or that you're accessing them correctly.

You can also make some efficiencies in your controller by not querying for the Group model twice.

I have assumed from your database schema that a Group has many Files and a File has many FilesUrls.

```<code><?php

// app/Group.php
namespace App;

class Group extends Model
{
    // ...

    public function files()
    {
        return $this->hasMany(App\File::class);
    }

    // ...
}

// app/File.php
namespace App;

class File extends Model
{
    // ...

    public function group()
    {
        return $this->belongsTo(App\Group::class);
    }

    public function urls()
    {
        return $this->hasMany(App\FilesUrl::class)
    }

    // ...
}

// app/FilesUrl.php
namespace App;

class FilesUrl extends Model
{
    // ...

    public function file()
    {
        return $this->belongsTo(App\File::class);
    }

    // ...
}

// app/Http/Controllers/LandingPageController.php
namespace App\Http\Controllers;

class LandingPageController extends Controller
{
    // ...

    public function listFiles($id)
    {
        $group = Group::with('files.urls')->findOrFail($id);
        return view('upload.files', compact('group'));
    }

    // ...
}

// resources/views/upload/files.blade.php
@foreach ($group->files as $file)
    <tr>
        <td>{{$file->date}}</td>
        <td>{{$file->name}}</td>
        <td>{{$file->description}}</td>
        <td>
            @foreach($file->urls as $url)
                {{$url->filename}}
            @endforeach
        </td>
    </tr>
        @endforeach
@endforeach
</code>```

Body:
So there are three tables:

Schema::create('files_urls', function (Blueprint $table) {
         $table->increments('id');
         $table->integer('file_id')->unsigned();
         $table->foreign('file_id')->references('id')->on('files');
         $table->string('filename');
         $table->timestamps();
        });

public function up()
    {
     Schema::create('files', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamp('date');
      $table->string('name');
      $table->string('description');
      $table->integer('group_id');
      $table->timestamps();
     });
    }

Schema::create('groups', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('course_id');
            $table->timestamp('start_date')->nullable();
            $table->timestamp('end_date')->nullable();
            $table->timestamps();
        });

Landing page controller looks like this:

public function listFiles($id){
  $group = Group::find($id);
  $data ['gInfo'] = $group;
  $files = Group::find($id)->file;
  $data ['fInfo'] = $files;
  return view('upload.files', $data);
 }

loop in the blade file:

@foreach ($fInfo as $file)

     {{$file->date}}
     {{$file->name}}
     {{$file->description}}
     @foreach($file->file as $url)
      {{$url->file->filename}}
     @endforeach

   @endforeach

Basically, i want to print all information from the file(probably the name is not right here - should be called lesson or something). However, 1 lesson (file) can have a few names (from files_urls table). So it should print date, name, description and all names that it has in the files_urls table in one row for each lesson(file).

relationships are like this:

class FilesUrl extends Model
{
 protected $fillable = ['file_id', 'filename'];

 public function file()
 {
  return $this->belongsTo('App\File');
 }
}

public function file(){
  return $this->hasMany('App\File');
 }

Thank you in advance.

Body:
It doesn't look as though your model relationships are set up correctly, or that you're accessing them correctly.

You can also make some efficiencies in your controller by not querying for the Group model twice.

I have assumed from your database schema that a Group has many Files and a File has many FilesUrls.

<?php

// app/Group.php
namespace App;

class Group extends Model
{
    // ...

    public function files()
    {
        return $this->hasMany(App\File::class);
    }

    // ...
}

// app/File.php
namespace App;

class File extends Model
{
    // ...

    public function group()
    {
        return $this->belongsTo(App\Group::class);
    }

    public function urls()
    {
        return $this->hasMany(App\FilesUrl::class)
    }

    // ...
}

// app/FilesUrl.php
namespace App;

class FilesUrl extends Model
{
    // ...

    public function file()
    {
        return $this->belongsTo(App\File::class);
    }

    // ...
}

// app/Http/Controllers/LandingPageController.php
namespace App\Http\Controllers;

class LandingPageController extends Controller
{
    // ...

    public function listFiles($id)
    {
        $group = Group::with('files.urls')->findOrFail($id);
        return view('upload.files', compact('group'));
    }

    // ...
}

// resources/views/upload/files.blade.php
@foreach ($group->files as $file)
    <tr>
        <td>{{$file->date}}</td>
        <td>{{$file->name}}</td>
        <td>{{$file->description}}</td>
        <td>
            @foreach($file->urls as $url)
                {{$url->filename}}
            @endforeach
        </td>
    </tr>
        @endforeach
@endforeach