问:
How to populate Identity Framework tables & custom tables without getting Invalid object name
I'm using ASP.NET MVC 5 framework to implement a simple project. In that project, I would like to use Identity Framework Tables (users, roles, etc..) as well as customized tables (student, landlord, etc..).

I also would like to initialize the tables with some values, therefore I added the following function to my home controller:

```<code>    public void PopulateAspNetTables()
    {
        context = new ApplicationDbContext();

        // Define Users and insert them to IF database :
        // **********************************************
        var passwordHash = new PasswordHasher();
        string password = passwordHash.HashPassword("Password@123");

        ApplicationUser user1 = new ApplicationUser
        {
            UserName = "user1",
            Email = "user1@user1.com",
            PasswordHash = password
        };
        context.Users.AddOrUpdate(user1);
        context.SaveChanges();
    }
</code>```

as well as :

```<code>    public void PopulateOurDatabase()
    {

        dbCntxt = new DatabaseContext();

        stdnt = new Student {StudentID = 1, FirstName = "FN", LastName = "LN", Age = 27, Sex = "Male", ContactNumber = "123456", Email = "user1@gmail.com", AcademicYear = 1, AcademicDegree = "Electrical Engineering", AcademicSubject = "blabla" };
        dbCntxt.Students.AddOrUpdate(stdnt);
        dbCntxt.SaveChanges();
</code>```

The previous two functions will be called in the Home Controller constructor:

```<code>    public class HomeController : Controller
    {
    private DatabaseContext dbCntxt;
    private ApplicationDbContext context;

    private Student stdnt;

    public HomeController()
    {

        PopulateOurDatabase();
        PopulateAspNetTables();
    }
....
....
}
</code>```

Now the problem is that whenever I call the two functions in the constructor, the first one works correctly, while the second one throws always an error :

```<code>SqlException: Invalid object name 'dbo.AspNetUsers'.
</code>```

If I change the order in which I call the functions, AspNetUsers table would be created properly, while I get the same error regarding Student tables. This can be clearly seen in the Server Explorer !

Why is that happening?

And since I created my own context, does this occur because I'm using two different contexts ? What's the best practice in this case ?

Thank you.

答:
I did not test but use "using" keyword to close each connection.

```<code> public void PopulateOurDatabase()
{
   using (dbCntxt = new DatabaseContext())
   {
    stdnt = new Student {StudentID = 1, FirstName = "FN", LastName = "LN",
    Age = 27, Sex = "Male", ContactNumber = "123456", Email =
   "user1@gmail.com", AcademicYear = 1, AcademicDegree = "Electrical
   Engineering", AcademicSubject = "blabla" };
    dbCntxt.Students.AddOrUpdate(stdnt);
    dbCntxt.SaveChanges();
   }
</code>```

Body:
I'm using ASP.NET MVC 5 framework to implement a simple project. In that project, I would like to use Identity Framework Tables (users, roles, etc..) as well as customized tables (student, landlord, etc..).

I also would like to initialize the tables with some values, therefore I added the following function to my home controller:

    public void PopulateAspNetTables()
    {
        context = new ApplicationDbContext();

        // Define Users and insert them to IF database :
        // **********************************************
        var passwordHash = new PasswordHasher();
        string password = passwordHash.HashPassword("Password@123");

        ApplicationUser user1 = new ApplicationUser
        {
            UserName = "user1",
            Email = "user1@user1.com",
            PasswordHash = password
        };
        context.Users.AddOrUpdate(user1);
        context.SaveChanges();
    }

as well as :

    public void PopulateOurDatabase()
    {

        dbCntxt = new DatabaseContext();

        stdnt = new Student {StudentID = 1, FirstName = "FN", LastName = "LN", Age = 27, Sex = "Male", ContactNumber = "123456", Email = "user1@gmail.com", AcademicYear = 1, AcademicDegree = "Electrical Engineering", AcademicSubject = "blabla" };
        dbCntxt.Students.AddOrUpdate(stdnt);
        dbCntxt.SaveChanges();

The previous two functions will be called in the Home Controller constructor:

    public class HomeController : Controller
    {
    private DatabaseContext dbCntxt;
    private ApplicationDbContext context;

    private Student stdnt;

    public HomeController()
    {

        PopulateOurDatabase();
        PopulateAspNetTables();
    }
....
....
}

Now the problem is that whenever I call the two functions in the constructor, the first one works correctly, while the second one throws always an error :

SqlException: Invalid object name 'dbo.AspNetUsers'.

If I change the order in which I call the functions, AspNetUsers table would be created properly, while I get the same error regarding Student tables. This can be clearly seen in the Server Explorer !

Why is that happening?

And since I created my own context, does this occur because I'm using two different contexts ? What's the best practice in this case ?

Thank you.

Body:
I did not test but use "using" keyword to close each connection.

 public void PopulateOurDatabase()
{
   using (dbCntxt = new DatabaseContext())
   {
    stdnt = new Student {StudentID = 1, FirstName = "FN", LastName = "LN",
    Age = 27, Sex = "Male", ContactNumber = "123456", Email =
   "user1@gmail.com", AcademicYear = 1, AcademicDegree = "Electrical
   Engineering", AcademicSubject = "blabla" };
    dbCntxt.Students.AddOrUpdate(stdnt);
    dbCntxt.SaveChanges();
   }


来源: stackexchange

问:
How to execute a same query for 7 days in Oracle sql developer
I have a query

```<code>select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);
</code>```

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

```<code>  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110
</code>```

Is it achievable ?

答:
This should work in your case:</p>

```<code>SELECT TRUNC (p.start_time), COUNT (*)
    FROM purchases p
   WHERE     START_TIME >= sysdate - INTERVAL '7' DAY
         AND START_TIME <= sysdate
          AND TO_CHAR (start_time, 'HH24:MI') IN ('00:00', '01:00')
         AND CLIENT_ID IN (1, 54)
GROUP BY p.start_time
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a query

select count(*)
from purchases
where START_TIME>=TO_DATE('10-NOV-2017 00:00','DD-MON-YY HH24:MI') AND START_TIME<TO_DATE('10-NOV-2017 01:00','DD-MON-YY HH24:MI') and
      CLIENT_ID in (1,54);

and by using this I am gathering stats for an hour. But I am going to need stats everyday for the same time for past 7 days.

I mean, from above query I am gathering between 10-NOV-2017 00:00 and 10-NOV-2017 01:00 and similarly I need to gather for 09-NOV-2017 00:00 to 09-NOV-2017 01:00 and so on for past 7 days.

And it should print like

  Date        | Count
+-------------+-------+
  10-NOV-2017 | 100
  09-NOV-2017 | 110

Is it achievable ?

Body:
This should work in your case:

SELECT TRUNC (p.start_time), COUNT (*)
    FROM purchases p
   WHERE     START_TIME >= sysdate - INTERVAL '7' DAY
         AND START_TIME <= sysdate
          AND TO_CHAR (start_time, 'HH24:MI') IN ('00:00', '01:00')
         AND CLIENT_ID IN (1, 54)
GROUP BY p.start_time


问:
How to loop over a number in React inside JSX
I need to be able to loop over a number and return some jsx. For example

```<code><ul>
 {for(i =0; i < 10; i++){
   return <li>{i}</li>
 }}
</ul>
</code>```

This is not exactly what I want to do, but if I can solve this then I should be able to complete what I need to do. This however returns expression expected on the for. I have done some research and people say you can't use for loops inside of jsx because they do not return anything.

How do I go about looping over a number to return some amount of jsx?

答:
You can do it like this :</p>

```<code>createElements(n){
    var elements = [];
    for(i =0; i < n; i++){
        elements.push(<li>{i}</li>);
    }
    return elements;
}

<ul>
    {this.createElements(20)}
</ul>
</code>```

Body:
I need to be able to loop over a number and return some jsx. For example

 {for(i =0; i < 10; i++){
   return
{i}

 }}

This is not exactly what I want to do, but if I can solve this then I should be able to complete what I need to do. This however returns expression expected on the for. I have done some research and people say you can't use for loops inside of jsx because they do not return anything.

How do I go about looping over a number to return some amount of jsx?

Body:
You can do it like this :

createElements(n){
    var elements = [];
    for(i =0; i < n; i++){
        elements.push(<li>{i}</li>);
    }
    return elements;
}

<ul>
    {this.createElements(20)}
</ul>


问:
How to enable/ disable javascript based on environment?
I am trying to put in scripts for google analytics in my code. But I want it to run only if the environment is production and not in dev or qa. This javascript runs at page load itself and I am confused how to make it run conditionally. My app is an asp.net app.

Javascript is always confusing to me. There are many other javascripts in the page and I just need to disable this one. Had it been a .net code/function I would check for the environment and conditionally run the function. But I am confused about how to accomplish this type of functionality with javascript

答:
I don't know about ASP but you can include html script tag conditionally</p>

```<code>var DEVEL = true;

if (!DEVEL) {
   #call  echo function or whatever ASP have
   echo "<script <!-- put code for google analytics here -->";
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I don't know about ASP but you can include html script tag conditionally

var DEVEL = true;

if (!DEVEL) {
   #call  echo function or whatever ASP have
   echo "<script <!-- put code for google analytics here -->";
}


问:
Forfiles - spaces in folder path
I am running a batch file and I have one forfiles command in it

```<code>FORFILES -p%spinputarchrootpath% -m*.csv -d-365 -c"CMD /C DEL @FILE"

%spinputarchrootpath% variable maps to a folder location (Y:\Temp Documents\testfolder).
</code>```

Now the above command is throwing an error because of the space in the folder name (Temp Documents).

How to handle this space? I have tried putting quotes around %spinputarchrootpath% variable but it is not working.

答:
I'd the same problem and found the solution.
I think your folder-variable of the folder you wish to empty has a backslash at the end.

This will NOT work:

echo J|forfiles /P "C:\temp files\" /S /M * /D -7 /C "cmd /c del /F /S /Q @path"

... but this works (without backslash)

echo J|forfiles /P "C:\temp files" /S /M * /D -7 /C "cmd /c del /F /S /Q @path"

Regards

Tino

ContentLicense: CC BY-SA 4.0

Title: Forfiles - spaces in folder path

Body:
I am running a batch file and I have one forfiles command in it

FORFILES -p%spinputarchrootpath% -m*.csv -d-365 -c"CMD /C DEL @FILE"

%spinputarchrootpath% variable maps to a folder location (Y:\Temp Documents\testfolder).

Now the above command is throwing an error because of the space in the folder name (Temp Documents).

How to handle this space? I have tried putting quotes around %spinputarchrootpath% variable but it is not working.


问:
How to Print Unicode (Bangla Font) to Thermal Printer?
I want to Print Bangla text Like "আপনি কি ডাটা সংরক্ষন করতে চান" from my android app.But i got wrong result every time. Here is my Output:

My Code is Here:

```<code>   String memo = "আপনি কি ডাটা সংরক্ষন করতে চান" + "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n";

    byte[] buffer = memo.getBytes(Charset.forName("UTF-8"));

    try {
        Toast.makeText(getApplicationContext(), "Starting...", Toast.LENGTH_LONG).show();

        Thread.sleep(1000);
        byte[] printformat = {27, 33, 01};
        mmOutputStream.write(printformat);
        mmOutputStream.write(buffer);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.flush();

        mmOutputStream.close();
        mmSocket.close();
        Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
        mmOutputStream.close();
        mmSocket.close();
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(),
                "Excep IntentPrint", Toast.LENGTH_SHORT).show();
  }
</code>```

答: First of all please check the printer has bangla font support. if not then another way you can print.  you need to capture the layout which has the bangla text as image (bitmap)  then use the printers bitmap printing api.  I had the same problem for arabic text. i solve this problem using this technique.  thanks. </p>

Body:
I want to Print Bangla text Like "আপনি কি ডাটা সংরক্ষন করতে চান" from my android app.But i got wrong result every time. Here is my Output:

My Code is Here:

   String memo = "আপনি কি ডাটা সংরক্ষন করতে চান" + "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n" +
            "\n";

    byte[] buffer = memo.getBytes(Charset.forName("UTF-8"));

    try {
        Toast.makeText(getApplicationContext(), "Starting...", Toast.LENGTH_LONG).show();

        Thread.sleep(1000);
        byte[] printformat = {27, 33, 01};
        mmOutputStream.write(printformat);
        mmOutputStream.write(buffer);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.write(0x0B);
        mmOutputStream.flush();

        mmOutputStream.close();
        mmSocket.close();
        Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show();
        mmOutputStream.close();
        mmSocket.close();
    } catch (Exception ex) {
        Toast.makeText(getApplicationContext(),
                "Excep IntentPrint", Toast.LENGTH_SHORT).show();
  }


问:
weird phenomena during deadlocks involving IMAGE or TEXT columns
This is something very disturbing I stumbled upon while stress-testing an application using Sybase ASE 15.7.

We have the following table:

```<code>CREATE TABLE foo
(
    i INT NOT NULL,
    blob  IMAGE
);
ALTER TABLE foo ADD PRIMARY KEY (i);
</code>```

The table has, even before starting the test, a single row with some data in the IMAGE column. No rows are either deleted or inserted during the test. So the table always contains a single row. Column blob is only updated (in transaction T1 below) to some value (not NULL).

Then, we have the following two transactions:

```<code>T1: UPDATE foo SET blob=<some not null value> WHERE i=1
T2: SELECT * FROM foo WHERE i=1
</code>```

For some reason, the above transactions may deadlock under load (approx. 10 threads doing T1 20 times in a loop and another 10 threads doing T2 20 times in loop).

This is already weird enough, but there's more to come. T1 is always chosen as the deadlock victim. So, the application logic, on the event of a deadlock (error code 1205) simply retries T1. This should work and should normally be the end of the story. However …

… it happens that sometimes T2 will retrieve a row in which the value of the blob column is NULL! This is even though the table already starts with a row and the updates simply reset the previous (non-NULL) value to some other (non-NULL) value. This is 100% reproducible in every test run.

This is observed with the READ COMMITTED serialization level.

I verified that the above behavior also occurs with the TEXT column type but not with VARCHAR.

I've also verified that obtaining an exlusive lock on table foo in transaction T1 makes the issue go away.

So I'd like to understand how can something that so fundamentally breaks transaction isolation be even possible? In fact, I think this is worse than transaction isolation as T1 never sets the value of the blob column to NULL.

The test code is written in Java using the jconn4.jar driver (class com.sybase.jdbc4.jdbc.SybDriver) so I don't rule out that this may be a JDBC driver bug.

update

This is reproducible simply using isql and spawning several shells in parallel that continuously execute T1 in a loop. So I am removing the Java and JDBC tags as this is definitely server-related.

答:
Your example create table code by default would create an allpages locked table unless your DBA has changed the system-wide 'lock scheme' parameter via sp_configure to another value(you can check this yourself as anyone via sp_configure 'lock scheme'.

Unless you have a very large number of rows they are all going to be sat on a single data page because an int is only 4 bytes long and the blob data is stored at the end of the table (unless you use the in-row LOB functionality in ASE15.7 and up). This is why you are getting deadlocks. You have by definition created a single hotspot where all the data is being accessed at the page level. This is even more likely where larger page sizes > 2k are used, since by their nature they will have even more rows per page and with allpages locking, even more likelihood of contention.

Change your locking scheme to datarows (unless you are planning to have very high rowcounts) as has been said above and your problem should go away. I will add that your blob column looks to allow nulls from your code, so you should also consider setting the 'dealloc_first_txtpg' attribute for your table to avoid wasted space if you have nulls in your image column.

Body:
This is something very disturbing I stumbled upon while stress-testing an application using Sybase ASE 15.7.

We have the following table:

CREATE TABLE foo
(
    i INT NOT NULL,
    blob  IMAGE
);
ALTER TABLE foo ADD PRIMARY KEY (i);

The table has, even before starting the test, a single row with some data in the IMAGE column. No rows are either deleted or inserted during the test. So the table always contains a single row. Column blob is only updated (in transaction T1 below) to some value (not NULL).

Then, we have the following two transactions:

T1: UPDATE foo SET blob=<some not null value> WHERE i=1
T2: SELECT * FROM foo WHERE i=1

For some reason, the above transactions may deadlock under load (approx. 10 threads doing T1 20 times in a loop and another 10 threads doing T2 20 times in loop).

This is already weird enough, but there's more to come. T1 is always chosen as the deadlock victim. So, the application logic, on the event of a deadlock (error code 1205) simply retries T1. This should work and should normally be the end of the story. However …

… it happens that sometimes T2 will retrieve a row in which the value of the blob column is NULL! This is even though the table already starts with a row and the updates simply reset the previous (non-NULL) value to some other (non-NULL) value. This is 100% reproducible in every test run.

This is observed with the READ COMMITTED serialization level.

I verified that the above behavior also occurs with the TEXT column type but not with VARCHAR.

I've also verified that obtaining an exlusive lock on table foo in transaction T1 makes the issue go away.

So I'd like to understand how can something that so fundamentally breaks transaction isolation be even possible? In fact, I think this is worse than transaction isolation as T1 never sets the value of the blob column to NULL.

The test code is written in Java using the jconn4.jar driver (class com.sybase.jdbc4.jdbc.SybDriver) so I don't rule out that this may be a JDBC driver bug.

update

This is reproducible simply using isql and spawning several shells in parallel that continuously execute T1 in a loop. So I am removing the Java and JDBC tags as this is definitely server-related.


问:
Character Segmentation fails on 'W'
I am using OpenCV for OCR of printed codes containing arbitrary characters and numbers. My pipeline involves thresholding, denoising, gradient morphology, and then finding the contours in order to palce a bounding box around each letter.

It works very well except when a 'W' appears in the code. It usually places 2 or 3 bounding boxes such that the prediction is "VAV" or "VV", which is honestly a mistake my own eyes might make when I'm tired.

Does anyone have any ideas how best to address this issue? I can be fairly certain that a 'W' appears in many of these codes and it needs to be segmented properly. Thanks for any help!

答:
I found a solution that worked, at least in my case. I iteratively compute the relative overlap of neighboring bounding boxes, combining bounding boxes that have an overlap greater than a specified threshold (0.15 in my case). This works very effectively for my data.

Here is a cropping as an example:

Title: Character Segmentation fails on 'W'


问:
ERROR- ORA-00060: deadlock detected while waiting for resource
I got this error when running a procedure
I would like to know if it is possible to see the trace file on the server
about the details</p>

答:
You can find such informations in the alert<your_sid>.log file.
By <your_sid>, i mean the value when you issue $ echo $ORACLE_SID ( mostly set as this ).

It's under $ORACLE_BASE/diag/rdbms/<your_sid>/<your_sid>/trace path location.

You may also see the value for base path by issuing

$ echo $ORACLE_BASE( or alternatively, you would keep under
  $ORACLE_HOME directory, instead ).

You can also query

gv$diag_info
  performance view ( g stands whether you have a RAC instance ) to see the path.


答:
You need to use recursive iterators such as map, forEach, filter etc. If you really need to do something like this you can

```<code>const statelessComp = props => {
    let arr = Array.apply(null, {length: 10}).map(Number.call, Number);
    return (
        <ul>
            {arr.map(item => {
                return <li>{item}</li>
            })}
        </ul>
    )
}
</code>```

edit: these are the functions you should familiarize yourself with

Title: How to loop over a number in React inside JSX

Body:
You need to use recursive iterators such as map, forEach, filter etc. If you really need to do something like this you can

const statelessComp = props => {
    let arr = Array.apply(null, {length: 10}).map(Number.call, Number);
    return (
        <ul>
            {arr.map(item => {
                return <li>{item}</li>
            })}
        </ul>
    )
}

edit: these are the functions you should familiarize yourself with


问:
Identify how the function has been called in closure javascript
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

```<code>function multiply(a,b) {
     return a*b;
}
</code>```

Now here is the problem the function might call in different ways such as

```<code>multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);
</code>```

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

```<code>function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}
</code>```

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

答:
To have an unlimited callchain you need some js trick:

```<code>function multiply(...args){
  //make the chain endless through using some recursive like stuff:
  const func = (...args2) => multiply(...args,...args2);
  //the chains endpoint:
  func.valueOf = function(){
     return args.reduce((a,b) => a*b);
  };
  return func;
}
</code>```

The problem of such variable currying is that its infinite, so theres ( usually ) no way to end it.

```<code>multiply(1) // func :/
</code>```

However in javascript its possible to assign methods to functions so we can easily somewhen call the method instead of the function to end the chain:

```<code>multiply(1)(2)(3).valueOf()
</code>```

So you can simply do:

```<code> console.log(
  +multiply(1,2,3)(4)(5),
  +multiply(1,2)
);
</code>```

The + is equal to valueOf and is therefore neccessary to end the chain, however this call to valueOf is inferred by many operations in javascript ( all math operations like - * /).

Body:
Recently i faced one problem in hackerrank which has to calculate multiplication operation and has to return the answer. For example

function multiply(a,b) {
     return a*b;
}

Now here is the problem the function might call in different ways such as

multiply(4,5);
multiply(4)(5);
multiply(4)(5)(6);

I know we have to closure apporach for the second one which is multiply(4)(5). I had written code for that

function multiply(a,b) {
  return function(b) {
    return a*b;
  }
}

Now what if its been multiply function has been called with 3 arguments multiply(4)(5)(6). How can i identify how the function has been called and how can i write a common solution for all the inputs.

Any help is appreciated. Thanks

Body:
To have an unlimited callchain you need some js trick:

function multiply(...args){
  //make the chain endless through using some recursive like stuff:
  const func = (...args2) => multiply(...args,...args2);
  //the chains endpoint:
  func.valueOf = function(){
     return args.reduce((a,b) => a*b);
  };
  return func;
}

The problem of such variable currying is that its infinite, so theres ( usually ) no way to end it.

multiply(1) // func :/

However in javascript its possible to assign methods to functions so we can easily somewhen call the method instead of the function to end the chain:

multiply(1)(2)(3).valueOf()

So you can simply do:

 console.log(
  +multiply(1,2,3)(4)(5),
  +multiply(1,2)
);

The + is equal to valueOf and is therefore neccessary to end the chain, however this call to valueOf is inferred by many operations in javascript ( all math operations like - * /).


问:
reveal.js how to start in middle of presentation
Is it possible to start in the middle of a presentation with reveal.js? I would like the first slide to have the option of going up,down,foward ,back to act like a quiz. or do any of you know of a program that can do this. </p>

答:
Sorry for the late answer, but hope that this answer could help somebody in the future.

You can use the reveal.js API to achieve that.

Simply use the call to Reveal.slide function after the 'ready' event is called.

```<code>Reveal.slide( indexh, indexv, indexf );
</code>```

Reveal.initialize();
Reveal.addEventListener( 'ready', function( event ) {
  Reveal.slide(2, 1); //go to slide horizontal / vertical
} );```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/reveal.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/theme/simple.css" id="theme">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/theme/moon.css">

<div class="reveal">
   <div class="slides">
    <section>Slide 1</section>
    <section>Slide 2</section>
        <section>
          <section>Slide 3</section>
          <section>Slide 3.1</section>
          <section>Slide 3.2</section>
          <section>Slide 3.3</section>
        </section>
        <section>Slide 4</section>
        <section>
          <section>Slide 5</section>
          <section>Slide 5.1</section>
          <section>Slide 5.2</section>

        </section>

        <section>Slide 6</section>
   </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.js"></script>
<script src="https://cdn.jsdelivr.net/reveal.js/3.0.0"></script></code>```

Body:
Sorry for the late answer, but hope that this answer could help somebody in the future.

You can use the reveal.js API to achieve that.

Simply use the call to Reveal.slide function after the 'ready' event is called.

Reveal.slide( indexh, indexv, indexf );

Reveal.initialize();
Reveal.addEventListener( 'ready', function( event ) {
  Reveal.slide(2, 1); //go to slide horizontal / vertical
} );

<link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/reveal.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/theme/simple.css" id="theme">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/reveal.js/3.0.0/css/theme/moon.css">

<div class="reveal">
   <div class="slides">
    <section>Slide 1</section>
    <section>Slide 2</section>
        <section>
          <section>Slide 3</section>
          <section>Slide 3.1</section>
          <section>Slide 3.2</section>
          <section>Slide 3.3</section>
        </section>
        <section>Slide 4</section>
        <section>
          <section>Slide 5</section>
          <section>Slide 5.1</section>
          <section>Slide 5.2</section>

        </section>

        <section>Slide 6</section>
   </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/headjs/1.0.3/head.js"></script>
<script src="https://cdn.jsdelivr.net/reveal.js/3.0.0"></script>


问:
How to get a coordinator (x, y) from specific letter in PDF using iTextSharp?
I'm working with PDF and using iTexhSharp. So far, I could get data from a specific area already. But, I would like to make more flexible by make a it find the coordinator of the first letter(or number) of desired word and then from that coordinator make rectangle to crop around desired word. It would be good if anyone can give me a short example. Thank you.</p>

答:
The basic idea here is to use IEventListener to get notified of TextRenderInfo events. Then split these into CharacterRenderInfo, and then ask for the bounding box of each of those.

```<code>class CharacterRenderInfoGetter implements IEventListener {

    private List<CharacterRenderInfo> characterRenderInfoList = new ArrayList<>();

    @Override
    public void eventOccurred(IEventData iEventData, EventType eventType) {
        if(eventType == EventType.RENDER_TEXT)
        {
            TextRenderInfo tri = (TextRenderInfo) iEventData;
            for(TextRenderInfo subTri : tri.getCharacterRenderInfos())
            {
                characterRenderInfoList.add(new CharacterRenderInfo(subTri));
            }
        }
    }

    public List<CharacterRenderInfo> getCharacterRenderInfoList()
    {
        java.util.Collections.sort(characterRenderInfoList);
        return characterRenderInfoList;
    }

    @Override
    public Set<EventType> getSupportedEvents() {
        return null;
    }
}
</code>```

You can then use this class like so:

```<code>   File inputFile = getInputFiles()[0]; // provide your own implementation of course

    // create an iText PdfDocument out of the File
    PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile));

    // construct the IEventListener that will measure character distances
    CharacterRenderInfoGetter characterRenderInfoGetter = new CharacterRenderInfoGetter();
    PdfCanvasProcessor processor = new PdfCanvasProcessor(characterRenderInfoGetter);

    /* Here we explicitly tell the IEventListener to process page 1 (the first page of the document
     * you can loop over all pages if you want to repeat this
     */
    processor.processPageContent(pdfDocument.getPage(1));
</code>```

I know this code is written in Java. But the .NET equivalent should be very similar. At the very least it's good pseudo-code.

Body:
The basic idea here is to use IEventListener to get notified of TextRenderInfo events. Then split these into CharacterRenderInfo, and then ask for the bounding box of each of those.

class CharacterRenderInfoGetter implements IEventListener {

    private List<CharacterRenderInfo> characterRenderInfoList = new ArrayList<>();

    @Override
    public void eventOccurred(IEventData iEventData, EventType eventType) {
        if(eventType == EventType.RENDER_TEXT)
        {
            TextRenderInfo tri = (TextRenderInfo) iEventData;
            for(TextRenderInfo subTri : tri.getCharacterRenderInfos())
            {
                characterRenderInfoList.add(new CharacterRenderInfo(subTri));
            }
        }
    }

    public List<CharacterRenderInfo> getCharacterRenderInfoList()
    {
        java.util.Collections.sort(characterRenderInfoList);
        return characterRenderInfoList;
    }

    @Override
    public Set<EventType> getSupportedEvents() {
        return null;
    }
}

You can then use this class like so:

   File inputFile = getInputFiles()[0]; // provide your own implementation of course

    // create an iText PdfDocument out of the File
    PdfDocument pdfDocument = new PdfDocument(new PdfReader(inputFile));

    // construct the IEventListener that will measure character distances
    CharacterRenderInfoGetter characterRenderInfoGetter = new CharacterRenderInfoGetter();
    PdfCanvasProcessor processor = new PdfCanvasProcessor(characterRenderInfoGetter);

    /* Here we explicitly tell the IEventListener to process page 1 (the first page of the document
     * you can loop over all pages if you want to repeat this
     */
    processor.processPageContent(pdfDocument.getPage(1));

I know this code is written in Java. But the .NET equivalent should be very similar. At the very least it's good pseudo-code.


问:
update database date values format using MY-SQL
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

```<code>UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');
</code>```

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!

答:
STR_TO_DATE should work, assuming you have the same format that you specify.

Assuming a basic table as specified below:

```<code>CREATE TABLE
Demo
(
date VARCHAR(10)
);

INSERT INTO `Demo` (`date`) VALUES ('30-05-2016');
</code>```

You can obviously select itself, but you can also format it in whichever format serves your purpose using the DATE_FORMAT function.

```<code>SELECT
  `date` AS `OriginalFormat`,
  STR_TO_DATE(`date`, '%d-%m-%Y') AS `DateFormat`,
  DATE_FORMAT(STR_TO_DATE(`date`, '%d-%m-%Y'), '%m-%d-%Y') AS `CustomFormat`
FROM
  `Demo`
</code>```

Returns:

```<code>OriginalFormat | DateFormat | CustomFormat
-------------------------------------------
30-05-2016     | 2016-05-30 | 05-30-2016
</code>```

SQLFiddle: http://sqlfiddle.com/#!9/85c27c/3

Body:
i have date stored in database on date column in dd-mm-yyyy format. This column data type is VARCHAR. i wanted to convert those stored dates in yyy-mm-dd format. i tried using this MYSQL query:

UPDATE status SET new_time_creation = STR_TO_DATE(date, '%Y-%m-%d');

but this does not convert the dates properly (eg. 30-05-2016 => 2030-05-20).
please help me with this query or suggest best on even using php to update the date format. Thanks!

Body:
STR_TO_DATE should work, assuming you have the same format that you specify.

Assuming a basic table as specified below:

CREATE TABLE
Demo
(
date VARCHAR(10)
);

INSERT INTO `Demo` (`date`) VALUES ('30-05-2016');

You can obviously select itself, but you can also format it in whichever format serves your purpose using the DATE_FORMAT function.

SELECT
  `date` AS `OriginalFormat`,
  STR_TO_DATE(`date`, '%d-%m-%Y') AS `DateFormat`,
  DATE_FORMAT(STR_TO_DATE(`date`, '%d-%m-%Y'), '%m-%d-%Y') AS `CustomFormat`
FROM
  `Demo`

Returns:

OriginalFormat | DateFormat | CustomFormat
-------------------------------------------
30-05-2016     | 2016-05-30 | 05-30-2016

SQLFiddle: http://sqlfiddle.com/#!9/85c27c/3


问:
What are the differences between Amazon Redshift and the new AWS Glue datawarehousing services?
I am confused about these two services. It looks that they are offering the same service. Probably the only difference is that the Glue catalog can contain a wider range of data sources. Does it mean that AWS Glue can replace Redshift?</p>

答:
The Comment is right , These two services are not same AWS Glue is ETL Service while AWS Redshift is Data Warehousing service.

According to AWS Documentation :

Amazon Redshift is a fast, fully managed, petabyte-scale data warehouse service that makes it simple and cost-effective to efficiently analyze all your data using your existing business intelligence tools. It allows you to run complex analytic queries against petabytes of structured data, using sophisticated query optimization, columnar storage on high-performance local disks, and massively parallel query execution.

According to AWS Documentation :

AWS Glue is a fully managed ETL (extract, transform, and load) service that makes it simple and cost-effective to categorize your data, clean it, enrich it, and move it reliably between various data stores

You can Refer the Documentation Provided by AWS for Details but essentially these are totally different services.


问:
PHP proxy/mirroring script
I'm looking for a way to use PHP and possibly .htaccess to create a proxy that would essentially create a "dynamic mirror" of one site.

Example:
http://myawesome.proxy/questions/ask would fetch https://stackoverflow.com/questions/ask and return it to the browser with absolute URLs properly rewritten. Then I could log in and submit a question through that proxy.

What is the best way to do this?

答:
Have a look at http://code.google.com/p/php5rp/

It's a reverse proxy written in PHP5 using cURL.

Title: PHP proxy/mirroring script


问:
Drawing outside a UICollectionViewCell's bounds when using a UICollectionViewFlowLayout
Has anyone been able to draw outside the bounds of a UICollectionViewCell without the cell clipping to its bounds?  I have a vanilla collection view that uses a UICollectionViewFlowLayout (horizontal) and I would like to be able to draw a path outside the bounds of the UICollectionViewCell without disrupting any of the layout provided by UICollectionViewFlowLayout. Setting clipsToBounds to NO does not seem to do the trick.

答:
For me using maskToBounds did the job </p>

```<code>   override func awakeFromNib() {
    super.awakeFromNib()
    self.layer.masksToBounds = false
   }
</code>```

Body:
For me using maskToBounds did the job

   override func awakeFromNib() {
    super.awakeFromNib()
    self.layer.masksToBounds = false
   }


问:
Installing python 3.6.3 using chef on Ubunbu 16.04
I'm trying to install python 3.6.3 on Ubuntu 16.04 using chef cookbooks poise-python and seem to be going aroud in circles. I've tried various differnet methods using the docs but none seem to work.

I've trid adding these after including the recipe

```<code>python_runtime '3.6.3'

python_runtime '3' do
options version: '3.6'
end
</code>```

I've tried these in the attributes.

```<code>node.default['poise-python']['poise_python_version'] = '3.6.3'
node.default['poise-python']['version'] = '3.6.3'
</code>```

I've tried to install the version I want i na virtual enviroment

```<code>python_virtualenv '/opt/myapp' do
group "group"
python '3.6.3'
action :create
end
</code>```

Any suggestions on how best to install the version of python I require?

答:
Unfortunately there is no Python 3.6 package for Ubuntu 16.04 by default, they only offer 2.7 and 3.5. You can set up the Deadsnakes PPA and then do something like this:</p>

```<code>python_runtime '3.6' do
  provider :system # This is already the default on Ubuntu but restating for clarity
  options package_name: 'python3.6'
end
</code>```

Body:
I'm trying to install python 3.6.3 on Ubuntu 16.04 using chef cookbooks poise-python and seem to be going aroud in circles. I've tried various differnet methods using the docs but none seem to work.

I've trid adding these after including the recipe

python_runtime '3.6.3'

python_runtime '3' do
options version: '3.6'
end

I've tried these in the attributes.

node.default['poise-python']['poise_python_version'] = '3.6.3'
node.default['poise-python']['version'] = '3.6.3'

I've tried to install the version I want i na virtual enviroment

python_virtualenv '/opt/myapp' do
group "group"
python '3.6.3'
action :create
end

Any suggestions on how best to install the version of python I require?

Body:
Unfortunately there is no Python 3.6 package for Ubuntu 16.04 by default, they only offer 2.7 and 3.5. You can set up the Deadsnakes PPA and then do something like this:

python_runtime '3.6' do
  provider :system # This is already the default on Ubuntu but restating for clarity
  options package_name: 'python3.6'
end


问:
How to turn off the alarm?
My App goes like this:

When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.

When you tap the Start button, the "service" is started.

Now if you remove the AC charger you will hear an alarm sound.

Connecting the AC with the device again should stop the alarm but it does NOT.

Now removing the AC again starts another alarm. The alarms overlap.

Can you help me find the bug?

Thanks

My work so far:

AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/antitheft"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/antitheft"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name=".PowerConnectionReceiver">

        </receiver>

    </application>

</manifest>
</code>```

MainActivity.java

```<code>public class MainActivity extends AppCompatActivity {

    Button startServiceButton;
    PowerConnectionReceiver powerConnectionReceiver;
    BroadcastReceiver powerDisconnectedBroadcastReceiver;
    BroadcastReceiver powerConnectedBroadcastReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        powerConnectionReceiver = new PowerConnectionReceiver(true);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);

        powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
        powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerDisconnectedBroadcastReceiver);
                    unregisterReceiver(powerConnectedBroadcastReceiver);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                    startServiceButton.setActivated(false);
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {

        IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
        registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);

        IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
        registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);

        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
        startServiceButton.setActivated(true);
    }

}
</code>```

PowerConnectionReceiver.java

```<code>public class PowerConnectionReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer = new MediaPlayer();

    // Determine whether the AC is disconnected or not
    private boolean POWER_DISCONNECTED = true;

    PowerConnectionReceiver(boolean disconnected) {
        this.POWER_DISCONNECTED = disconnected;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (POWER_DISCONNECTED) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            //POWER_DISCONNECTED = false;
        } else {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
</code>```

答:
The bug is in your complex code.

You register two different instances of PowerConnectionReceiver one for "connected" and another for "disconnected" events. So MediaPlayer is started in "connected" receiver, and you try to stop MediaPlayer in "disconected", but it doesn't play.

You should remove POWER_DISCONNECTED field, and handle event in a single instance of receiver. You can register a single receiver for multiple events and use intent.getAction() to check how to handle it.

UPD

Also you can make your receiver singleton, to prevent multiple registrations, and playing of multiple MediaPlayers

Title: How to turn off the alarm?

Body:
My App goes like this:

When you first start the app, you'll see a button. Connecting or disconnecting the AC charger doesn't affect anything until you hit that Start button.

When you tap the Start button, the "service" is started.

Now if you remove the AC charger you will hear an alarm sound.

Connecting the AC with the device again should stop the alarm but it does NOT.

Now removing the AC again starts another alarm. The alarms overlap.

Can you help me find the bug?

Thanks

My work so far:

AndroidManifest.xml

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/antitheft"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/antitheft"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        <receiver android:name=".PowerConnectionReceiver">

        </receiver>

    </application>

</manifest>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    Button startServiceButton;
    PowerConnectionReceiver powerConnectionReceiver;
    BroadcastReceiver powerDisconnectedBroadcastReceiver;
    BroadcastReceiver powerConnectedBroadcastReceiver;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        powerConnectionReceiver = new PowerConnectionReceiver(true);
        startServiceButton = (ToggleButton) findViewById(R.id.startServiceButton);

        powerDisconnectedBroadcastReceiver = new PowerConnectionReceiver(true);
        powerConnectedBroadcastReceiver = new PowerConnectionReceiver(false);

        startServiceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (startServiceButton.isActivated()) {
                    unregisterReceiver(powerDisconnectedBroadcastReceiver);
                    unregisterReceiver(powerConnectedBroadcastReceiver);
                    Toast.makeText(MainActivity.this, "Service stopped", Toast.LENGTH_SHORT).show();
                    startServiceButton.setActivated(false);
                } else {
                    monitorBatteryChanges();
                }
            }
        });
    }

    private void monitorBatteryChanges() {

        IntentFilter powerDisconnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_DISCONNECTED");
        registerReceiver(powerDisconnectedBroadcastReceiver, powerDisconnectedIntentFilter);

        IntentFilter powerConnectedIntentFilter = new IntentFilter("android.intent.action.ACTION_POWER_CONNECTED");
        registerReceiver(powerConnectedBroadcastReceiver, powerConnectedIntentFilter);

        Toast.makeText(MainActivity.this, "Service started", Toast.LENGTH_SHORT).show();
        startServiceButton.setActivated(true);
    }

}

PowerConnectionReceiver.java

public class PowerConnectionReceiver extends BroadcastReceiver {

    MediaPlayer mediaPlayer = new MediaPlayer();

    // Determine whether the AC is disconnected or not
    private boolean POWER_DISCONNECTED = true;

    PowerConnectionReceiver(boolean disconnected) {
        this.POWER_DISCONNECTED = disconnected;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (POWER_DISCONNECTED) {
            mediaPlayer = MediaPlayer.create(context, R.raw.alarm_2);
            Toast.makeText(context, "Alarm started", Toast.LENGTH_SHORT).show();
            mediaPlayer.start();
            mediaPlayer.setLooping(true);
            //POWER_DISCONNECTED = false;
        } else {
            try {
                if (mediaPlayer.isPlaying()) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    Toast.makeText(context, "Alarm stopped", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}


答:
You could use Array.from() instead.

let App = () => {
  return
{Array.from(Array(10), (e, i) => {
    return
{i}

  })}

}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

You can also use ES6 spread syntax with map() method.

let App = () => {
  return
{[...Array(10)].map((e, i) => {
    return
{i}

  })}

}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div></code>```

Body:
I need to be able to loop over a number and return some jsx. For example

 {for(i =0; i < 10; i++){
   return
{i}

 }}

This is not exactly what I want to do, but if I can solve this then I should be able to complete what I need to do. This however returns expression expected on the for. I have done some research and people say you can't use for loops inside of jsx because they do not return anything.

How do I go about looping over a number to return some amount of jsx?

Body:
You could use Array.from() instead.

let App = () => {
  return <ul>{Array.from(Array(10), (e, i) => {
    return <li key={i}>{i}</li>
  })}</ul>
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>

You can also use ES6 spread syntax with map() method.

let App = () => {
  return <ul>{[...Array(10)].map((e, i) => {
    return <li key={i}>{i}</li>
  })}</ul>
}

ReactDOM.render(
  <App />,
  document.getElementById('app')
);

<script src="https://unpkg.com/react@16.1.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.1.0/umd/react-dom.development.js"></script>
<div id="app"></div>


问:
Why does Java have transient fields?
Why does Java have transient fields?

答:
Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.

In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.

```<code>public abstract class BaseJob implements Serializable{
   public void ShouldRetryRun(){}
}

public class SyncOrganizationJob extends BaseJob {

   public String organizationName;
   public Boolean isSynced

   @Inject transient RemoteDataSource remoteDataSource;
   @Inject transient LocalDaoSource localDataSource;

   public SyncOrganizationJob(String organizationName) {
     super(new
         Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());

      this.organizationName = organizationName;
      this.isSynced=isSynced;

   }
}
</code>```

Title: Why does Java have transient fields?

Body: Why does Java have transient fields?

Body:
Simply put, the transient java keyword protect fields from the been Serialize as their non-transient fields counter parts.

In this code snippet our abstract class BaseJob implement Serializable interface, we extends from BaseJob but we need not serialize the remote and local data sources; serialize only organizationName and isSynced fields.

public abstract class BaseJob implements Serializable{
   public void ShouldRetryRun(){}
}

public class SyncOrganizationJob extends BaseJob {

   public String organizationName;
   public Boolean isSynced

   @Inject transient RemoteDataSource remoteDataSource;
   @Inject transient LocalDaoSource localDataSource;

   public SyncOrganizationJob(String organizationName) {
     super(new
         Params(BACKGROUND).groupBy(GROUP).requireNetwork().persist());

      this.organizationName = organizationName;
      this.isSynced=isSynced;

   }
}


问:
Ansible with Windows Server 2012 and SQL Server 2014
I actually posted this question on superUser but I think it might be in the wrong place. My apologies.

I've been playing around with ansible and with WinRM to manage windows servers and have been slightly successful with it to run basic commands.

However when i try to run an exe file from within the powershell script, it fails.

The same powershell script when i run from windows directly, it runs perfectly without any errors. The only error it throws out is an Access Denied error which would link to permissions, however being the Administrator, it should have full permissions no?

The powershell script i try to run is:

```<code>Write-Host "Installing SQL Server"
C:\software-downloads\SQL\setup.exe /ConfigurationFile=C:\software-downloads\ConfigurationFile.ini
</code>```

The error Ansible throws out is:

```<code>The following error occurred:
There was an error generating the XML document.
Error result: -2068774911
Result facility code: 1201
Result error code: 1
Please review the summary.txt log for further details
</code>```

And looking at the summary log file it shows:

```<code>Overall summary:
  Final result:                  Failed: see details below
  Exit code (Decimal):           -2068774911
  Exit facility code:            1201
  Exit error code:               1
  Exit message:                  There was an error generating the XML document.
  Start time:                    2016-06-24 06:47:55
  End time:                      2016-06-24 06:48:15
  Requested action:              Install
  Exception help link:           http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.4100.1&EvtType=0xE0C083E6%400xF80B8030&EvtType=0xE0C083E6%400xF80B8030

Exception summary:
The following is an exception stack listing the exceptions in outermost to innermost order
Inner exceptions are being indented

Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
    Message:
        There was an error generating the XML document.
    HResult : 0x84b10001
        FacilityCode : 1201 (4b1)
        ErrorCode : 1 (0001)
    Data:
      DisableWatson = true
    Stack:
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(Object objectToSerialize)
        at Microsoft.SqlServer.Chainer.Infrastructure.InputSettingService.CalculateSettings(IEnumerable`1 settingIds)
        at Microsoft.SqlServer.Chainer.Infrastructure.InputSettingService.CalculateAllSettings(Boolean chainerSettingOnly)
        at Microsoft.SqlServer.Configuration.SetupExtension.FinalCalculateSettingsAction.ExecuteAction(String actionId)
        at Microsoft.SqlServer.Chainer.Infrastructure.Action.Execute(String actionId, TextWriter errorStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.<>c__DisplayClasse.<ExecuteActionWithRetryHelper>b__b()
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.ExecuteActionHelper(ActionWorker workerDelegate)
    Inner exception type: System.InvalidOperationException
        Message:
                There was an error generating the XML document.
        HResult : 0x80131509
        Stack:
                at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
                at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        Inner exception type: System.Security.Cryptography.CryptographicException
            Message:
                        Access is denied.

            HResult : 0x80070005
            Stack:
                        at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
                        at Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
                        at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String n, String ns, AgentConfigurationPublic o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object o)
</code>```

The exception help link doesn't go anywhere either when I click on it.

I tried passing the credentials as well with Start-Process but that doesn't work either as I'm probably using it wrong since i have to pass the configuration file in as a parameter.

I've run the following ansible script on the Windows Host: https://github.com/ansible/ansible/blob/devel/examples/scripts/ConfigureRemotingForAnsible.ps1

And I know it's working fine as I can run other scripts which include, downloading files from S3 and auto-joining to a domain.

Has anyone successfully installed an exe file in windows via ansible? Any help will awesome, as maybe I might even have over-looked something simple?

答:
I think the issue and solution is captured within this page: https://github.com/ansible/ansible/issues/22660

It's all to do with "multi-hop".

It may depend on how you are authenticating to the Windows hosts, the link above suggested using CredSSP, although says Kerberos may also work.

Body:
I actually posted this question on superUser but I think it might be in the wrong place. My apologies.

I've been playing around with ansible and with WinRM to manage windows servers and have been slightly successful with it to run basic commands.

However when i try to run an exe file from within the powershell script, it fails.

The same powershell script when i run from windows directly, it runs perfectly without any errors. The only error it throws out is an Access Denied error which would link to permissions, however being the Administrator, it should have full permissions no?

The powershell script i try to run is:

Write-Host "Installing SQL Server"
C:\software-downloads\SQL\setup.exe /ConfigurationFile=C:\software-downloads\ConfigurationFile.ini

The error Ansible throws out is:

The following error occurred:
There was an error generating the XML document.
Error result: -2068774911
Result facility code: 1201
Result error code: 1
Please review the summary.txt log for further details

And looking at the summary log file it shows:

Overall summary:
  Final result:                  Failed: see details below
  Exit code (Decimal):           -2068774911
  Exit facility code:            1201
  Exit error code:               1
  Exit message:                  There was an error generating the XML document.
  Start time:                    2016-06-24 06:47:55
  End time:                      2016-06-24 06:48:15
  Requested action:              Install
  Exception help link:           http://go.microsoft.com/fwlink?LinkId=20476&ProdName=Microsoft+SQL+Server&EvtSrc=setup.rll&EvtID=50000&ProdVer=12.0.4100.1&EvtType=0xE0C083E6%400xF80B8030&EvtType=0xE0C083E6%400xF80B8030

Exception summary:
The following is an exception stack listing the exceptions in outermost to innermost order
Inner exceptions are being indented

Exception type: Microsoft.SqlServer.Chainer.Infrastructure.ChainerInfrastructureException
    Message:
        There was an error generating the XML document.
    HResult : 0x84b10001
        FacilityCode : 1201 (4b1)
        ErrorCode : 1 (0001)
    Data:
      DisableWatson = true
    Stack:
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(Object objectToSerialize)
        at Microsoft.SqlServer.Chainer.Infrastructure.InputSettingService.CalculateSettings(IEnumerable`1 settingIds)
        at Microsoft.SqlServer.Chainer.Infrastructure.InputSettingService.CalculateAllSettings(Boolean chainerSettingOnly)
        at Microsoft.SqlServer.Configuration.SetupExtension.FinalCalculateSettingsAction.ExecuteAction(String actionId)
        at Microsoft.SqlServer.Chainer.Infrastructure.Action.Execute(String actionId, TextWriter errorStream)
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.<>c__DisplayClasse.<ExecuteActionWithRetryHelper>b__b()
        at Microsoft.SqlServer.Setup.Chainer.Workflow.ActionInvocation.ExecuteActionHelper(ActionWorker workerDelegate)
    Inner exception type: System.InvalidOperationException
        Message:
                There was an error generating the XML document.
        HResult : 0x80131509
        Stack:
                at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
                at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
                at Microsoft.SqlServer.Chainer.Infrastructure.DataStoreService.SerializeObject(String rootPath, Object objectToSerialize, Boolean saveToCache)
        Inner exception type: System.Security.Cryptography.CryptographicException
            Message:
                        Access is denied.

            HResult : 0x80070005
            Stack:
                        at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData, Byte[] optionalEntropy, DataProtectionScope scope)
                        at Microsoft.SqlServer.Common.SqlSecureString.WriteXml(XmlWriter writer)
                        at System.Xml.Serialization.XmlSerializationWriter.WriteSerializable(IXmlSerializable serializable, String name, String ns, Boolean isNullable, Boolean wrapped)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write6_AgentConfigurationPublic(String n, String ns, AgentConfigurationPublic o, Boolean isNullable, Boolean needType)
                        at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterAgentConfigurationPublic.Write7_AgentConfigurationPublic(Object o)

The exception help link doesn't go anywhere either when I click on it.

I tried passing the credentials as well with Start-Process but that doesn't work either as I'm probably using it wrong since i have to pass the configuration file in as a parameter.

I've run the following ansible script on the Windows Host: https://github.com/ansible/ansible/blob/devel/examples/scripts/ConfigureRemotingForAnsible.ps1

And I know it's working fine as I can run other scripts which include, downloading files from S3 and auto-joining to a domain.

Has anyone successfully installed an exe file in windows via ansible? Any help will awesome, as maybe I might even have over-looked something simple?


问:
error: method onCreate(Bundle) is already defined in class MainActivity
I'm pretty new to android development. I'm aware I shouldn't use duplicate onCreate(), but I don't know how to do this than. I'm creating two spinners from sqlite database on the same layout.

My code is:

```<code>import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper datahelper = new DataHelper(this);

        datahelper.insertBreed ("Beagle");
        datahelper.insertBreed ("Bulldog");
        datahelper.insertBreed ("Chow Chow");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerBreeds);
        ArrayList<String> list = datahelper.getAllBreeds();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper2 datahelper2 = new DataHelper2(this);

        datahelper2.insertAge("1");
        datahelper2.insertAge ("2");
        datahelper2.insertAge("3");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerAge);
        ArrayList<String> list = datahelper2.getAllAge();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }
}
</code>```

答:
You have two methods

```<code>protected void onCreate(Bundle savedInstanceState)
</code>```

in your code, and that is why you get the error.

You should remove one of them and put the code into the other method.

Body:
I'm pretty new to android development. I'm aware I shouldn't use duplicate onCreate(), but I don't know how to do this than. I'm creating two spinners from sqlite database on the same layout.

My code is:

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Spinner;

import java.util.ArrayList;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper datahelper = new DataHelper(this);

        datahelper.insertBreed ("Beagle");
        datahelper.insertBreed ("Bulldog");
        datahelper.insertBreed ("Chow Chow");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerBreeds);
        ArrayList<String> list = datahelper.getAllBreeds();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create DataHelper object and insert some sample data
        DataHelper2 datahelper2 = new DataHelper2(this);

        datahelper2.insertAge("1");
        datahelper2.insertAge ("2");
        datahelper2.insertAge("3");

        // Get sample data from the database and display them in the spinner
        Spinner spinner = (Spinner) findViewById(R.id.spinnerAge);
        ArrayList<String> list = datahelper2.getAllAge();
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_layout, R.id.text, list);
        spinner.setAdapter(adapter);
    }
}

Body:
You have two methods

protected void onCreate(Bundle savedInstanceState)

in your code, and that is why you get the error.

You should remove one of them and put the code into the other method.


问:
rendering texture from other class in libgdx
i am making a game in libgdx. I have a super class Monster with child classes of that monster (warrior,mage,..). I would like to render this Monster class (actually his child) in playScreen class. Each class has its own animaton and textures, damage/health values. How do i do that? In which class do i define position for rendering, animation of that monster? in child classes, super class or in playScreen?  My current code is here:

```<code>public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){

    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());

}
</code>```

Child class:

```<code>public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){

    super(health, damage, animation);

}
</code>```

PlayScreen class:

```<code>public class PlayScreen  implements Screen, InputProcessor {
private SpriteBatch batch;
public TextureAtlas atlas;
TextureRegion region;
private int height;
private Viewport viewport;
private Camera camera;
private int width;
private float elapsedTime = 0;
private Handler h;
private Stage stage;
private InputProcessor processor;

public PlayScreen(Handler h){
    this.h = h;
    batch = h.batch;
    camera = h.camera;
    viewport = h.viewport;
    height = h.height;
    width = h.width;
    region = new TextureRegion();
    stage = new Stage(viewport,batch);
    stateTime = 0f;

}
@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();

    batch.end();

}
</code>```

答:
You could make a render method in the monster and/or child class. It depends if all monsters are going to be rendered the same way, either way it is useful to make an empty render method in the monster class nonetheless (so we do not have to cast classes in future).

```<code>public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){
    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());
}

public void render(SpriteBatch batch) {
    // here you will use your animation and textureAtlas to render
}
</code>```

You then call the render method in your main render in PlayScreen, make sure to put the batch as parameter.

If you have one monster you wish to render differently, you could override the monster's render method like this:

```<code>public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){
    super(health, damage, animation);
}

@Override
public void render(SpriteBatch batch) {
    // your mage specific render
    // calling super.render(batch) will call its superclass' render
}
</code>```

I hope you know how to use your animation to actually render it now, otherwise here is a useful link. Good luck!

Body:
i am making a game in libgdx. I have a super class Monster with child classes of that monster (warrior,mage,..). I would like to render this Monster class (actually his child) in playScreen class. Each class has its own animaton and textures, damage/health values. How do i do that? In which class do i define position for rendering, animation of that monster? in child classes, super class or in playScreen?  My current code is here:

public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){

    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());

}

Child class:

public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){

    super(health, damage, animation);

}

PlayScreen class:

public class PlayScreen  implements Screen, InputProcessor {
private SpriteBatch batch;
public TextureAtlas atlas;
TextureRegion region;
private int height;
private Viewport viewport;
private Camera camera;
private int width;
private float elapsedTime = 0;
private Handler h;
private Stage stage;
private InputProcessor processor;

public PlayScreen(Handler h){
    this.h = h;
    batch = h.batch;
    camera = h.camera;
    viewport = h.viewport;
    height = h.height;
    width = h.width;
    region = new TextureRegion();
    stage = new Stage(viewport,batch);
    stateTime = 0f;

}
@Override
public void render(float delta) {

    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();

    batch.end();

}

Body:
You could make a render method in the monster and/or child class. It depends if all monsters are going to be rendered the same way, either way it is useful to make an empty render method in the monster class nonetheless (so we do not have to cast classes in future).

public class Monster {
public Animation monster;
public TextureAtlas atlas;
public int health;
public int damage;

public Monster(){
    atlas = new TextureAtlas(Gdx.files.internal("mons1.txt"));
    monster = new Animation(1/15f, atlas.getRegions());
}

public void render(SpriteBatch batch) {
    // here you will use your animation and textureAtlas to render
}

You then call the render method in your main render in PlayScreen, make sure to put the batch as parameter.

If you have one monster you wish to render differently, you could override the monster's render method like this:

public class Mage extends Monster {

public Mage(int health,int damage, Animation animation){
    super(health, damage, animation);
}

@Override
public void render(SpriteBatch batch) {
    // your mage specific render
    // calling super.render(batch) will call its superclass' render
}

I hope you know how to use your animation to actually render it now, otherwise here is a useful link. Good luck!


问:
PHP Variables - opposite strings
I have a single variable $width that can be a string with any one of these values:

shortest, short, half, long, longest

In my template, I want to create 2 elements - one that has the original value of $width and one that has an opposite width:

short is opposite of long and vice-versa

shortest is opposite of longest and vice-versa

half is opposite of half

This is my code which is working exactly as I want it, but it feels a little repetitive and dirty to me, so I was wondering if a cleaner/smarter PHP syntax exists to store the opposite string pairs and refactor/shorten the code or is that as lean as it can get?

```<code><?
// Possible values - shortest, short, half, long, longest
$width = '';

if ($width == 'shortest') {
    $opposite_width = 'longest';
}
if ($width == 'short') {
    $opposite_width = 'long';
}
if ($width == 'half') {
    $opposite_width = 'half';
}
if ($width == 'long') {
    $opposite_width = 'short';
}
if ($width == 'longest') {
    $opposite_width = 'shortest';
}

?>

<div class="<?= width ?>"></div>
<div class="<?= opposite_width ?>"></div>
</code>```

Thank you.

答:
Here is one method without array mapping:

```<code>// Possible values - shortest, short, half, long, longest

function opposite($width) {
    $widths = array('shortest', 'short', 'half', 'long', 'longest');
    $widthCount = count($widths) - 1;
    $position = array_search($width, $widths);
    $newPosition = $widthCount - $position;
    $oppositePosition = $widths[$newPosition];
    return $oppositePosition;
}

echo opposite('half'); // 'half'
</code>```

Taking a count of the array I don't have to worry about making a map, which means I can add to the array without having to modify the function. This could be further modified by passing in both the needle and the haystack, which means the function can work with multiple datasets (of any size array) without modification.

```<code>function opposite($width, $oppositeOf) {
    $widthCount = count($oppositeOf) - 1;
    $position = array_search($width, $oppositeOf);
    $newPosition = $widthCount - $position;
    $oppositePosition = $oppositeOf[$newPosition];
    return $oppositePosition;
}

$widths = array('shortest', 'short', 'half', 'long', 'longest');
echo opposite('long', $widths); // 'short'

$sizes = array('skinnier', 'skinny', 'average', 'above average', 'hefty', 'heftier');
echo opposite('above average', $sizes); // 'average'
</code>```

Title: PHP Variables - opposite strings

Body:
I have a single variable $width that can be a string with any one of these values:

shortest, short, half, long, longest

In my template, I want to create 2 elements - one that has the original value of $width and one that has an opposite width:

short is opposite of long and vice-versa

shortest is opposite of longest and vice-versa

half is opposite of half

This is my code which is working exactly as I want it, but it feels a little repetitive and dirty to me, so I was wondering if a cleaner/smarter PHP syntax exists to store the opposite string pairs and refactor/shorten the code or is that as lean as it can get?

<?
// Possible values - shortest, short, half, long, longest
$width = '';

if ($width == 'shortest') {
    $opposite_width = 'longest';
}
if ($width == 'short') {
    $opposite_width = 'long';
}
if ($width == 'half') {
    $opposite_width = 'half';
}
if ($width == 'long') {
    $opposite_width = 'short';
}
if ($width == 'longest') {
    $opposite_width = 'shortest';
}

?>

<div class="<?= width ?>">

<div class="<?= opposite_width ?>">

Thank you.

Body:
Here is one method without array mapping:

// Possible values - shortest, short, half, long, longest

function opposite($width) {
    $widths = array('shortest', 'short', 'half', 'long', 'longest');
    $widthCount = count($widths) - 1;
    $position = array_search($width, $widths);
    $newPosition = $widthCount - $position;
    $oppositePosition = $widths[$newPosition];
    return $oppositePosition;
}

echo opposite('half'); // 'half'

Taking a count of the array I don't have to worry about making a map, which means I can add to the array without having to modify the function. This could be further modified by passing in both the needle and the haystack, which means the function can work with multiple datasets (of any size array) without modification.

function opposite($width, $oppositeOf) {
    $widthCount = count($oppositeOf) - 1;
    $position = array_search($width, $oppositeOf);
    $newPosition = $widthCount - $position;
    $oppositePosition = $oppositeOf[$newPosition];
    return $oppositePosition;
}

$widths = array('shortest', 'short', 'half', 'long', 'longest');
echo opposite('long', $widths); // 'short'

$sizes = array('skinnier', 'skinny', 'average', 'above average', 'hefty', 'heftier');
echo opposite('above average', $sizes); // 'average'


问:
How to put a dot after three digits of a number
do you know how can i put a dot (.) after 3 digits of a number(starting from the end) in php?
example: the number 1254631 to be shown as 1.254.631??</p>

答:
```<code>$printThisNumber = number_format($getThisNumber, 2, '.', ',');
</code>```


问:
Insert text into textarea with jQuery
I'm wondering how I can insert text into a text area using jquery, upon the click of an anchor tag.

I don't want to replace text already in textarea, I want to append new text to textarea.

答:
```<code>$.fn.extend({
    insertAtCaret: function(myValue) {
        var elemSelected = window.getSelection();
        if(elemSelected) {
            var startPos = elemSelected.getRangeAt(0).startOffset;
            var endPos = elemSelected.getRangeAt(0).endOffset;
            this.val(this.val().substring(0, startPos)+myValue+this.val().substring(endPos,this.val().length));
        } else {
            this.val(this.val()+ myValue) ;
        }
    }
});
</code>```

Title: Insert text into textarea with jQuery


问:
Change color of android.support.v7.widget.SearchView
I am using search view.

```<code>  <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/imageViewMenu"
            >
  </android.support.v7.widget.SearchView>
</code>```

Is this possible to change text color and icon color to view?

Currently it shows black text and icon. I want to change it to white color text and white search icon.

答:
```<code><style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" >
    <item name="colorControlHighlight">@color/LightGray</item>
    <item name="android:textColorHint">@color/LightGray</item>
    <item name="android:editTextColor">@color/TransparentGray</item>
</style>
</code>```

apply this theme to your toolbar hint that (colorControlHighlight) color of ripple effct of your menu items

Body:
I am using search view.

  <android.support.v7.widget.SearchView
            android:id="@+id/searchView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/imageViewMenu"
            >
  </android.support.v7.widget.SearchView>

Is this possible to change text color and icon color to view?

Currently it shows black text and icon. I want to change it to white color text and white search icon.

Body:
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" >
    <item name="colorControlHighlight">@color/LightGray</item>
    <item name="android:textColorHint">@color/LightGray</item>
    <item name="android:editTextColor">@color/TransparentGray</item>
</style>

apply this theme to your toolbar hint that (colorControlHighlight) color of ripple effct of your menu items


问:
Showing the soft keyboard for SearchView on ActionBar
We've got a SearchView on the ActionBar which is set to be non-iconified. As we don't have any content in the view until the user's entered something to search for, it would make sense to give the SearchView initial focus, and make sure the soft keyboard is showing ready for the user to enter text — otherwise they'll always have to first tap in the SearchView.

I can give the SearchView focus by just calling

```<code>searchView.requestFocus();
</code>```

but I can't get the soft keyboard to appear. In another one of our Fragments I have an EditText which we want to be focused I can get the soft keyboard to appear there by calling

```<code>InputMethodManager mgr = (InputMethodManager)getActivity().getSystemService(
            Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
</code>```

but this just doesn't work on the SearchView. It must surely be possible to get this to work.

答:
I have a similar problem where none of the proposed solutions here worked. Some just didn't make the keyboard appear at all and some show a keyboard but the key presses there just do not work.

The only thing that worked was:

```<code>                    // hack for making the keyboard appear
                    searchView.setIconified(true);
                    searchView.setIconified(false);
</code>```

Body:
We've got a SearchView on the ActionBar which is set to be non-iconified. As we don't have any content in the view until the user's entered something to search for, it would make sense to give the SearchView initial focus, and make sure the soft keyboard is showing ready for the user to enter text — otherwise they'll always have to first tap in the SearchView.

I can give the SearchView focus by just calling

searchView.requestFocus();

but I can't get the soft keyboard to appear. In another one of our Fragments I have an EditText which we want to be focused I can get the soft keyboard to appear there by calling

InputMethodManager mgr = (InputMethodManager)getActivity().getSystemService(
            Context.INPUT_METHOD_SERVICE);
mgr.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

but this just doesn't work on the SearchView. It must surely be possible to get this to work.

Body:
I have a similar problem where none of the proposed solutions here worked. Some just didn't make the keyboard appear at all and some show a keyboard but the key presses there just do not work.

The only thing that worked was:

                    // hack for making the keyboard appear
                    searchView.setIconified(true);
                    searchView.setIconified(false);


问:
Compatible DDL (CREATE TABLE) across different SQL databases?
I'm working on a desktop application that must support (currently) MS Access and SQL Server back ends.  The application is under constant development and changes are frequently being made to the database, mostly the addition of tables and views to support new features (but also some DROPs and ALTER TABLEs to add new columns).

I have a system that compiles the DDL into the executable, checks the database to see if the executable has any new DDL that has to be executed, and executes it.  This works fine for a single database.

My immediate problem is that SQL Server and Access support wildly different names for data types so a CREATE TABLE statement that executes against Access will not execute against SQL Server (or worse, will execute but create a table with different datatypes).

Is there a method that can be used to create DDL (especially CREATE TABLE commands) that can be executed through ADO against both of these databases without having to craft separate DDL for each provider?

答:
This can be done using DBX in Delphi.

The following is links to sample code showing how this can be done.
http://cc.embarcadero.com/item/26210


Title: How to compare two columns in csv with two values declared before in python?

Body:
the catalog there this values:

0.6881  -55.0099
0.6883  -80.3465
0.7827  -59.5199
0.8206  -54.5565
0.8418  -49.7932
0.9503  -43.6182
1.0236  -52.9165
1.0488  -50.6465
1.1068  -50.6182
1.134   -32.2499
1.1325  -45.4482
1.2633  -27.7416
1.2725  -50.8282
1.3115  -40.6049
1.3461  -30.5649
...
...

and my values declared before is ra = 59.6517601 dec = 61.5475502. How compare to show if there values ra, dec in my catalog?

Body:
First create the catalogue in python:

l = '0.6881 -55.0099 0.6883 -80.3465 0.7827 -59.5199 0.8206 -54.5565 0.8418 -49.7932 0.9503 -43.6182 1.0236 -52.9165 1.0488 -50.6465 1.1068 -50.6182 1.134 -32.2499 1.1325 -45.4482 1.2633 -27.7416 1.2725 -50.8282 1.3115 -40.6049 1.3461 -30.5649'

l = l.replace(' ', ',')
l = l.split(',')
l = [float(a) for a in l]

ra = 59.6517601
dec = 61.5475502

ra in l
dec in l

Both output False, so neither ra or dec are on the list.
Imagine ra was in the list, then:

l.append(ra)
ra in l
True


问:
Fitting a function with a heavyside step function
I am trying to fit a function to a part of the following graph:

I want to find out the time the signal starts increasing exponentially. To do this I fit an exponential curve to the data, multiplied by a heavyside step function.

```<code>def fit(x, a, b, c, d, e):
    return np.heaviside(x-a, 0.5)*b*np.exp(c*x-d)+e

parameter, covariance = curve_fit(fit, fitx, fity)

x = np.linspace(min(fitx), max(fitx), 1000)
plt.plot(fitx, fity)
plt.plot(x, fit(x, *parameter), 'b-', label='fit')
plt.show()
</code>```

The result is somehow a straight line

When I fit only the exponential part I get the following graph:

I'd expect a straight line at the x-axis, followed by the exponential graph in image 2. Does anybody know where I went wrong?

答:
The most likely situation is that you have an issue with convergence of the parameters. In most cases, this convergence problem is due to bad starting points for the parameters.

Since it works as expected without the heavyside function, my guess would be that you should give a reasonable starting point for your parameter a in the curve_fit function call.

Body:
I am trying to fit a function to a part of the following graph:

I want to find out the time the signal starts increasing exponentially. To do this I fit an exponential curve to the data, multiplied by a heavyside step function.

def fit(x, a, b, c, d, e):
    return np.heaviside(x-a, 0.5)*b*np.exp(c*x-d)+e

parameter, covariance = curve_fit(fit, fitx, fity)

x = np.linspace(min(fitx), max(fitx), 1000)
plt.plot(fitx, fity)
plt.plot(x, fit(x, *parameter), 'b-', label='fit')
plt.show()

The result is somehow a straight line

When I fit only the exponential part I get the following graph:

I'd expect a straight line at the x-axis, followed by the exponential graph in image 2. Does anybody know where I went wrong?


问:
Store and call method from a HashMap
I have 2 files: ImplementationProvider and CaseHandler.

ImplementationProvider:

```<code>class ImplementationProvider {
    public void method1(Object[] params) {}
    public void method2(Object[] params) {}
    ...
    public void method100(Object[] params) {}
}
</code>```

CaseHandler:

```<code>class CaseHandler {
    ImplementationProvider ip; // auto injected
    public void handle(String s, String param) {
        switch(s) {
            case USE_CASE_ONE: ip.method1(param); break;
            case USE_CASE_TWO: ip.method2(param); break;
            ...
        }
    }
}
</code>```

How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? The main issue I'm having is the propagation of the parameters. Other answers here recommend using an interface, however I need to provide the parameter on runtime.

答:
Here's one way I can think of, using the Consumer functional interface:

```<code>Map<String,Consumer<Object[]>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, param -> ip.method1(param));
methods.put (USE_CASE_TWO, param -> ip.method2(param));
...

public void handle(String s, String param) {
    methods.get(s).accept(new Object[]{param});
}
</code>```

EDIT:

If your methods require two parameters, you can use the BiConsumer interface:

```<code>Map<String,BiConsumer<String,List<String>>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, (s,l) -> ip.method1(s,l));
methods.put (USE_CASE_TWO, (s,l) -> ip.method2(s,l));
...

public void handle(String s, String param) {
    methods.get(s).accept(someString,someListOfStrings);
}
</code>```

Title: Store and call method from a HashMap

Body:
I have 2 files: ImplementationProvider and CaseHandler.

ImplementationProvider:

class ImplementationProvider {
    public void method1(Object[] params) {}
    public void method2(Object[] params) {}
    ...
    public void method100(Object[] params) {}
}

CaseHandler:

class CaseHandler {
    ImplementationProvider ip; // auto injected
    public void handle(String s, String param) {
        switch(s) {
            case USE_CASE_ONE: ip.method1(param); break;
            case USE_CASE_TWO: ip.method2(param); break;
            ...
        }
    }
}

How can I refactor the CaseHandler so that the USE_CASE strings are keys in a HashMap where the values would be the methods? The main issue I'm having is the propagation of the parameters. Other answers here recommend using an interface, however I need to provide the parameter on runtime.

Body:
Here's one way I can think of, using the Consumer functional interface:

Map<String,Consumer<Object[]>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, param -> ip.method1(param));
methods.put (USE_CASE_TWO, param -> ip.method2(param));
...

public void handle(String s, String param) {
    methods.get(s).accept(new Object[]{param});
}

EDIT:

If your methods require two parameters, you can use the BiConsumer interface:

Map<String,BiConsumer<String,List<String>>> methods = new HashMap<>();

methods.put (USE_CASE_ONE, (s,l) -> ip.method1(s,l));
methods.put (USE_CASE_TWO, (s,l) -> ip.method2(s,l));
...

public void handle(String s, String param) {
    methods.get(s).accept(someString,someListOfStrings);
}


问:
Saltstack cmd.run - if statement and unless
I manage the installation of our workstations with Saltstack.
In my recipe for the ipa-client-automount installation on clients, I need to:

set the location based on fqdn

check if ipa-client-automount is already configured

Currently, I have the following state:

```<code> ipa-client-automount:
  cmd.run:
    {% if salt['cmd.run']('hostname -f | grep domain1') %}
    - name: ipa-client-automount --location=linkedtodomain1 -U
    {% elif salt['cmd.run']('hostname -f | grep domain2') %}
    - name: ipa-client-automount --location=linkedtodomain2 -U
    {% endif %}
    - unless: python -c "from ipapython import sysrestore; from ipaplatform.paths import paths; statestore = sysrestore.StateFile(paths.IPA_CLIENT_SYSRESTORE); exit(not statestore.has_state('autofs'))"
</code>```

The issue is that when adding the if and elif statement, it doesn't consider the unless. It runs directly the command without checking the unless condition.
Also, I'm sure that my unless statement is working, it was all fine with only one location.

How can I write this to have the if and unless working at the same time?
Thanks

答:
I have a working solution:

```<code>ipa-client-automount:
  cmd.run:
    - names:
      {% if salt['cmd.run']('hostname -f | grep domain1') %}
      - ipa-client-automount --location=linkedtodomain1 -U
      {% elif salt['cmd.run']('hostname -f | grep domain2') %}
      - ipa-client-automount --location=linkedtodomain2 -U
      {% endif %}
    - unless: condition
</code>```

It's not the cleanest solution but it worked for me. Don't know why this doesn't work on names but does on name.

Body:
I manage the installation of our workstations with Saltstack.
In my recipe for the ipa-client-automount installation on clients, I need to:

set the location based on fqdn

check if ipa-client-automount is already configured

Currently, I have the following state:

 ipa-client-automount:
  cmd.run:
    {% if salt['cmd.run']('hostname -f | grep domain1') %}
    - name: ipa-client-automount --location=linkedtodomain1 -U
    {% elif salt['cmd.run']('hostname -f | grep domain2') %}
    - name: ipa-client-automount --location=linkedtodomain2 -U
    {% endif %}
    - unless: python -c "from ipapython import sysrestore; from ipaplatform.paths import paths; statestore = sysrestore.StateFile(paths.IPA_CLIENT_SYSRESTORE); exit(not statestore.has_state('autofs'))"

The issue is that when adding the if and elif statement, it doesn't consider the unless. It runs directly the command without checking the unless condition.
Also, I'm sure that my unless statement is working, it was all fine with only one location.

How can I write this to have the if and unless working at the same time?
Thanks

Body:
I have a working solution:

ipa-client-automount:
  cmd.run:
    - names:
      {% if salt['cmd.run']('hostname -f | grep domain1') %}
      - ipa-client-automount --location=linkedtodomain1 -U
      {% elif salt['cmd.run']('hostname -f | grep domain2') %}
      - ipa-client-automount --location=linkedtodomain2 -U
      {% endif %}
    - unless: condition

It's not the cleanest solution but it worked for me. Don't know why this doesn't work on names but does on name.


问:
What is the difference between DBCC cachedataremove and sp_unbindcache?
I would like to know the difference between DBCC cachedataremove and sp_unbindcache. because in my project i got permissions for unbindingcache but not to execute DBCC cachedataremove. I was assuming that they did pretty much the same thing.

SYBASE ASE 15.7

答:
sp_unbindcache is used to unbind and object from a user-defined cache whereas dbcc cachedataremove is use to remove an object from default data cache.

You cannot bind objects to default data cache explicitly only to user-defined caches.


问:
How to retrieve a file from a server via SFTP?
I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>

答:
I found complete working example for SFTP in java using JSCH API
http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/</p>