问:
Pass test data to table-valued parameter within SQL
Is it possible, and if so how, to pass data to a table-valued parameter of a stored function using SQL EXEC?

I know how to pass in data from C#. One of my four stored procs using table-valued parameters is not producing the expected results. I'd like to execute my proc from SQL server management studio for debugging purposes, but I am unable to find the correct syntax for doing so, if such a syntax even exists. I haven't found anything relevant in the docs.

My type table:

```<code>CREATE TYPE [MyNameSpace].[MyTypeTable] AS TABLE(
//... all my fields
)
</code>```

My stored proc:

```<code>//... bunch of stuff
ALTER PROCEDURE [MyNameSpace].[MyStoredProc]
@MyTypeTableVar MyTypeTable READONLY
AS
BEGIN
//Do a bunch of stuff
//Want to test the stuff in here
END
</code>```

I have tried:

```<code>IF OBJECT_ID('tempdb.dbo.#MyTempTable') IS NOT NULL DROP TABLE tempdb.dbo.#MyTempTable;
select top 0 *
into #MyTempTable
//existing table with structure that matches the table-valued param
from MyNameSpace.MyTable;

//...Long insert statement assigning test data to #MyTempTable

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = #MyTempTable;
</code>```

which throws:

Operand type clash: nvarchar is incompatible with MyTypeTable

答:
You can't use a temp table - you have to use a table variable:

```<code>declare @t [MyNameSpace].[MyTypeTable]
insert into @t (/*columns*/) values
(/* first row */),
(/* second row */)

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = @t;
</code>```

(You can populate it with either INSERT ... VALUES as shown above or INSERT ... SELECT if you have an existing table containing the data you care about)

Body:
Is it possible, and if so how, to pass data to a table-valued parameter of a stored function using SQL EXEC?

I know how to pass in data from C#. One of my four stored procs using table-valued parameters is not producing the expected results. I'd like to execute my proc from SQL server management studio for debugging purposes, but I am unable to find the correct syntax for doing so, if such a syntax even exists. I haven't found anything relevant in the docs.

My type table:

CREATE TYPE [MyNameSpace].[MyTypeTable] AS TABLE(
//... all my fields
)

My stored proc:

//... bunch of stuff
ALTER PROCEDURE [MyNameSpace].[MyStoredProc]
@MyTypeTableVar MyTypeTable READONLY
AS
BEGIN
//Do a bunch of stuff
//Want to test the stuff in here
END

I have tried:

IF OBJECT_ID('tempdb.dbo.#MyTempTable') IS NOT NULL DROP TABLE tempdb.dbo.#MyTempTable;
select top 0 *
into #MyTempTable
//existing table with structure that matches the table-valued param
from MyNameSpace.MyTable;

//...Long insert statement assigning test data to #MyTempTable

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = #MyTempTable;

which throws:

Operand type clash: nvarchar is incompatible with MyTypeTable

Body:
You can't use a temp table - you have to use a table variable:

declare @t [MyNameSpace].[MyTypeTable]
insert into @t (/*columns*/) values
(/* first row */),
(/* second row */)

EXECUTE MyNameSpace.MyStoredProc @MyTypeTableVar = @t;

(You can populate it with either INSERT ... VALUES as shown above or INSERT ... SELECT if you have an existing table containing the data you care about)


来源: stackexchange

问:
How to keep header the same size as the window
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:</p>

```<code><header>
        <div id="adresa">
            <ul>
              <li><img name="telefon" src="Prvisajt/Rounded-16-128.png" width="20"; height="18"; align="bottom";> 011/2762-124 </li>
              <li>  <img name="adresa" src="Prvisajt/location-square-social-media-128.png" width="20"; height="18"; align="bottom";> Ruzveltova 45, 11000 Beograd, Frizerski salon Marko</li>
              <li id="mail"><a href="mailto:kontakt@frizerskisalonmarko.com"> <img src="Prvisajt/mail-square-social-media-128.png" width="20"; height="18"; align="bottom"> </a></li>
              <li id="face"><a href="https://www.facebook.com/FSM.Beograd/"> <img src="Prvisajt/Facebook_social_media_logo-128.png" width="20"; height="18"; align="bottom"> </a></li>
            </ul>
        </div>

       <div id="navbar">
        <ul>
            <li><img id="logo" src="Prvisajt/logo-alternate.png" alt="Logo"></li>
            <li><a href="galerija.html">GALERIJA</a></li>
            <li><a href="cenovnik.html">CENOVNIK</a></li>
            <li><a href="kontakt.html">KONTAKT</a></li>
        </ul>
      </div>
    </header>

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}
</code>```

答:
What you want is responsiveness if I'm not wrong, so what you need to do is
add a meta tag to you head section like this:

```<code><head>
   <meta name="viewport" content="width=device-width , initial-scale=1">
</head>
</code>```

And instead go for a responsive CSS framework like Bootstrap

ContentLicense: CC BY-SA 3.0

Body:
I am a total beginner and i have a problem with a header width (i am also not so great English speaker so i hope that i will manage to explain this good as i need to).
Header is marked in css as 100% but when i change size of the firefox or chrome window it stays with width of the monitor and i get that drag line down on the browser window.
Everything else on site follows the size of the window, only that stays big.
Also they all have position:relative.
This is the html code:

 011/2762-124

   Ruzveltova 45, 11000 Beograd, Frizerski salon Marko

GALERIJA

CENOVNIK

KONTAKT

and this is css:

body {
    margin: 0;
    padding: 0;
    background: black;
}

header {
    width: 100%;
    max-width: 100%;
    height: 120px;
    position: relative;
}

#navbar {
    width:100%;
    height:92px;
    float: right;
    background-color: black;
    position: relative;
    top: 0px;
    border-bottom: 1px solid white;

}

#navbar ul li {
    width:100px;
    float: left;
    list-style: none;
    display: inline;
    position: relative;
    left: 970px;
}

#navbar li a {
    color: white;
    line-height: 80px;
    text-align: center;
    font-size: 12px;
    font-family: sans-serif;
    font-weight: 600;
    text-decoration: none;
}

#logo {
    position: relative;
    top: -16px;
    right: 620px;
}

#adresa {
    float: left;
    display:inline;
    background-color: black;
    border-bottom: 1px solid white;
    width: 100%;
    height: 25px;
    text-align: center;
    font-size: 11px;
    font-weight: 600;
    font-family: sans-serif;
    list-style-type: none;
    text-decoration: none;
    text-align: left;
    position: relative;
    top: 0px;
}

#adresa ul li {
    list-style-type: none;
    background-color: black;
    text-align: center;
    display: inline;
    text-decoration: none;
    color: white;
    position: relative;
    top: -10px;
    left: 350px;
}

#mail img {
    position: relative;
    top: 4px;
    right: -600px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

#face img {
    position: relative;
    top: 4px;
    right: -610px;
    border-color: white;
    border-left: 1px solid white;
    border-right: 1px solid white;
}

Body:
What you want is responsiveness if I'm not wrong, so what you need to do is
add a meta tag to you head section like this:

<head>
   <meta name="viewport" content="width=device-width , initial-scale=1">
</head>

And instead go for a responsive CSS framework like Bootstrap


问:
Dynamics CRM2016: cannot read property 'SetParameter' of undefined
I've subgrid on Account form, I am trying to get list of Orders of child contact and then add to subgrid. So, far I did the following scripts but it throws error that cannot read property 'SetParameter' of undefined. Can anyone please guide how can I change fetchxml of a subgrid?

```<code>function listOfOrders(contactId){
    var orderFetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+
                    "  <entity name='salesorder'>"+
                    "    <attribute name='name' />"+
                    "    <attribute name='customerid' />"+
                    "    <attribute name='salesorderid' />"+
                    "    <attribute name='statecode' />"+
                    "    <attribute name='createdon' />"+
                    "    <order attribute='name' descending='false' />"+
                    "    <filter type='and'>"+
                    "      <condition attribute='customerid' operator='eq' uitype='contact' value='"+contactId+"' />"+
                    "    </filter>"+
                    "  </entity>"+
                    "</fetch>";

    var retrievedOrders = XrmServiceToolkit.Soap.Fetch(orderFetchXml);

        var contactId = "";
        if(retrievedOrders.length <0)
            return;

    var viewId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
    var viewDisName = "Account Orders subgridview";

     var layOutXml = "<grid name='resultset' object='1' jump='name' select='1' icon='1' preview='1'>" +
                            "<row name='result' id='salesorderid'>" +
                            "<cell name='name' width='300' />" +
                            "<cell name='statecode' />"+
                            "<cell name='createdon' />"+
                            "<cell name='customerid' />"+
                            "disableSorting='1' />" +
                            "</row>" +
                    "</grid>";
    var orderSubgrid = window.parent.document.getElementById("orderssubgrid");
    //apply layout and filtered fetchXML
    orderSubgrid.control.SetParameter("layoutXml", layOutXml);
    orderSubgrid.control.SetParameter("fetchXml", orderFetchXml);
    //Refresh grid to show filtered records only.
    orderSubgrid.control.Refresh();
}
</code>```

答:
There is a supported no-code way to do this.

Create a QuickView in Contact entity containing the subgrid to Orders

Add the QuickView to the Account entity linking it to the Contact lookup

If the Contact is not from a lookup, you can

Add a hidden lookup on Contact in the Account form

Make your javascript fill this lookup with the reference to the contact you want to filter the subgrid on (remember to .fireOnChange() after filling the field, to invoke the next step)

invoke refresh() to update the subgrid in the onchange of the contact lookup you just filled

Then implement the quickview like the two points above.

Body:
I've subgrid on Account form, I am trying to get list of Orders of child contact and then add to subgrid. So, far I did the following scripts but it throws error that cannot read property 'SetParameter' of undefined. Can anyone please guide how can I change fetchxml of a subgrid?

function listOfOrders(contactId){
    var orderFetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>"+
                    "  <entity name='salesorder'>"+
                    "    <attribute name='name' />"+
                    "    <attribute name='customerid' />"+
                    "    <attribute name='salesorderid' />"+
                    "    <attribute name='statecode' />"+
                    "    <attribute name='createdon' />"+
                    "    <order attribute='name' descending='false' />"+
                    "    <filter type='and'>"+
                    "      <condition attribute='customerid' operator='eq' uitype='contact' value='"+contactId+"' />"+
                    "    </filter>"+
                    "  </entity>"+
                    "</fetch>";

    var retrievedOrders = XrmServiceToolkit.Soap.Fetch(orderFetchXml);

        var contactId = "";
        if(retrievedOrders.length <0)
            return;

    var viewId = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
    var viewDisName = "Account Orders subgridview";

     var layOutXml = "<grid name='resultset' object='1' jump='name' select='1' icon='1' preview='1'>" +
                            "<row name='result' id='salesorderid'>" +
                            "<cell name='name' width='300' />" +
                            "<cell name='statecode' />"+
                            "<cell name='createdon' />"+
                            "<cell name='customerid' />"+
                            "disableSorting='1' />" +
                            "</row>" +
                    "</grid>";
    var orderSubgrid = window.parent.document.getElementById("orderssubgrid");
    //apply layout and filtered fetchXML
    orderSubgrid.control.SetParameter("layoutXml", layOutXml);
    orderSubgrid.control.SetParameter("fetchXml", orderFetchXml);
    //Refresh grid to show filtered records only.
    orderSubgrid.control.Refresh();
}


问:
Null-Conditional Operator

var a = b?.c.d;

Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding usage of this operator in an expression spreads viral.

But neither Visual Studio 2015 nor Resharper says anything to me, am I missing something here?

答:
The operator is just syntactic sugar for this:

```<code>MyType a = b == null ?
    null:
    b.c.d;
</code>```

Why this should throw a compile-error is unclear to me.

If b is null, the null value is propagated through so c will also be null and thus also need this operator

This isn´t true. Actually when b is null c doesn´t even exist as there´s no instance on which that member could exist. So in short the operator just returns null and omits evaluating c or even d any further.

Title: Null-Conditional Operator

Body:
The operator is just syntactic sugar for this:

MyType a = b == null ?
    null:
    b.c.d;

Why this should throw a compile-error is unclear to me.

If b is null, the null value is propagated through so c will also be null and thus also need this operator

This isn´t true. Actually when b is null c doesn´t even exist as there´s no instance on which that member could exist. So in short the operator just returns null and omits evaluating c or even d any further.


答: This operator does short circuit and returns null in case of b is null.

Title: Null-Conditional Operator

Body:
var a = b?.c.d;

Shouldn't this expression always give a compile error? If b is null, the null value is propagated through so c will also be null and thus also need this operator. In my understanding usage of this operator in an expression spreads viral.

But neither Visual Studio 2015 nor Resharper says anything to me, am I missing something here?


问:
How to make a progress-bar in copy or query?
How can I make a progress-bar in copy or SQL query or file transfer (rapi)?

Or some thing's that I can't measure?

Thanks for any help.

答:
It really depends on how architect your code.

As far as I know, there is no API for tracking the progress of a task such as copying files or running SQL commands. If you want to be able to track progress, you'll have to devise some sort of way to break the task up into measurable tasks, then use that as your progress benchmark.

For example, if you were doing a series of SQL INSERT queries, measure the number of queries you will need (if possible). Keep a count of how many inserts you've performed so far. Every time you finish a query, you can do some simple math to measure your progress since you've got your total queries required, and your queries so far.

OwnerDisplayName: Gold

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Federico Ramponi

OwnerDisplayName: DanHerbert


问:
Use of foreignKey between app models in Django 1.10
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

```<code>from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

The second app, called members has one model called Member.

This is the Member/models.py:

```<code>from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

What I want is include the name of the team inside the member profile, so I know it should be something like:

```<code>team_of_member = models.ForeignKey();
</code>```

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

```<code>from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

答:
In order to do what you want (assuming the code provided is your full "problematic" code) you should:

In Member/models.py:

```<code>from django.db import models
from teams.models import Team  # <--add this line

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        team_of_member = models.ForeignKey(Team, on_delete=models.CASCADE); # <--add this line
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name
</code>```

After you do this, remember to:

python manage.py makemigrations

python manage.py migrate

to change your models state.

Good luck :)

Body:
I have a website built in Django 1.10. The site has 3 different apps: teams, members and news.

The first app, called teams has one model called Team.

This is the Team/models.py:

from django.db import models
from django.db.models.signals import pre_save
from django.utils.text import slugify

class Team(models.Model):
        name = models.CharField(max_length=255)
        description = models.TextField()
        slug = models.CharField(max_length=255, default='team', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

The second app, called members has one model called Member.

This is the Member/models.py:

from django.db import models

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

What I want is include the name of the team inside the member profile, so I know it should be something like:

team_of_member = models.ForeignKey();

But I don't know what to put in the parenthesis or how to import the model of the team to the model of the member. I was following the documentation of Django 1.10 but it wasn't working, also I've tried this link but it doesn't work. Could you give a hand?  Thanks

Edit:
I tried to do as @Bulva was suggesting, so my code is now like this:

from django.db import models
from equipos.models import Team

class Member(models.Model):
        name = models.CharField(max_length=255)
        team = models.ForeignKey('teams.Team', null=True)
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

Body:
In order to do what you want (assuming the code provided is your full "problematic" code) you should:

In Member/models.py:

from django.db import models
from teams.models import Team  # <--add this line

class Piloto(models.Model):
        name = models.CharField(max_length=255)
        team_of_member = models.ForeignKey(Team, on_delete=models.CASCADE); # <--add this line
        biography = models.TextField()
        slug = models.CharField(max_length=255, default='piloto', editable=True)

        class Meta:
                ordering = ('name',)

        def __unicode__(self):
                return self.name

After you do this, remember to:

python manage.py makemigrations

python manage.py migrate

to change your models state.

Good luck :)


问:
How to download multiple files from URL as one zip file
I want to download multiple zip files as one zip file for a request.
I have zip file paths like C, https://test12.zip etc. So how can I download these files as a one zip file. I have been searching this for a while. All i got is examples for downloading multiple files(local) and zip them. This is what i tried for downloading one file. For multiple files it won't work.

```<code>URL url = new URL("https://test12.zip");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());

        int len;
        byte[] buf = new byte[1024];
        while ((len = stream.read(buf)) > 0) {
            outs.write(buf, 0, len);
        }
        outs.close();
</code>```

Any help would be much appreciated.

答:
A ZIP file consists of two parts: First the compressed file entries (filename, attributes and data) and at the end of the file there is a central directory containing a list of all entries, again with filename and attributes.

Hence, you can not directly combine or concatenate zip files. In Java you can only decompress the downloaded zip files on-the-fly (without storing them in the file-system) and at the same time using the decompressed content to create a new combined ZIP file:

First create a ZipOutputStream for the zip file you want to create.

Then use the InputStream of each download and use it with a ZipInputStream.
Iterates through all the entries in every ZipInputStream and for each entry create a new identical entry in the ZipOutputStream and copy the content from the ZipInputStream to the ZipOutputStream.

How to use ZipInputStream see for example: https://stackoverflow.com/a/36648504/150978

Note that this process requires to decompress and afterwards re-compress the file content. Depending on the archive size this can result in a high utilization of one CPU core.

Body:
I want to download multiple zip files as one zip file for a request.
I have zip file paths like C, https://test12.zip etc. So how can I download these files as a one zip file. I have been searching this for a while. All i got is examples for downloading multiple files(local) and zip them. This is what i tried for downloading one file. For multiple files it won't work.

URL url = new URL("https://test12.zip");
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());

        int len;
        byte[] buf = new byte[1024];
        while ((len = stream.read(buf)) > 0) {
            outs.write(buf, 0, len);
        }
        outs.close();

Any help would be much appreciated.

ContentLicense: CC BY-SA 4.0


问:
Converting FORTRAN to C / C++
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

```<code>copy makefile.vc makefile
nmake
</code>```

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?

答: Do you have MS's Visual Studio installed? If so, nmake is available on the Visual Studio Command Line (not the normal command line). If not, perhaps try downloading and installing that?

Title: Converting FORTRAN to C / C++

Body:
As part of my Final Year Project, I need to convert some FORTRAN code into C or C++ (it doesn't matter which language as long as I can understand it, and I can understand C style languages).

I have discovered f2c, a program that allegedly converts FORTRAN to C, and tried to install it, following instructions, by saving a makefile.vc file on my drive and then doing

copy makefile.vc makefile
nmake

(here is the part of the README file about installing f2c that is included in the f2c download page)

To compile f2c on Linux or Unix
  systems, copy makefile.u to makefile,
  edit makefile if necessary (see the
  comments in it and below) and type
  "make" (or maybe "nmake", depending on
  your system).

To compile f2c.exe on MS Windows
  systems with Microsoft Visual C++,

copy makefile.vc makefile  nmake

With other PC compilers, you may need
  to compile xsum.c with -DMSDOS (i.e.,
  with MSDOS #defined).

If your compiler does not understand
  ANSI/ISO C syntax (i.e., if you have a
  K&R C compiler), compile with
  -DKR_headers .

On non-Unix systems where files have
  separate binary and text modes, you
  may need to "make xsumr.out" rather
  than "make xsum.out".

I am running x64 bit version of Windows Vista and tried "nmake", but I get

'nmake' is not recognised as an internal or external command, operable program or batch file.

I downloaded Nmake15.exe after some searching but it doesn't work on x64 bit machines and apparently there is not version of it that does. So I downloaded the Windows SDK, after being told that would work, but it didn't change anything.

Where have I gone wrong in all this, if I have, and is there any way of converting that FORTRAN code into C or C++?


问:
host java web application on remote server
I developed an web application using spring and hibernate.i bought domain name and hosting but now i can not understand how to host this application.i don't know how to install Apache tomcat on this remote server and how to install JDK.

I tried to install tomcat using putty but it showing an error "Network Error :Connection refused"

Can someone provide me details how to host an java application in remote Linux server. I am using windows 7 by the way.

i created war.now i need to deploy this war in tomcat.but how do i install tomcat on that remote server.I want to know A-Z how to host java web app on remote server.

答: I know you have said you already bought a hosting solution, but I have had good experiences with DigitalOcean. They provide lots of documentation on getting started to host web applications and servers. Here is a link to them describing how to install Apache Tomcat on a remote linux server, perhaps this will be helpful.</p>


问:
jQuery validate plugin on DIV
I am trying to use the validate plugin on a div as shown in the answer to this question:

```<code><script type="text/javascript">
  $("#pseudoForm").validate({
    onfocusout:true,
    rules:{
      first_name:"required",
      last_name:"required"
    }
  });
</script>
<!-- whatever -->
<div id="pseudoForm">
  <input type="text" name="first_name"/>
  <input type="text" name="last_name"/>
</div>
</code>```

I have all within a form.

I am getting a bunch of different errors on different browsers.

Firefox: validator in undefined

IE8: 'settings' is null or not an
object

Chrome: Cannot read property 'settings' of undefined

Any help appreciated!

答:
Open jquery.validate.js or jquery.validate.min.js and find(ctrl + F) "label" and replaceAll with your your required tag:

Example: div

then perform validation.

Title: jQuery validate plugin on DIV

Body:
I am trying to use the validate plugin on a div as shown in the answer to this question:

  <input type="text" name="first_name"/>
  <input type="text" name="last_name"/>

I have all within a form.

I am getting a bunch of different errors on different browsers.

Firefox: validator in undefined

IE8: 'settings' is null or not an
object

Chrome: Cannot read property 'settings' of undefined

Any help appreciated!


问:
Will the Android Device Manager app installed by one user enforce the policies for another user of the same device?
I am a newbie to Android Development. I am developing an app which will disable the camera for security reasons. When the device owner logs in as User A, he activates the app which will disable the camera. When the  device owner logs in as User B/Guest then the camera is enabled. But I don't want the camera to be enabled for them. Is this possible if I design the app as a Device Manager? Will the policies enforced by the Device Manager app work across different users of the same device?</p>

答:
Look, so far I know that System keeps users running. just switch between them.

See: Supporting Multiple User

User. Each user is intended to be used by a different physical person.
  Each user has distinct application data and some unique settings, as
  well as a user interface to explicitly switch between users. A user
  can run in the background when another user is active; the system
  manages shutting down users to conserve resources...

So that would explain why permissions are shared between users. I would recommend you to check if current front loggeg-in user is the owner.Then allow camera, otherwise disable it.

You can obtain whether user is owner(admin) by: Android UserManager: Check if user is owner (admin)


问:
onDelete('cascade') not deleting data on pivot table
I have the following migration:

```<code> public function up()
    {
        Schema::create('topics_to_subscriptions', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->integer('topic_id')->unsigned();
            $table->integer('subscription_id')->unsigned();

            $table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
        });
    }
</code>```

My undersatnding is that when using onDelete('cascade'), if I delete a subscription, then all associated TopicsToSubscriptions will be delete.

When I run App\Subscription::truncate(); all the subscriptions are deleted correctly from subscriptions table but no data is deleted from topics_to_subscriptions. what am I doing wrong?

答:
You shouldn't be able to truncate a table referenced by foreign keys.  I suspect your foreign keys never got applied correctly.

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

```<code>public function up()
{
    Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('topic_id')->unsigned();
        $table->integer('youtube_subscription_id')->unsigned();

        $table->foreign('topic_id')->references('id')->on('youtube_topics')->onDelete('cascade');
        $table->foreign('youtube_subscription_id')->references('id')->on('youtube_subscriptions')->onDelete('cascade');
    });
}
</code>```

Body:
I have the following migration:

 public function up()
    {
        Schema::create('topics_to_subscriptions', function (Blueprint $table) {
            $table->engine = 'InnoDB';
            $table->integer('topic_id')->unsigned();
            $table->integer('subscription_id')->unsigned();

            $table->foreign('topic_id')->references('id')->on('topics')->onDelete('cascade');
            $table->foreign('subscription_id')->references('id')->on('subscriptions')->onDelete('cascade');
        });
    }

My undersatnding is that when using onDelete('cascade'), if I delete a subscription, then all associated TopicsToSubscriptions will be delete.

When I run App\Subscription::truncate(); all the subscriptions are deleted correctly from subscriptions table but no data is deleted from topics_to_subscriptions. what am I doing wrong?

Body:
You shouldn't be able to truncate a table referenced by foreign keys.  I suspect your foreign keys never got applied correctly.

https://laravel.com/docs/5.4/migrations#foreign-key-constraints

public function up()
{
    Schema::create('youtube_topics_to_subscriptions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->integer('topic_id')->unsigned();
        $table->integer('youtube_subscription_id')->unsigned();

        $table->foreign('topic_id')->references('id')->on('youtube_topics')->onDelete('cascade');
        $table->foreign('youtube_subscription_id')->references('id')->on('youtube_subscriptions')->onDelete('cascade');
    });
}


问:
Count number of times a value appears (and append it in EVERY row) in R
so I want to count the number of times each value appears in a vector and to create a new vector, of EQUAL length, to bind it with the initial one. So my solution cannot be the table function as it returns only the unique values and the times they appear. I need in each row of the initial vector to append its number of appearences. I have found a solution but I got a big database with ~800k rows and it runs for like 10 min. Does anyone know how to perform this task more efficiently? I include an example.Thanks

```<code>df<-as.data.frame(sample(1:100, 800000, replace = T))
df[2]<-rep(1,nrow(df))
names(df)<-c("Numbers","Count")

df$Count<-pbapply(df,1,function(x) length(which(df$Numbers==df$Numbers[x])))
</code>```

P.S. I have used to pbapply function to keep track of the progress.

答:
If you want a count of the number of each unique item in Number, this is straightforward in dplyr

```<code>library(dplyr)
set.seed(123)
df<-data.frame(Numbers = sample(1:100, 800000, replace = T))
df2 <- df %>%
  group_by(Numbers) %>%
  mutate(Count = n())
head(df2)

# Numbers Count
# 51      8146
# 49      7961
# 3       8090
# 63      8072
# 80      8017
# 80      8017
</code>```

Body:
so I want to count the number of times each value appears in a vector and to create a new vector, of EQUAL length, to bind it with the initial one. So my solution cannot be the table function as it returns only the unique values and the times they appear. I need in each row of the initial vector to append its number of appearences. I have found a solution but I got a big database with ~800k rows and it runs for like 10 min. Does anyone know how to perform this task more efficiently? I include an example.Thanks

df<-as.data.frame(sample(1:100, 800000, replace = T))
df[2]<-rep(1,nrow(df))
names(df)<-c("Numbers","Count")

df$Count<-pbapply(df,1,function(x) length(which(df$Numbers==df$Numbers[x])))

P.S. I have used to pbapply function to keep track of the progress.

Body:
If you want a count of the number of each unique item in Number, this is straightforward in dplyr

library(dplyr)
set.seed(123)
df<-data.frame(Numbers = sample(1:100, 800000, replace = T))
df2 <- df %>%
  group_by(Numbers) %>%
  mutate(Count = n())
head(df2)

# Numbers Count
# 51      8146
# 49      7961
# 3       8090
# 63      8072
# 80      8017
# 80      8017


问:
Cannot convert object of type 'list' to a numeric value
I am making a pyomo model, where i want to use random numbers for my two dimensional parameters. I put a small python script for random numbers that looks exactly what i wanted to see for my two dimensional parameter. I am getting a TypeError: Cannot convert object of type 'list'(value =[[....]] to a numeric value. in my objective function. Below is my objective function and random numbers script.

```<code>model.obj = Objective(expr=sum(model.C[v,l] * model.T[v,l] for v in model.V for l in model.L) + \
            sum(model.OC[o,l] * model.D[o,l] for o in model.O for l in model.L), sense=minimize)

import random
C = [[] for i in range(7)]
for i in range(7):
     for j in range(5):
        C[i]+= [random.randint(100,500)]
model.C = Param(model.V, model.L, initialize=C)
</code>```

Please let me know if someone can help fixing this.

答:
You should initialize your parameter using a function instead of a nested list</p>

```<code>def init_c(m, i, j):
    return random.randint(100,500)
model.c = Param(model.V, model.L, initialize=init_c)
</code>```

Body:
I am making a pyomo model, where i want to use random numbers for my two dimensional parameters. I put a small python script for random numbers that looks exactly what i wanted to see for my two dimensional parameter. I am getting a TypeError: Cannot convert object of type 'list'(value =[[....]] to a numeric value. in my objective function. Below is my objective function and random numbers script.

model.obj = Objective(expr=sum(model.C[v,l] * model.T[v,l] for v in model.V for l in model.L) + \
            sum(model.OC[o,l] * model.D[o,l] for o in model.O for l in model.L), sense=minimize)

import random
C = [[] for i in range(7)]
for i in range(7):
     for j in range(5):
        C[i]+= [random.randint(100,500)]
model.C = Param(model.V, model.L, initialize=C)

Please let me know if someone can help fixing this.

Body:
You should initialize your parameter using a function instead of a nested list

def init_c(m, i, j):
    return random.randint(100,500)
model.c = Param(model.V, model.L, initialize=init_c)


问:
How to remove a comment using AJAX?
I'm trying to write a comment destroy method to remove comments on a page using Ajax (with no page reload).

Here's what I've tried.

posts/show.html.erb

```<code><% @comments.each do |comment| %>
   <div id="comment_<%= comment.id %>">
      <p><strong><%= comment.user.username %></strong></p>
      <p class="comment"><%= comment.comment %><p>
      <%= link_to "Delete", [@post, comment], method: :delete, remote: true %>
   </div>
<% end %>
</code>```

comments_controller.rb

```<code>def destroy
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
  @comment.destroy

  respond_to do |format|
  format.html {redirect_to post_path(id: params[:post_id])}
  format.js
end
</code>```

I'm not sure what else I need but I tried this

posts/destroy.js.erb

```<code>$('#comment_<%= @comment.id %>').remove();
</code>```

Any help is appreciated! According to the server logs, the comment is being removed when I click delete, but the JS is not removing the comment on the front end.

答:
Change

$('#comment_<%= @comment.id %>').remove();

To

```<code>$('#edit_comment_<%= @comment.id %>').remove();
</code>```

Title: How to remove a comment using AJAX?

Body:
I'm trying to write a comment destroy method to remove comments on a page using Ajax (with no page reload).

Here's what I've tried.

posts/show.html.erb

<% @comments.each do |comment| %>
   <div id="comment_<%= comment.id %>">

<%= comment.user.username %>

<%= comment.comment %>

      <%= link_to "Delete", [@post, comment], method: :delete, remote: true %>

<% end %>

comments_controller.rb

def destroy
  @post = Post.find(params[:post_id])
  @comment = Comment.find(params[:id])
  @comment.destroy

  respond_to do |format|
  format.html {redirect_to post_path(id: params[:post_id])}
  format.js
end

I'm not sure what else I need but I tried this

posts/destroy.js.erb

$('#comment_<%= @comment.id %>').remove();

Any help is appreciated! According to the server logs, the comment is being removed when I click delete, but the JS is not removing the comment on the front end.

Body:
Change

$('#comment_<%= @comment.id %>').remove();

To

$('#edit_comment_<%= @comment.id %>').remove();


问:
Python OOP object instantiation
I am new to Python, and I have one dilemma concerning OOP (I am familiar with OOP concepts).

Basically, I have a class with a static class-variable (counter that shows how many objects I have instantiated):

```<code>class Employee:
   counter=0
   def __init__(self,name):
     self.name=name
     Employee.counter+=1
</code>```

So now I instantiate an object:

```<code>obj1=Employee("Alan")
</code>```

My question is: what happens when I have this call? What happens behind, because the static variable "counter" is incremented, but it is possible to access the object created like this?

```<code>Employee("foo")
</code>```

<__main__.Employee object at 0x02A16870>

Thanks

答:
First of all, you need counter+=1 to be Employee.counter += 1 in order for the code to behave like you say it does. Otherwise you will get an error for trying to increment a variable that's not known within the scope of __init__.

Since you have no reference to Employee("foo") it will soon be garbage collected and gone forever. However, this does not change the fact that Employee.__init__ was called to increment your counter.

Title: Python OOP object instantiation

Body:
I am new to Python, and I have one dilemma concerning OOP (I am familiar with OOP concepts).

Basically, I have a class with a static class-variable (counter that shows how many objects I have instantiated):

class Employee:
   counter=0
   def __init__(self,name):
     self.name=name
     Employee.counter+=1

So now I instantiate an object:

obj1=Employee("Alan")

My question is: what happens when I have this call? What happens behind, because the static variable "counter" is incremented, but it is possible to access the object created like this?

Employee("foo")

<__main__.Employee object at 0x02A16870>

Thanks


问:
Remove an If Statement after it has been fired once
Is there anyway of removing an if statement after it has been fired once?

I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away.  I don't though want a the browser constantly tracking a scrollTop() method because of the performance hit from this.

What's the best way to remove or cancel an if statement after it has been used once?

The code is below and I have a codepen here: http://codepen.io/emilychews/pen/evbzMQ

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
    }
  });

  $('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 1s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}</code>```

Menu Box

<button class="mybutton">menu</button>```

答:
Sounds like you actually have two conditions.  One is based on the scroll position, the other is based on some state to be tracked.  So just add a variable to track that state.  Maybe something like:</p>

```<code>var scrolled = false;

$(window).scroll(function() {
    if ( !scrolled && $(document).scrollTop() > 1) { // check the state
        $('.menubox').css('left', '-25%');
        scrolled = true; // update the state
    }
});

$('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
    scrolled = false; // don't forget to reset the state
});
</code>```

Body:
Is there anyway of removing an if statement after it has been fired once?

I have a menu container that shows on page load and want it so when the user scrolls 1px it slides away.  I don't though want a the browser constantly tracking a scrollTop() method because of the performance hit from this.

What's the best way to remove or cancel an if statement after it has been used once?

The code is below and I have a codepen here: http://codepen.io/emilychews/pen/evbzMQ

jQuery(document).ready(function($) {
  $(window).scroll(function() {
    if ($(document).scrollTop() > 1) {
      $('.menubox').css('left', '-25%');
    }
  });

  $('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
  });
});

body {
  margin: 0;
  padding: 0;
  height: 200vh;
}

.menubox {
  top: 100;
  position: fixed;
  width: 20%;
  height: 100%;
  background: red;
  padding: 10px;
  color: white;
  transition: all 1s;
}

.mybutton {
  position: fixed;
  left: 40%;
  top: 50px;
  padding: 5px 10px;
}

Menu Box

<button class="mybutton">menu</button>

Body:
Sounds like you actually have two conditions.  One is based on the scroll position, the other is based on some state to be tracked.  So just add a variable to track that state.  Maybe something like:

var scrolled = false;

$(window).scroll(function() {
    if ( !scrolled && $(document).scrollTop() > 1) { // check the state
        $('.menubox').css('left', '-25%');
        scrolled = true; // update the state
    }
});

$('.mybutton').on('click', function() {
    $('.menubox').css('left', '0%');
    scrolled = false; // don't forget to reset the state
});


问:
How to associate list with each enum item in c#
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

```<code>public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }
</code>```

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

```<code>public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }
</code>```

答:
What you have here is actually state machine. You can create method which defines possible stage transitions for each stage supported by your application. E.g. (of course you don't have to use iterators, you can simply return array of stages from each case block):

```<code>public static IEnumerable<MatchStage> GetAvailableStageTransitions(MatchStage stage)
{
    switch (stage)
    {
        case MatchStage.FirstHalfAssumedStartTime:
            yield return MatchStage.FirstHalfAssumedEndTime;
            yield return MatchStage.PauseStartTime;
            yield break;
        case MatchStage.SecondHalfAssumedStartTime:
            yield return MatchStage.SecondHalfAssumedEndTime;
            yield return MatchStage.PauseStartTime;
            yield break;
        // etc
        default:
            throw new NotSupportedException($"Stage {stage} is not supported.");
    }
}
</code>```

Then checking if proposed stage is available:

```<code>GetAvailableStageTransitions(currentSiteCoreStage).Contains(proposedStage)
</code>```

Depending on complexity of your system you can think about incapsulating state transions and logic realted to each state into state objects. For more details read about State Design Pattern.

Body:
I have website to perform match action. I am writing code to restrict some of the action based on current match stage. For example, If first half is current stage then I should restrict direct end match without second half. For each stage, I have multiple restrict stages. Below is my stage enum.

public enum MatchStage
    {
        FirstHalfAssumedStartTime = 1,
        FirstHalfAssumedEndTime = 2,
        SecondHalfAssumedStartTime = 3,
        SecondHalfAssumedEndTime = 4,
        ExtraFirstHalfAssumedStartTime = 5,
        ExtraFirstHalfAssumedEndTime = 6,
        ExtraSecondHalfAssumedStartTime = 7,
        ExtraSecondHalfAssumedEndTime = 8,
        PauseStartTime = 9,
        PauseEndTime = 10,
        EndMatchTime = 11
    }

I would like to make below method work. I want to call something like currentSiteCoreStage.RestrictedStages which returns List of restricted stages. How can I achieve this?

public static bool IsProposedStageValid(MatchStage currentSiteCoreStage, MatchStage proposedStage )
        {
            if (currentSiteCoreStage.RestrictedStages.Contains(proposedStage)) // I am hoping to make this work
                return false;
        }

Body:
What you have here is actually state machine. You can create method which defines possible stage transitions for each stage supported by your application. E.g. (of course you don't have to use iterators, you can simply return array of stages from each case block):

public static IEnumerable<MatchStage> GetAvailableStageTransitions(MatchStage stage)
{
    switch (stage)
    {
        case MatchStage.FirstHalfAssumedStartTime:
            yield return MatchStage.FirstHalfAssumedEndTime;
            yield return MatchStage.PauseStartTime;
            yield break;
        case MatchStage.SecondHalfAssumedStartTime:
            yield return MatchStage.SecondHalfAssumedEndTime;
            yield return MatchStage.PauseStartTime;
            yield break;
        // etc
        default:
            throw new NotSupportedException($"Stage {stage} is not supported.");
    }
}

Then checking if proposed stage is available:

GetAvailableStageTransitions(currentSiteCoreStage).Contains(proposedStage)

Depending on complexity of your system you can think about incapsulating state transions and logic realted to each state into state objects. For more details read about State Design Pattern.


问:
Is there a way to change column name before fetching data?
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

```<code>      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));
</code>```

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

答:
I'm not entirely sure on how this is being called, but you could be a bit sneaky on the entity itself.  I think you are saying that you are always using the Title property on the entity, but you need it to be EN when the culture is set to EN.  If you don't mind selecting both values every time on every query, there is an easy fix for this.

In your entity, I would do something like this:

```<code>public class MyEntity
{
   [Column("Title")]  // Can use FluentApi here instead
   public string TitleOld { get; set; }

   [Column("TitleEN")]
   public string TitleEN { get; set; }

   [NotMapped]
   public string Title
   {
     get { return Thread.CurrentThread.CurrentUICulture.Name == "en-US" ? TitleEN : TitleOld; }
     set { TitleOld = value; }
   }
}
</code>```

This way, your code wouldn't change, but you'd be selecting both values down every time.

Body:
Is there a way to change column name before fetching data in all the controllers I call that column from, for example I had 2 columns in my table "Section" : "Title" and "TitleEN"

If the current culture is "en", I want to fetch "TitleEn" data but in my code I'll only use "Title" like this:

      section.Where(p =>
      p.Title.ToUpper().Contains(searchword.ToUpper()));

I was working on a project with only one language and then the client requested adding English. Unfortunately I made the wrong decision by adding language fields for every table having string fields.

Now I want to fix this because the project has a lot of code dealing only with fields without "En".

Body:
I'm not entirely sure on how this is being called, but you could be a bit sneaky on the entity itself.  I think you are saying that you are always using the Title property on the entity, but you need it to be EN when the culture is set to EN.  If you don't mind selecting both values every time on every query, there is an easy fix for this.

In your entity, I would do something like this:

public class MyEntity
{
   [Column("Title")]  // Can use FluentApi here instead
   public string TitleOld { get; set; }

   [Column("TitleEN")]
   public string TitleEN { get; set; }

   [NotMapped]
   public string Title
   {
     get { return Thread.CurrentThread.CurrentUICulture.Name == "en-US" ? TitleEN : TitleOld; }
     set { TitleOld = value; }
   }
}

This way, your code wouldn't change, but you'd be selecting both values down every time.


问:
Unpacked javascript doesn't work
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

```<code>ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14
</code>```

答: It seems like you have a syntax error in your code (referencing an unknown variable - typo?). If you copy your modified cshout.js to cshout.packed.js and it doesn't work, it means you broke something when you modified the original library.

Title: Unpacked javascript doesn't work

Body:
I found this script (http://coolersport.info/) and downloaded it. I want change some things in javascript code, so I opened cshout.js (unpacked version) and do changes. I saved it as "cshout.packed.js" (replaced with original packed version).

But now I go to my script index, I can't see any thing, And I see only a white blank page...

Why unpacked version doesn't work? The packed version was create from original unpacked file  (I have same problem with some other scripts...it is an example!)

I debugging it with FireBug. Firebug said:

ajaxCS is not defined
localhost/cshout/cshout.js Line 49
cshout is not defined localhost/cshout
Line 14


问:
Converting array of unicode byte to string
From some external module I receive array with unicode symbols and can not convert it to string.

```<code>   print(data)
   print(type(data))
   print(type(data[0]))
   print(len(data[0]))
</code>```

Output

```<code>   array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])
   <type 'unicode'>
   <type 'unicode'>
   1
</code>```

So I just need to get a string 'cdcdcdcdc', but type of data[0] is unicode, although 'B' (int) presented. All my tires finished with errors or I got same one array (not a string) when print.

upd:I tried

```<code>   rets=''
   for i in xrange(len(data)):
       rets += chr(int(ord( data[i] )))
   print( rets )
</code>```

答:
you can use eval to convert a string to a python object in this case a list(unicode can be handled many times as a string. So eval will work with unicode aswell). If data[1] is already a list just remove eval from the print statement.

Then use map to turn every int into a character with chr. This can then be made into a string with "".join

```<code> print ("".join(map(chr,eval(data[1]))))
</code>```

output:

```<code> "cdcdcdcdc"
</code>```

Edited:
try it in a few statements to see where it goes wrong

```<code>print (eval(data[1])) #check if eval works
print (type(eval(data[1]))) #check if the type that evel returns is a list
print (type(map(chr,eval(data[1]))[0])) #check if the types in the list are strings
print (map(chr,eval(data[1]))) #check if you get a list with strings
</code>```

Body:
From some external module I receive array with unicode symbols and can not convert it to string.

   print(data)
   print(type(data))
   print(type(data[0]))
   print(len(data[0]))

Output

   array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])
   <type 'unicode'>
   <type 'unicode'>
   1

So I just need to get a string 'cdcdcdcdc', but type of data[0] is unicode, although 'B' (int) presented. All my tires finished with errors or I got same one array (not a string) when print.

upd:I tried

   rets=''
   for i in xrange(len(data)):
       rets += chr(int(ord( data[i] )))
   print( rets )

Body:
you can use eval to convert a string to a python object in this case a list(unicode can be handled many times as a string. So eval will work with unicode aswell). If data[1] is already a list just remove eval from the print statement.

Then use map to turn every int into a character with chr. This can then be made into a string with "".join

 print ("".join(map(chr,eval(data[1]))))

output:

 "cdcdcdcdc"

Edited:
try it in a few statements to see where it goes wrong

print (eval(data[1])) #check if eval works
print (type(eval(data[1]))) #check if the type that evel returns is a list
print (type(map(chr,eval(data[1]))[0])) #check if the types in the list are strings
print (map(chr,eval(data[1]))) #check if you get a list with strings


问:
Bamboo - SonarQube multimodule maven project skip the child module
I have created SonarQube task in Bamboo. I have one parent pom which contains 4 modules. While running the task it skips the child tasks.I am not getting the root cause???

Parent POM.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mastercard.mpts.emailsms</groupId>
    <artifactId>emailsms-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>
    <description>EmailSMS Application</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <modules>
        <module>ESBMsgProcessor</module>
        <module>EmailSMSService</module>
        <module>SMTPMsgProcessor</module>
        <module>ESBSMSService</module>
    </modules>

</project>
</code>```

Following is child for SMTPMsgProcessor

```<code><?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.mastercard.mpts.emailsms</groupId>
    <artifactId>emailsms-parent</artifactId>
    <version>1.0</version>
  </parent>
  <groupId>com.mastercard.mpts.emailsms</groupId>
  <artifactId>smtpmsgprocessor</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SMTPMsgProcessor</name>
  <description>Handle Email for SMTP</description>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
</code>```

Result of SonarQube plan is :

```<code>30-Mar-2017 08:33:10    [INFO] Reactor Summary:
30-Mar-2017 08:33:10    [INFO]
30-Mar-2017 08:33:10    [INFO] emailsms-parent .................................... SUCCESS [ 33.879 s]
30-Mar-2017 08:33:10    [INFO] ESBMsgProcessor .................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] EmailSMSService .................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] SMTPMsgProcessor ................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] ESBSMSService ...................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] ------------------------------------------------------------------------
30-Mar-2017 08:33:10    [INFO] BUILD SUCCESS
30-Mar-2017 08:33:10    [INFO] ------------------------------------------------------------------------
30-Mar-2017 08:33:10    [INFO] Total time: 34.260 s
30-Mar-2017 08:33:10    [INFO] Finished at: 2017-03-30T08:33:10-05:00
30-Mar-2017 08:33:11    [INFO] Final Memory: 48M/3050M
</code>```

I have not added anything to get skipped.Also I am not able to see soanr analysis for the same as modules are getting skipped.

答:
The sonar:sonar Maven goal is an aggregator one: this means that it is triggered only once on the root module. It's then up to the SonarQube Scanner for Maven to analyse the modules on its own.

So from a Maven point of view, it looks like the modules are skipped, but actually they are analyzed by SonarQube correctly. Go to your SonarQube web interface, and you will find the modules inside your project.

Body:
I have created SonarQube task in Bamboo. I have one parent pom which contains 4 modules. While running the task it skips the child tasks.I am not getting the root cause???

Parent POM.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mastercard.mpts.emailsms</groupId>
    <artifactId>emailsms-parent</artifactId>
    <packaging>pom</packaging>
    <version>1.0</version>
    <description>EmailSMS Application</description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <modules>
        <module>ESBMsgProcessor</module>
        <module>EmailSMSService</module>
        <module>SMTPMsgProcessor</module>
        <module>ESBSMSService</module>
    </modules>

</project>

Following is child for SMTPMsgProcessor

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.mastercard.mpts.emailsms</groupId>
    <artifactId>emailsms-parent</artifactId>
    <version>1.0</version>
  </parent>
  <groupId>com.mastercard.mpts.emailsms</groupId>
  <artifactId>smtpmsgprocessor</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>SMTPMsgProcessor</name>
  <description>Handle Email for SMTP</description>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>

Result of SonarQube plan is :

30-Mar-2017 08:33:10    [INFO] Reactor Summary:
30-Mar-2017 08:33:10    [INFO]
30-Mar-2017 08:33:10    [INFO] emailsms-parent .................................... SUCCESS [ 33.879 s]
30-Mar-2017 08:33:10    [INFO] ESBMsgProcessor .................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] EmailSMSService .................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] SMTPMsgProcessor ................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] ESBSMSService ...................................... SKIPPED
30-Mar-2017 08:33:10    [INFO] ------------------------------------------------------------------------
30-Mar-2017 08:33:10    [INFO] BUILD SUCCESS
30-Mar-2017 08:33:10    [INFO] ------------------------------------------------------------------------
30-Mar-2017 08:33:10    [INFO] Total time: 34.260 s
30-Mar-2017 08:33:10    [INFO] Finished at: 2017-03-30T08:33:10-05:00
30-Mar-2017 08:33:11    [INFO] Final Memory: 48M/3050M

I have not added anything to get skipped.Also I am not able to see soanr analysis for the same as modules are getting skipped.


问:
Python OOP - Should def main() be outside of any class in a .py file?
I have a question when it comes to OOP in general, as well as Python in particular. Let's say that I have, for instance, priorities.py - a simple GUI program to manage priorities and there are three classes: Priority, Client, GuiPart:

```<code># priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:
    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

class Client:
    pass

def main():
    g = GuiPart()
    g.display()
    root = g.root.mainloop()

main()
</code>```

Should I put def main() outside of any classes, or should I put it in Client class?

答:
Every module(python file) have a builtin __name__ variable, if this equal to "__main__" this means that this file ran directly, but if __name__ is equal to other things this means that current file imported to other python files.

if you running this file directly or as module, you can use __name__ variable to recognize type of code-file used, similar below:

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

Now users can running this file directly and/or programmers can use this module in other codes without running main() function.

Body:
I have a question when it comes to OOP in general, as well as Python in particular. Let's say that I have, for instance, priorities.py - a simple GUI program to manage priorities and there are three classes: Priority, Client, GuiPart:

# priorities.py
#   GUI program to manage priorities

from tkinter import *

class Priority:
    pass

class GuiPart:
    def __init__(self):
        self.root = self.createWindow()

    def createWindow(self):

        root = Tk()
        root.resizable(width = False, height = False)
        root.title("Priorities")

        return root

    def display(self):

        Label(self.root,
              text = "testes").grid(row = 0, column = 1)

class Client:
    pass

def main():
    g = GuiPart()
    g.display()
    root = g.root.mainloop()

main()

Should I put def main() outside of any classes, or should I put it in Client class?

Body:
Every module(python file) have a builtin __name__ variable, if this equal to "__main__" this means that this file ran directly, but if __name__ is equal to other things this means that current file imported to other python files.

if you running this file directly or as module, you can use __name__ variable to recognize type of code-file used, similar below:

# Some codes
if __name__ == '__main__':
    main()

Now users can running this file directly and/or programmers can use this module in other codes without running main() function.


问:
Effective ways to deploy rcp applications outside eclipse
Dear all,
I would like to know if there is any best practice or effective way to deploy a set of eclipse osgi bundles (developed with eclipse RCP) outside the eclipse IDE. Up to now we are deploying the plugins with hand-written scripts but this procedure is error prone and time consuming. I discovered the "Plug-In Development -> Product Configuration" approach offered by eclipse but honestly I cannot get it working: in particular I cannot understand what is the correct choice for the Product Application. I tried with org.eclipse.ui.ide.workbench but I got errors during the export procedure.</p>

答:
Have you created an Application class? This is the class that should fire up the Workbench and start your RCP app. The difference between an application and a product is explained here.

Rather than create your Application class from scratch, the easiest way to do it is to create a new "Hello RCP" plug-in project (see previous link), which gives you a basic working RCP app. This will give you the workbench to which your other plug-ins can contribute.

This gives you a product application to select when exporting your product. Choosing "org.eclipse.ui.ide.workbench" as you did will try to export the Eclipse IDE with all its plug-ins as a new RCP app, which is probably not what you want to do.


问:
How to refer a view inside include layout in android
Hi i have coded the following to get the view from include layout. But i am getting null pointer exception. Where i am wrong?

My Java Code:

```<code>View actionbar = findViewById(R.id.actionbar);
                RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR);
                actionRRl.setEnabled(false);
                actionRRl.setClickable(false);
</code>```

In my Activity.xml,

```<code>   <include
            android:id="@+id/actionbar"
            layout="@layout/actionbar" />
</code>```

Layout that is included, ie., actionbar.xml

```<code>  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/header"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:id="@+id/actionRR"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:clickable="false"
            android:padding="@dimen/logo_size"
            android:src="@drawable/logo" />

    </RelativeLayout>
</code>```

Error Stack:

```<code>Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference
</code>```

答:
Once you include the toolbar layout to your activity, their components belong to your activity as well, so you can instantiate them directly</p>

```<code>RelativeLayout actionRRl = (RelativeLayout) findViewById(R.id.actionRR);
actionRRl.setEnabled(false);
actionRRl.setClickable(false);
</code>```

Body:
Hi i have coded the following to get the view from include layout. But i am getting null pointer exception. Where i am wrong?

My Java Code:

View actionbar = findViewById(R.id.actionbar);
                RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR);
                actionRRl.setEnabled(false);
                actionRRl.setClickable(false);

In my Activity.xml,

   <include
            android:id="@+id/actionbar"
            layout="@layout/actionbar" />

Layout that is included, ie., actionbar.xml

  <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/header"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:clickable="false"
        android:id="@+id/actionRR"
        android:orientation="vertical">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:clickable="false"
            android:padding="@dimen/logo_size"
            android:src="@drawable/logo" />

    </RelativeLayout>

Error Stack:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setEnabled(boolean)' on a null object reference

Body:
Once you include the toolbar layout to your activity, their components belong to your activity as well, so you can instantiate them directly

RelativeLayout actionRRl = (RelativeLayout) findViewById(R.id.actionRR);
actionRRl.setEnabled(false);
actionRRl.setClickable(false);


问:
n.times do returns value of n
I have a problem with my code, I want it to display n number of stars. It display the right number of stars,  plus the integer  like ***3I only want ***

show.html.slim

```<code>= article.rating_average.times do
  span
  i.fa.fa-star
</code>```

答:
Change = to -:

```<code>- article.rating_average.times do
  %span.fa.fa-star
</code>```

= evaluates code and prints the returned value (3 is a return value of article.rating_average.times {})

- just evaluates code (gives you 3 stars without the returned value printed)

Title: n.times do returns value of n

Body:
I have a problem with my code, I want it to display n number of stars. It display the right number of stars,  plus the integer  like ***3I only want ***

show.html.slim

= article.rating_average.times do
  span
  i.fa.fa-star

Body:
Change = to -:

- article.rating_average.times do
  %span.fa.fa-star

= evaluates code and prints the returned value (3 is a return value of article.rating_average.times {})

- just evaluates code (gives you 3 stars without the returned value printed)


问:
The service cannot accept control messages at this time
I just stopped an Application Pool in IIS. When trying to start it, IIS complains that,

The service cannot accept control messages at this time. (Exception from HRESULT: 0x80080425).

What gives? Whence did this error come?

Looking at the Event Viewer > System shows these warnings:

A worker process '1456' serving application pool 'MyAppPool' failed to stop a listener channel for protocol 'http' in the allotted time.  The data field contains the error number.

A process serving application pool 'MyAppPool' suffered a fatal communication error with the Windows Process Activation Service. The process id was '10592'. The data field contains the error number.

A process serving application pool 'MyAppPool' exceeded time limits during shut down. The process id was '10516'.

This resolved itself after about 5-minutes, at which point we tried to restart the website, and received:

The World Wide Web Publish Service (W3SVC) is stopped. Web sites cannot be started unless the World Wide Web Publishing Service (W3SVC) is running.

So, we started the W3SVC service, and then we could start our website.

答: Being impatient, I created a new App Pool with the same settings and used that.</p>


问:
elasticsearch : replace several term request in a should container by one unique request
I would like to make a request on an array of number in spite of repeat the same term request several time with a different searched term

This is my request with three differents term query in a should container

```<code>POST /test_index/film_type/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "id_film": {
                    "value": 4
                  }
                }
              },
              {
                "term": {
                  "id_film": {
                    "value": 5
                  }
                }
              },
              {
                "term": {
                  "id_film": {
                    "value": 45
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}
</code>```

Do you know how to do this please?

答:
You could take a look at the Simple Query String Query

Small example:

```<code>POST test/test/1
{
  "film-id": 1
}

POST test/test/2
{
  "film-id": 2
}

POST test/test/3
{
  "film-id": 3
}

GET test/_search
{
  "query": {
    "simple_query_string": {
      "query": "1 | 2",
      "fields": [
          "film-id"
        ]
    }
  }
}
</code>```

result:

```<code>"hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "test",
        "_type": "test",
        "_id": "2",
        "_score": 1,
        "_source": {
          "film-id": 2
        }
      },
      {
        "_index": "test",
        "_type": "test",
        "_id": "1",
        "_score": 1,
        "_source": {
          "film-id": 1
        }
      }
    ]
  }
}
</code>```

Hope this helps!

Body:
I would like to make a request on an array of number in spite of repeat the same term request several time with a different searched term

This is my request with three differents term query in a should container

POST /test_index/film_type/_search
{
  "query": {
    "bool": {
      "filter": [
        {
          "bool": {
            "should": [
              {
                "term": {
                  "id_film": {
                    "value": 4
                  }
                }
              },
              {
                "term": {
                  "id_film": {
                    "value": 5
                  }
                }
              },
              {
                "term": {
                  "id_film": {
                    "value": 45
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Do you know how to do this please?

Body:
You could take a look at the Simple Query String Query

Small example:

POST test/test/1
{
  "film-id": 1
}

POST test/test/2
{
  "film-id": 2
}

POST test/test/3
{
  "film-id": 3
}

GET test/_search
{
  "query": {
    "simple_query_string": {
      "query": "1 | 2",
      "fields": [
          "film-id"
        ]
    }
  }
}

result:

"hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "test",
        "_type": "test",
        "_id": "2",
        "_score": 1,
        "_source": {
          "film-id": 2
        }
      },
      {
        "_index": "test",
        "_type": "test",
        "_id": "1",
        "_score": 1,
        "_source": {
          "film-id": 1
        }
      }
    ]
  }
}

Hope this helps!


问:
How to create a controller in VS 2017 Core
I installed RTM VS 2017 and created a project:

Template: ASP.NET Core Web Application (.Net Core)

ASP.NET Core 1.1 Templates:Web Application

Right Click Controller, Add, Controller and select Full Dependency

Right Click Controller, Add, Controller, and select MVC Controller Empty

Click Add, Add (scaffolding now runs)

I get this error: There was an error running the selected code generator: The specified deps.json [.....bin\HPD\Debug\netcoreapp1.1\myApp.deps.json] does not exist.

I reinstalled VS 2017 just in case I had some kind of corruption but get the same error.  I tried manually adding an empty deps.json in the indicated location but that just leads to a different error because the file is empty.

It would seem that the Full Dependency action should have provided any necessary files.  However, do I need to do something to have this file generated before scaffolding will work?

答:
I haven't had that problem, but I want to point out there are Nuget packages installed when you select to install MVC Scaffolding Full Dependencies.

If you want your application back to the previous state (without Scaffolding), simply uninstall those packages.

```<code><PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />
</code>```

Body:
I haven't had that problem, but I want to point out there are Nuget packages installed when you select to install MVC Scaffolding Full Dependencies.

If you want your application back to the previous state (without Scaffolding), simply uninstall those packages.

<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.1" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.0" />


问:
Tensorflow: InvalidArgumentError: You must feed a value for placeholder tensor 'Placeholder_1'
I get the above error for the following code that is supposed to find a conic section that best fits the source image:

```<code>import numpy as np
import tensorflow as tf
import cv2

# import image
img = cv2.imread('stinkbug.png')
height, width, channels = img.shape

# blur image
img = cv2.blur(img, (5, 5))

# posterize image
n = 4    # Number of levels of quantization
indices = np.arange(0,256)   # List of all colors
divider = np.linspace(0,255,n+1)[1] # we get a divider
quantiz = np.int0(np.linspace(0,255,n)) # we get quantization colors
color_levels = np.clip(np.int0(indices/divider),0,n-1) # color levels 0,1,2..
palette = quantiz[color_levels] # Creating the palette
im2 = palette[img]  # Applying palette on image
im2 = cv2.convertScaleAbs(im2) # Converting image back to uint8
img = im2

# create graph image
graph = np.zeros((height, width, 3), np.uint8)
graph[:] = (255, 255, 255)
cv2.imwrite('grf.png', graph)

# Model parameters
A = tf.Variable([20], tf.int32)
B = tf.Variable([20], tf.int32)
C = tf.Variable([20], tf.int32)
D = tf.Variable([20], tf.int32)
E = tf.Variable([20], tf.int32)
F = tf.Variable([20], tf.int32)
G = tf.Variable([20], tf.int32)
Red = tf.Variable([20], tf.int32)
Green = tf.Variable([20], tf.int32)
Blue = tf.Variable([20], tf.int32)

#inputs
pic = tf.placeholder(tf.int32, shape=(height, width))
out = tf.placeholder(tf.int32, shape=(height, width))

sess = tf.Session()

# model
def conic_model(x, y):
    tf.multiply(A, (x+F)) ** 2 + tf.multiply(tf.multiply(B, (x+F)), (y+G)) + tf.multiply(C, (y+G)) ** 2 + tf.multiply(D, (x+F)) + tf.multiply(E, (y+G))
def f1(): return (Red, Green, Blue)
def f2(): return (255, 255, 255)
decider = tf.cond(tf.less(conic_model(out.eval(session=sess), out[0].eval(session=sess)), 0), f1(), f2())
grf = decider

# loss
combo = tf.reduce_sum(tf.square(pic - grf))
loss = combo / (height * width)

# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training loop
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
  sess.run(train, feed_dict={pic:img, out:graph})
</code>```

The error occurs on line 42, out = tf.placeholder(tf.int32, shape=(height, width)). Out is supposed to be just (255, 255, 255), so I am not sure what is going on.

答:
The only thing I see right now is that your input is not really correct. Your placeholders are:

```<code>pic = tf.placeholder(tf.int32, shape=(height, width))
out = tf.placeholder(tf.int32, shape=(height, width))
</code>```

While your images are of shape (height,width,3) <- color channels

Can you try fixing this and see if this works?

Body:
I get the above error for the following code that is supposed to find a conic section that best fits the source image:

import numpy as np
import tensorflow as tf
import cv2

# import image
img = cv2.imread('stinkbug.png')
height, width, channels = img.shape

# blur image
img = cv2.blur(img, (5, 5))

# posterize image
n = 4    # Number of levels of quantization
indices = np.arange(0,256)   # List of all colors
divider = np.linspace(0,255,n+1)[1] # we get a divider
quantiz = np.int0(np.linspace(0,255,n)) # we get quantization colors
color_levels = np.clip(np.int0(indices/divider),0,n-1) # color levels 0,1,2..
palette = quantiz[color_levels] # Creating the palette
im2 = palette[img]  # Applying palette on image
im2 = cv2.convertScaleAbs(im2) # Converting image back to uint8
img = im2

# create graph image
graph = np.zeros((height, width, 3), np.uint8)
graph[:] = (255, 255, 255)
cv2.imwrite('grf.png', graph)

# Model parameters
A = tf.Variable([20], tf.int32)
B = tf.Variable([20], tf.int32)
C = tf.Variable([20], tf.int32)
D = tf.Variable([20], tf.int32)
E = tf.Variable([20], tf.int32)
F = tf.Variable([20], tf.int32)
G = tf.Variable([20], tf.int32)
Red = tf.Variable([20], tf.int32)
Green = tf.Variable([20], tf.int32)
Blue = tf.Variable([20], tf.int32)

#inputs
pic = tf.placeholder(tf.int32, shape=(height, width))
out = tf.placeholder(tf.int32, shape=(height, width))

sess = tf.Session()

# model
def conic_model(x, y):
    tf.multiply(A, (x+F)) ** 2 + tf.multiply(tf.multiply(B, (x+F)), (y+G)) + tf.multiply(C, (y+G)) ** 2 + tf.multiply(D, (x+F)) + tf.multiply(E, (y+G))
def f1(): return (Red, Green, Blue)
def f2(): return (255, 255, 255)
decider = tf.cond(tf.less(conic_model(out.eval(session=sess), out[0].eval(session=sess)), 0), f1(), f2())
grf = decider

# loss
combo = tf.reduce_sum(tf.square(pic - grf))
loss = combo / (height * width)

# optimizer
optimizer = tf.train.GradientDescentOptimizer(0.01)
train = optimizer.minimize(loss)

# training loop
init = tf.global_variables_initializer()
sess.run(init)
for i in range(1000):
  sess.run(train, feed_dict={pic:img, out:graph})

The error occurs on line 42, out = tf.placeholder(tf.int32, shape=(height, width)). Out is supposed to be just (255, 255, 255), so I am not sure what is going on.

Body:
The only thing I see right now is that your input is not really correct. Your placeholders are:

pic = tf.placeholder(tf.int32, shape=(height, width))
out = tf.placeholder(tf.int32, shape=(height, width))

While your images are of shape (height,width,3) <- color channels

Can you try fixing this and see if this works?


问:
HABTM join table with a HABTM relationship
If i have the following database table names in a HTBTM relantionship:

```<code>**dressess**
id

**dressess_categories**
id
dress_id
category_id

**categories**
id
</code>```

How do I have to create the database table names for an HABTM relationship need it in dressess_categories table, for example:

```<code>**dressess_categories**
id

**colors_dress_categories**   <--- It is named right?
id
dress_category_id   <--- It is named right?
color_id

**colors**
id
</code>```

Thanks in advance.

答:
First, the join table needs to have the model names in alphabetical order for CakePHP to recognize them automagically:

```<code>dresses_categories /* incorrect */
categories_dresses /* correct */
</code>```

Now for the problem at hand:  If I understand your question correctly, you are trying to create a HABTM association between a Color model and the join table that is used for a different HABTM relationship?  This is not possible.  (or if it is, it will be a cake-hack-a-thon).

First, stop thinking of relationships as they relate between database tables.  Relationships are defined between CakePHP Models, and the tables drive them.  What you will need to do in order to accomplish this task is make four models:

```<code>Dress
Category
DressCategory
Color
</code>```

Define relationships like so:

```<code>Dress         -> hasMany   -> DressCategory
Category      -> hasMany   -> DressCategory
DressCategory -> belongsTo -> Category, Dress
DressCategory -> HABTM     -> Color
Color         -> HABTM     -> DressCategory
</code>```

And five tables with the appropriate foreign keys:

```<code>dresses
-------
id

categories
----------
id

dress_categories
----------------
id
dress_id
category_id

colors
------
id

colors_dress_categories
-----------------------
id
color_id
dress_category_id
</code>```

Body:
If i have the following database table names in a HTBTM relantionship:

**dressess**
id

**dressess_categories**
id
dress_id
category_id

**categories**
id

How do I have to create the database table names for an HABTM relationship need it in dressess_categories table, for example:

**dressess_categories**
id

**colors_dress_categories**   <--- It is named right?
id
dress_category_id   <--- It is named right?
color_id

**colors**
id

Thanks in advance.

Body:
First, the join table needs to have the model names in alphabetical order for CakePHP to recognize them automagically:

dresses_categories /* incorrect */
categories_dresses /* correct */

Now for the problem at hand:  If I understand your question correctly, you are trying to create a HABTM association between a Color model and the join table that is used for a different HABTM relationship?  This is not possible.  (or if it is, it will be a cake-hack-a-thon).

First, stop thinking of relationships as they relate between database tables.  Relationships are defined between CakePHP Models, and the tables drive them.  What you will need to do in order to accomplish this task is make four models:

Dress
Category
DressCategory
Color

Define relationships like so:

Dress         -> hasMany   -> DressCategory
Category      -> hasMany   -> DressCategory
DressCategory -> belongsTo -> Category, Dress
DressCategory -> HABTM     -> Color
Color         -> HABTM     -> DressCategory

And five tables with the appropriate foreign keys:

dresses
-------
id

categories
----------
id

dress_categories
----------------
id
dress_id
category_id

colors
------
id

colors_dress_categories
-----------------------
id
color_id
dress_category_id


问:
Local function vs Lambda C# 7.0
I am looking at the new implementations in C# 7.0 and I find it interesting that they have implemented local functions but I cannot imagine a scenario where a local function would be preferred over a lambda expression, and what is the difference between the two.

I do understand that lambdas are anonymous functions meanwhile local functions are not, but I can't figure out a real world scenario, where local function has advantages over lambda expressions

Any example would be much appreciated. Thanks.

答:
In addition to svick's great answer there is one more advantage to local functions:

They can be defined anywhere in the function, even after the return statement.

```<code>public double DoMath(double a, double b)
{
    var resultA = f(a);
    var resultB = f(b);
    return resultA + resultB;

    double f(double x) => 5 * x + 3;
}
</code>```

Title: Local function vs Lambda C# 7.0

Body:
In addition to svick's great answer there is one more advantage to local functions:

They can be defined anywhere in the function, even after the return statement.

public double DoMath(double a, double b)
{
    var resultA = f(a);
    var resultB = f(b);
    return resultA + resultB;

    double f(double x) => 5 * x + 3;
}


答:
try this

```<code>RelativeLayout actionRRl = (RelativeLayout)findViewById(R.id.actionRR);
                actionbar.setEnabled(false);
                actionbar.setClickable(false);
</code>```

You can also inflate the layout to get a view and do it like this,

```<code>View actionbar = LayoutInflater.from(this).inflate(R.layout.actionbar, null, false);
 RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR);
                actionRRl.setEnabled(false);
                actionRRl.setClickable(false);
</code>```

Title: How to refer a view inside include layout in android

Body:
try this

RelativeLayout actionRRl = (RelativeLayout)findViewById(R.id.actionRR);
                actionbar.setEnabled(false);
                actionbar.setClickable(false);

You can also inflate the layout to get a view and do it like this,

View actionbar = LayoutInflater.from(this).inflate(R.layout.actionbar, null, false);
 RelativeLayout actionRRl = (RelativeLayout)actionbar.findViewById(R.id.actionRR);
                actionRRl.setEnabled(false);
                actionRRl.setClickable(false);


问:
session logout issue in codeigniter
```<code>if ($this->Adminmodel->chck_login($this->input->post('email'), $this->input->post('password')) =="true")
{
    redirect("admin/index");
}
</code>```

答:
If you mean you want to logout - session clear, you can use following code in to your Controller. Here userData is the array that u set the data of the session.</p>

```<code>public function logout() {
    $this->session->unset_userdata('token');
    $this->session->unset_userdata('userData');
    $this->session->sess_destroy();
    redirect('admin/index');
}
</code>```

Title: session logout issue in codeigniter

Body:
If you mean you want to logout - session clear, you can use following code in to your Controller. Here userData is the array that u set the data of the session.

public function logout() {
    $this->session->unset_userdata('token');
    $this->session->unset_userdata('userData');
    $this->session->sess_destroy();
    redirect('admin/index');
}