问:
XSLT Translation from only one "subclass"?
I am trying to take a large XML file and pull only a few tagged elements from it. I thought that I used the template match tag to get into the subclass that I wanted (subClass isn't the right word, but I am coming from this from an RDF/OWL standpoint), but it doesn't seem to filter out the things that are not in that subclass. Here is the code:

XML:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <ns4:getCollectiveTaskResponse
xmlns:ns1="http://sample.com/xsd/task/1.0"
xmlns:ns2="http://sample.com/xsd/commonElements/1.0"     xmlns:ns3="http://sample.com/xsd/individualTask/1.0"     xmlns:ns4="http://sample.com/xsd/collectiveTask/1.0"
xmlns:ns5="http://sample.com/xsd/handle"
xmlns:ns6="http://sample.com/appinfo/1">
<ns4:collectiveTask>
    <ns4:generalInformation>
        <number>13</number>
        <title>Quarterback</title>
        <name>Dan Marino</name>

    </ns4:generalInformation>

        <junk>I don't want this</junk>

</ns4:collectiveTask>

        <junk>I don't want this either</junk>
</ns4:getCollectiveTaskResponse>
</code>```

XSL:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:ns1="http://sample.com/xsd/task/1.0"
xmlns:ns2="http://sample.com/xsd/commonElements/1.0"     xmlns:ns3="http://sample.com/xsd/individualTask/1.0"     xmlns:ns4="http://sample.com/xsd/collectiveTask/1.0"
xmlns:ns5="http://sample.com/xsd/handle"
xmlns:ns6="http://sample.com/appinfo/1">

<xsl:template     match="/ns4:getCollectiveTaskResponse/ns4:collectiveTask/ns4:generalInformation"    >

Number:<xsl:value-of select="number"/>
Title:<xsl:value-of select="title"/>
Name:<xsl:value-of select="name"/>

</xsl:template>

</xsl:stylesheet>
</code>```

答:
You have not a template matching / so XSLT's built-in template rules kick in. These will effectively match nodes and then select templates for the child nodes. So eventually your junk nodes will be selected, and the built-in template will then output text nodes where it files them.

There are a number of ways to solve your particular problem. You can add a template to ignore junk nodes...

```<code> <xsl:template match="junk" />
</code>```

Or, if you have lots of such nodes, you can add a template to ignore all text nodes

```<code><xsl:template match="text()" />
</code>```

Or you could add a template match for / and then explicitly select only the node you wanted....

```<code><xsl:template match="/">
    <xsl:apply-templates select="ns4:getCollectiveTaskResponse/ns4:collectiveTask/ns4:generalInformation" />
</xsl:template>

<xsl:template match="ns4:generalInformation">
Number:<xsl:value-of select="number"/>
Title:<xsl:value-of select="title"/>
Name:<xsl:value-of select="name"/>
</xsl:template>
</code>```

Body:
I am trying to take a large XML file and pull only a few tagged elements from it. I thought that I used the template match tag to get into the subclass that I wanted (subClass isn't the right word, but I am coming from this from an RDF/OWL standpoint), but it doesn't seem to filter out the things that are not in that subclass. Here is the code:

XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <ns4:getCollectiveTaskResponse
xmlns:ns1="http://sample.com/xsd/task/1.0"
xmlns:ns2="http://sample.com/xsd/commonElements/1.0"     xmlns:ns3="http://sample.com/xsd/individualTask/1.0"     xmlns:ns4="http://sample.com/xsd/collectiveTask/1.0"
xmlns:ns5="http://sample.com/xsd/handle"
xmlns:ns6="http://sample.com/appinfo/1">
<ns4:collectiveTask>
    <ns4:generalInformation>
        <number>13</number>
        <title>Quarterback</title>
        <name>Dan Marino</name>

    </ns4:generalInformation>

        <junk>I don't want this</junk>

</ns4:collectiveTask>

        <junk>I don't want this either</junk>
</ns4:getCollectiveTaskResponse>

XSL:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:ns1="http://sample.com/xsd/task/1.0"
xmlns:ns2="http://sample.com/xsd/commonElements/1.0"     xmlns:ns3="http://sample.com/xsd/individualTask/1.0"     xmlns:ns4="http://sample.com/xsd/collectiveTask/1.0"
xmlns:ns5="http://sample.com/xsd/handle"
xmlns:ns6="http://sample.com/appinfo/1">

<xsl:template     match="/ns4:getCollectiveTaskResponse/ns4:collectiveTask/ns4:generalInformation"    >

Number:<xsl:value-of select="number"/>
Title:<xsl:value-of select="title"/>
Name:<xsl:value-of select="name"/>

</xsl:template>

</xsl:stylesheet>

Body:
You have not a template matching / so XSLT's built-in template rules kick in. These will effectively match nodes and then select templates for the child nodes. So eventually your junk nodes will be selected, and the built-in template will then output text nodes where it files them.

There are a number of ways to solve your particular problem. You can add a template to ignore junk nodes...

 <xsl:template match="junk" />

Or, if you have lots of such nodes, you can add a template to ignore all text nodes

<xsl:template match="text()" />

Or you could add a template match for / and then explicitly select only the node you wanted....

<xsl:template match="/">
    <xsl:apply-templates select="ns4:getCollectiveTaskResponse/ns4:collectiveTask/ns4:generalInformation" />
</xsl:template>

<xsl:template match="ns4:generalInformation">
Number:<xsl:value-of select="number"/>
Title:<xsl:value-of select="title"/>
Name:<xsl:value-of select="name"/>
</xsl:template>


来源: stackexchange

问:
Store a pointer to a non-specified size array
I have a function like this:

```<code>void Menu_show(uint8_t count, char items[][UI_COLS + 1]);
</code>```

where count is the length of the first dimension of the array items.
I call this function in this way:

```<code>#define MAX_SIZE 4
char items[MAX_SIZE ][UI_COLS + 1];

for (uint8_t i = 0; i < MAX_SIZE ; i++) sprintf(items[i], "%u", i);
...
Menu_show(MAX_SIZE, items);
</code>```

It works, but now I need to store a pointer to the first element of the array in my function.

My tougths:

the first element is items[0][0]

its pointer is &items[0][0]

but now I have a pointer to a char, not to a bidimensional array

In fact, something like printf(items[3]) doesn't work in this way.
Then, I thought that the pointer to the first element of the second (fixed) dimension is &item[0] but:

```<code>char *_items[UI_COLS + 1];
_items = &items[0];
</code>```

gives an error:

assignment to expression with array type

I don't understand the right syntax to keep the bidimensional array usage when store the first location in a pointer.

答:
The way you defined _items is as an array of char *.  You're attempting to assign to that array (which by itself is illegal) a pointer to an array.

Since each element of items is an array of type char [UI_COLS + 1], you need to save its address in a pointer to an array:

```<code>char (*_items)[UI_COLS + 1] = &items[0];
printf("_items=%s\n", *_items);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function like this:

void Menu_show(uint8_t count, char items[][UI_COLS + 1]);

where count is the length of the first dimension of the array items.
I call this function in this way:

#define MAX_SIZE 4
char items[MAX_SIZE ][UI_COLS + 1];

for (uint8_t i = 0; i < MAX_SIZE ; i++) sprintf(items[i], "%u", i);
...
Menu_show(MAX_SIZE, items);

It works, but now I need to store a pointer to the first element of the array in my function.

My tougths:

the first element is items[0][0]

its pointer is &items[0][0]

but now I have a pointer to a char, not to a bidimensional array

In fact, something like printf(items[3]) doesn't work in this way.
Then, I thought that the pointer to the first element of the second (fixed) dimension is &item[0] but:

char *_items[UI_COLS + 1];
_items = &items[0];

gives an error:

assignment to expression with array type

I don't understand the right syntax to keep the bidimensional array usage when store the first location in a pointer.

Body:
The way you defined _items is as an array of char *.  You're attempting to assign to that array (which by itself is illegal) a pointer to an array.

Since each element of items is an array of type char [UI_COLS + 1], you need to save its address in a pointer to an array:

char (*_items)[UI_COLS + 1] = &items[0];
printf("_items=%s\n", *_items);


问:
Celery workers unable to connect to redis on docker instances
I have a dockerized setup running a Django app within which I use Celery tasks. Celery uses Redis as the broker.

Versioning:

Docker version 17.09.0-ce, build afdb6d4

docker-compose version 1.15.0, build e12f3b9

Django==1.9.6

django-celery-beat==1.0.1

celery==4.1.0

celery[redis]

redis==2.10.5

Problem:

My celery workers appear to be unable to connect to the redis container located at localhost:6379. I am able to telnet into the redis server on the specified port. I am able to verify redis-server is running on the container.

When I manually connect to the Celery docker instance and attempt to create a worker using the command celery -A backend worker -l info I get the notice:

[2017-11-13 18:07:50,937: ERROR/MainProcess] consumer: Cannot connect to redis://localhost:6379/0: Error 99 connecting to localhost:6379. Cannot assign requested address..
Trying again in 4.00 seconds...

Notes:

I am able to telnet in to the redis container on port 6379. On the redis container, redis-server is running.

Is there anything else that I'm missing? I've gone pretty far down the rabbit hole, but feel like I'm missing something really simple.

DOCKER CONFIG FILES:

docker-compose.common.yml here

docker-compose.dev.yml here

答:
When you use docker-compose, you aren't going to be using localhost for inter-container communication, you would be using the compose-assigned hostname of the container. In this case, the hostname of your redis container is redis. The top level elements under services: are your default host names.

So for celery to connect to redis, you should try redis://redis:6379/0. Since the protocol and the service name are the same, I'll elaborate a little more: if you named your redis service "butter-pecan-redis" in your docker-compose, you would instead use redis://butter-pecan-redis:6379/0.

Also, docker-compose.dev.yml doesn't appear to have celery and redis on a common network, which might cause them not to be able to see each other. I believe they need to share at least one network in common to be able to resolve their respective host names.

Networking in docker-compose has an example in the first handful of paragraphs, with a docker-compose.yml to look at.


问:
Cancel event on input type="file"
I am working with a standard file input for uploads, and I am looking for a way to attach a function to an event when the user clicks/hits enter on the "cancel" button (or escapes out from) the choose file dialog.

I can't find any events that work across all browsers and platforms consistently.

I've read the answers to this question: Capturing cancel event on input type=file but they don't work, as the change event doesn't fire in most browsers on canceling out of the choose file dialog.

I'm looking for a pure js solution, but open to jquery solutions as well.

Anyone solve this problem successfully?

答:
I had the problem where I clicked the cancel button on the input type="file" element and wanted the function to do nothing. if something was selected and I clicked the open button then I wanted my function to do something. The example only shows the method, I stripped out what I do with it after it opens. I put in the alerts just so you could see there isn't a filename coming back from the dialog when cancel is clicked.
Here is a method I use, it is simple but it works.

 function openFileOnClick(){
    document.getElementById("fileSelector").value = "";
    document.getElementById("fileSelector").files.length = 0;
    document.getElementById("fileSelector").click();
    if(document.getElementById("fileSelector").files.length >= 1){
        alert(document.getElementById("fileSelector").value);
        //Do something
    }
    else{
        alert(document.getElementById("fileSelector").value);
        //Cancel button has been called.
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<input type="file" id="fileSelector" name="fileSelector" value="" style="display:none;"  />
<input type="button" value="Open File" name="openFile" onclick="openFileOnClick();" />
</body>
</html></code>```

Title: Cancel event on input type="file"

Body:
I had the problem where I clicked the cancel button on the input type="file" element and wanted the function to do nothing. if something was selected and I clicked the open button then I wanted my function to do something. The example only shows the method, I stripped out what I do with it after it opens. I put in the alerts just so you could see there isn't a filename coming back from the dialog when cancel is clicked.
Here is a method I use, it is simple but it works.

 function openFileOnClick(){
    document.getElementById("fileSelector").value = "";
    document.getElementById("fileSelector").files.length = 0;
    document.getElementById("fileSelector").click();
    if(document.getElementById("fileSelector").files.length >= 1){
        alert(document.getElementById("fileSelector").value);
        //Do something
    }
    else{
        alert(document.getElementById("fileSelector").value);
        //Cancel button has been called.
    }
}

<html>
<head>
</head>
<body>
<input type="file" id="fileSelector" name="fileSelector" value="" style="display:none;"  />
<input type="button" value="Open File" name="openFile" onclick="openFileOnClick();" />
</body>
</html>


问:
Running `composer require ...` fails on post process cache clearing step
I can't seem to be able to complete installation of bundles using

composer require <bundle-name> because of these errors:

[Symfony\Component\Filesystem\Exception\IOException]   Failed to
  remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ

  I1q9aB": .

Complete console output of error:

Generating autoload files ocramius/package-versions:  Generating
  version class... ocramius/package-versions: ...done generating version
  class

Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
    Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

// Clearing the cache for the dev environment with debug  // true

Symfony\Component\Filesystem\Exception\IOException]   Failed to
  remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ

  I1q9aB": .

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--]

Script
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache
  handling the post-update-cmd event terminated with an exception

Installation failed, reverting ./composer.json to its original
  content.

[RuntimeException]   An error occurred when executing the
  "'cache:clear --no-warmup'" command:    // Clearing the cache for the
  dev environment with debug    // true

[Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ
  I1q9aB": .

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-e|--env ENV]   [--no-debug] [--]

Tried running composer with both sudo and without.
The command that I ran is: $ sudo composer require javiereguiluz/easyadmin-bundle

Not sure what to do about this, any help is appreciated.

Update

My environment is Ubuntu on Vagrant VM on Mac OS X.

答:
The directory ./de~/ is the old /dev/ directory, as it has been moved ready to be deleted. The /pools/ directory is the cache that is being built during the run of the application. On the initial startup, it's using one user-account, but the webserver is running another, and so the original user account does not have permission to delete some files.

The easy way around this - in the dev environment at least - is to sudo rm -rf .../de~. When I do remove old versions of code on prod, I'll often have to do the same because there was more than just the original deploying user, writing to the cache directory.


问:
Issue with more-than using Unix in Python
So I've been working on a script that calculates what seasonal event the current time is closer to, but I've ran into some issues regarding how to actually check. And before I get someone saying - "Yo, you know there's some easier way to pull the start off by using while loops?!" - I know, but that's really not what I asked. I just wanna see if there's any way to actually get the function to work correctly.

```<code>import datetime
yearlist = []
monthlist = []
daylist = []
holidaylist = []
#all of the time lists correspond to the ammount of years since 1970 - so, for instance, if you type that you were born in 2003, the number of seconds, displayed here
#will be yearlist[33], or 1041379200 seconds.
yearlist.append(0)#1970
yearlist.append(31536000)
yearlist.append(63072000)
yearlist.append(94694400)
yearlist.append(126230400)
yearlist.append(157766400)
yearlist.append(189302400)
yearlist.append(220924800)
yearlist.append(252460800)
yearlist.append(283996800)
yearlist.append(315532800)
yearlist.append(347155200)
yearlist.append(378691200)
yearlist.append(410227200)
yearlist.append(441763200)
yearlist.append(473385600)
yearlist.append(504921600)
yearlist.append(536457600)
yearlist.append(567993600)
yearlist.append(599616000)
yearlist.append(631152000)
yearlist.append(662688000)
yearlist.append(694224000)
yearlist.append(725846400)
yearlist.append(757382400)
yearlist.append(788918400)
yearlist.append(820454400)
yearlist.append(852076800)
yearlist.append(883612800)
yearlist.append(915148800)
yearlist.append(946684800)
yearlist.append(978307200)
yearlist.append(1009843200)
yearlist.append(1041379200)
yearlist.append(1072915200)
yearlist.append(1104537600)
yearlist.append(1136073600)
yearlist.append(1167609600)
yearlist.append(1199145600)
yearlist.append(1230768000)
yearlist.append(1262304000)
yearlist.append(1293840000)
yearlist.append(1325376000)
yearlist.append(1356998400)
yearlist.append(1388534400)
yearlist.append(1420070400)
yearlist.append(1451606400)
yearlist.append(1483228800)
yearlist.append(1514764800)
yearlist.append(1546300800)
yearlist.append(1577836800)
yearlist.append(1609459200)
yearlist.append(1640995200)
yearlist.append(1672531200)
yearlist.append(1704067200)
yearlist.append(1735689600)
yearlist.append(1767225600)
yearlist.append(1798761600)
yearlist.append(1830297600)
yearlist.append(1861920000)
yearlist.append(1893456000)
yearlist.append(1924992000)
yearlist.append(1956528000)
yearlist.append(1988150400)
yearlist.append(2019686400)
yearlist.append(2051222400)
yearlist.append(2082758400)
yearlist.append(2114380800)

monthlist.append(0)#january
monthlist.append(2592000)#february
monthlist.append(5184000)#march
monthlist.append(7776000)#arpril
monthlist.append(10368000)#may
monthlist.append(12960000)#june
monthlist.append(15552000)#july
monthlist.append(18144000)#august
monthlist.append(20736000)#september
monthlist.append(23328000)#october
monthlist.append(25920000)#november
monthlist.append(28512000)#december

daylist.append(0)#1
daylist.append(86400)#2
daylist.append(172800)#3
daylist.append(259200)#4
daylist.append(345600)#5
daylist.append(432000)#6
daylist.append(518400)#7
daylist.append(604800)#8
daylist.append(691200)#9
daylist.append(777600)#10
daylist.append(864000)#11
daylist.append(950400)#12
daylist.append(1036800)#13
daylist.append(1123200)#14
daylist.append(1209600)#15
daylist.append(1296000)#16
daylist.append(1382400)#17
daylist.append(1468800)#18
daylist.append(1555200)#19
daylist.append(1641600)#20
daylist.append(1728000)#21
daylist.append(1814400)#22
daylist.append(1900800)#23
daylist.append(1987200)#24
daylist.append(2073600)#25
daylist.append(2160000)#26
daylist.append(2246400)#27
daylist.append(2332800)#28
daylist.append(2419200)#29
daylist.append(2505600)#30
daylist.append(2592000)#31

#holiday list
holidaylist.append(30931200)#christmas

file = open("data.txt","a")
file.write("/Test write." + "\n")
time.sleep(2)
seconds=time.time()
print(seconds)
timedate=datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d %H:%M:%S:')
print(timedate)
file.write(timedate +"\n")
#time added

print("Hello, and welcome to the feel better about your life card generator - perfect for all of the depressives in your life.")
time.sleep(1)
name=input("OK, first things first. Have a name? ")
if name=="no":
    print("...")
    time.sleep(2)
    print("Oh.")
else:
    print(name + "? Jeez... I feel sorry for you.")
file.write("name = " + name + "\n")
    #check if time added

print("What about your Birthday - I'll be shocked if you don't have one!")
year=input("What was the year? ")
#year count starts here, btw
if year=="1970":
    birthyear=yearlist[0]+yearlist[0]
elif year=="1971":
    birthyear=yearlist[0]+yearlist[1]
elif year=="1972":
    birthyear=yearlist[0]+yearlist[2]
elif year=="1973":
    birthyear=yearlist[0]+yearlist[3]
elif year=="1974":
    birthyear=yearlist[0]+yearlist[4]
elif year=="1975":
    birthyear=yearlist[0]+yearlist[5]
elif year=="1976":
    birthyear=yearlist[0]+yearlist[6]
elif year=="1977":
    birthyear=yearlist[0]+yearlist[7]
elif year=="1978":
    birthyear=yearlist[0]+yearlist[8]
elif year=="1979":
    birthyear=yearlist[0]+yearlist[9]
elif year=="1980":
    birthyear=yearlist[0]+yearlist[10]
elif year=="1981":
    birthyear=yearlist[0]+yearlist[11]
elif year=="1982":
    birthyear=yearlist[0]+yearlist[12]
elif year=="1983":
    birthyear=yearlist[0]+yearlist[13]
elif year=="1984":
    birthyear=yearlist[0]+yearlist[14]
elif year=="1985":
    birthyear=yearlist[0]+yearlist[15]
elif year=="1986":
    birthyear=yearlist[0]+yearlist[16]
elif year=="1987":
    birthyear=yearlist[0]+yearlist[17]
elif year=="1988":
    birthyear=yearlist[0]+yearlist[18]
elif year=="1989":
    birthyear=yearlist[0]+yearlist[19]
elif year=="1990":
    birthyear=yearlist[0]+yearlist[20]
elif year=="1991":
    birthyear=yearlist[0]+yearlist[21]
elif year=="1992":
    birthyear=yearlist[0]+yearlist[22]
elif year=="1993":
    birthyear=yearlist[0]+yearlist[23]
elif year=="1994":
    birthyear=yearlist[0]+yearlist[24]
elif year=="1995":
    birthyear=yearlist[0]+yearlist[25]
elif year=="1996":
    birthyear=yearlist[0]+yearlist[26]
elif year=="1997":
    birthyear=yearlist[0]+yearlist[27]
elif year=="1998":
    birthyear=yearlist[0]+yearlist[28]
elif year=="1999":
    birthyear=yearlist[0]+yearlist[29]
elif year=="2000":
    birthyear=yearlist[0]+yearlist[30]
elif year=="2001":
    birthyear=yearlist[0]+yearlist[31]
elif year=="2002":
    birthyear=yearlist[0]+yearlist[32]
elif year=="2003":
    birthyear=yearlist[0]+yearlist[33]
elif year=="2004":
    birthyear=yearlist[0]+yearlist[34]
elif year=="2005":
    birthyear=yearlist[0]+yearlist[35]
elif year=="2006":
    birthyear=yearlist[0]+yearlist[36]
elif year=="2007":
    birthyear=yearlist[0]+yearlist[37]
elif year=="2008":
    birthyear=yearlist[0]+yearlist[38]
elif year=="2009":
    birthyear=yearlist[0]+yearlist[39]
elif year=="2010":
    birthyear=yearlist[0]+yearlist[40]
elif year=="2011":
    birthyear=yearlist[0]+yearlist[41]
elif year=="2012":
    birthyear=yearlist[0]+yearlist[42]
elif year=="2013":
    birthyear=yearlist[0]+yearlist[43]
elif year=="2014":
    birthyear=yearlist[0]+yearlist[44]
elif year=="2015":
    birthyear=yearlist[0]+yearlist[45]
elif year=="2016":
    birthyear=yearlist[0]+yearlist[46]
elif year=="2017":
    birthyear=yearlist[0]+yearlist[47]
elif year=="2018":
    birthyear=yearlist[0]+yearlist[48]
elif year=="2019":
    birthyear=yearlist[0]+yearlist[49]
elif year=="2020":
    birthyear=yearlist[0]+yearlist[50]
elif year=="2021":
    birthyear=yearlist[0]+yearlist[51]
elif year=="2022":
    birthyear=yearlist[0]+yearlist[52]
elif year=="2023":
    birthyear=yearlist[0]+yearlist[53]
elif year=="2024":
    birthyear=yearlist[0]+yearlist[54]
elif year=="2025":
    birthyear=yearlist[0]+yearlist[55]
elif year=="2026":
    birthyear=yearlist[0]+yearlist[56]
elif year=="2027":
    birthyear=yearlist[0]+yearlist[57]
elif year=="2028":
    birthyear=yearlist[0]+yearlist[58]
elif year=="2029":
    birthyear=yearlist[0]+yearlist[59]
elif year=="2030":
    birthyear=yearlist[0]+yearlist[60]
else:
    print("Damn, you're getting so old that even unix doesn't support your existence.")
    time.sleep(1)
    print("What else can I say? I'm not gonna make the counter go negative, that'll make me have to re-write most of this.")
    time.sleep(2)
    print("Go on then, leave. You broke it by being old. Congrats.")

time.sleep(1)

month=input("What month? ")
if month=="january":
    birthyearmonth = birthyear+monthlist[0]
    birthmonth = 0 + monthlist[0]
elif month=="february":
    birthyearmonth = birthyear+monthlist[1]
    birthmonth = 0 + monthlist[1]
elif month=="march":
    birthyearmonth = birthyear+monthlist[2]
    birthmonth = 0 + monthlist[2]
elif month=="april":
    birthyearmonth = birthyear+monthlist[3]
    birthmonth = 0 + monthlist[3]
elif month=="may":
    birthyearmonth = birthyear+monthlist[4]
    birthmonth = 0 + monthlist[4]
elif month=="june":
    birthyearmonth = birthyear+monthlist[5]
    birthmonth = 0 + monthlist[5]
elif month=="july":
    birthyearmonth = birthtyear+monthlist[6]
    birthmonth = 0 + monthlist[6]
elif month=="august":
    birthyearmonth = birthyear+monthlist[7]
    birthmonth = 0 + monthlist[7]
elif month=="september":
    birthyearmonth = birthyear+monthlist[8]
    birthmonth = 0 + monthlist[8]
elif month=="october":
    birthyearmonth = birthyear+monthlist[9]
    birthmonth = 0 + monthlist[9]
elif month=="november":
    birthyearmonth = birthyear+monthlist[10]
    birthmonth = 0 + monthlist[10]
elif month=="december":
    birthyearmonth = birthyear+monthlist[11]
    birthmonth = 0 + monthlist[11]
else:
    time.sleep(1)
    print("...of course you mistyped something. Typical.")
    time.sleep(1)
    print("Right, reset the shell - c'mon, this was you're fault.")
#That's the end of the month and year thing, future Laz.

time.sleep(1)
print("So - thus far we've got the year, and month. Logically, next is the day.")
time.sleep(2)
day=input("So, what date was it? ")
#here's the start of the final hurdle, Laz - don't mess this up.
if day=="1":
      birthfull = birthyearmonth+1+daylist[0]
      birthmonthday = birthmonth+daylist[0]
elif day=="2":
      birthfull = birthyearmonth+daylist[1]
      birthmonthday = birthmonth+daylist[1]
elif day=="3":
      birthfull = birthyearmonth+daylist[2]
      birthmonthday = birthmonth+daylist[2]
elif day=="4":
      birthfull = birthyearmonth+daylist[3]
      birthmonthday = birthmonth+daylist[3]
elif day=="5":
      birthfull = birthyearmonth+daylist[4]
      birthmonthday = birthmonth+daylist[4]
elif day=="6":
      birthfull = birthyearmonth+daylist[5]
      birthmonthday = birthmonth+daylist[5]
elif day=="7":
      birthfull = birthyearmonth+daylist[6]
      birthmonthday = birthmonth+daylist[6]
elif day=="8":
      birthfull = birthyearmonth+daylist[7]
      birthmonthday = birthmonth+daylist[7]
elif day=="9":
      birthfull = birthyearmonth+daylist[8]
      birthmonthday = birthmonth+daylist[8]
elif day=="10":
      birthfull = birthyearmonth+daylist[9]
      birthmonthday = birthmonth+daylist[9]
elif day=="11":
      birthfull = birthyearmonth+daylist[10]
      birthmonthday = birthmonth+daylist[10]
elif day=="12":
      birthfull = birthyearmonth+daylist[11]
      birthmonthday = birthmonth+daylist[11]
elif day=="13":
      birthfull = birthyearmonth+daylist[12]
      birthmonthday = birthmonth+daylist[12]
elif day=="14":
      birthfull = birthyearmonth+daylist[13]
      birthmonthday = birthmonth+daylist[13]
elif day=="15":
      birthfull = birthyearmonth+daylist[14]
      birthmonthday = birthmonth+daylist[14]
elif day=="16":
      birthfull = birthyearmonth+daylist[15]
      birthmonthday = birthmonth+daylist[15]
elif day=="17":
      birthfull = birthyearmonth+daylist[16]
      birthmonthday = birthmonth+daylist[16]
elif day=="18":
      birthfull = birthyearmonth+daylist[17]
      birthmonthday = birthmonth+daylist[17]
elif day=="19":
      birthfull = birthyearmonth+daylist[18]
      birthmonthday = birthmonth+daylist[18]
elif day=="20":
      birthfull = birthyearmonth+daylist[19]
      birthmonthday = birthmonth+daylist[19]
elif day=="21":
      birthfull = birthyearmonth+daylist[20]
      birthmonthday = birthmonth+daylist[20]
elif day=="22":
      birthfull = birthyearmonth+daylist[21]
      birthmonthday = birthmonth+daylist[21]
elif day=="23":
      birthfull = birthyearmonth+daylist[22]
      birthmonthday = birthmonth+daylist[22]
elif day=="24":
      birthfull = birthyearmonth+daylist[23]
      birthmonthday = birthmonth+daylist[23]
elif day=="25":
      birthfull = birthyearmonth+daylist[24]
      birthmonthday = birthmonth+daylist[24]
elif day=="26":
      birthfull = birthyearmonth+daylist[25]
      birthmonthday = birthmonth+daylist[25]
elif day=="27":
      birthfull = birthyearmonth+daylist[26]
      birthmonthday = birthmonth+daylist[26]
elif day=="28":
      birthfull = birthyearmonth+daylist[27]
      birthmonthday = birthmonth+daylist[27]
elif day=="29":
      birthfull = birthyearmonth+daylist[28]
      birthmonthday = birthmonth+daylist[28]
elif day=="30":
      birthfull = birthyearmonth+daylist[29]
      birthmonthday = birthmonth+daylist[29]
elif day=="31":
      birthfull = birthyearmonth+daylist[30]
      birthmonthday = birthmonth+daylist[30]
print(birthmonthday)
#Oooh, that was WAY harder to write than the year list.
if name=="admin":
    print("Whoops, I should've removed this - BUT SINCE IT HAS ACTUAL PURPOSE I GUESS NOT")
else:
    datetime1970 = int(seconds - yearlist[47])
    christmasfinal = holidaylist[0] - datetime1970
    print(christmasfinal)

birthactual=datetime.datetime.fromtimestamp(birthfull).strftime('%Y-%m-%d %H:%M:%S:')
print(birthactual)

if birthmonthday>christmasfinal:
    print("Christmas is closer. Also you gotta work on that card")

elif birthmonthday<christmasfinal:
    print("Birthday's closer, ya dingus")
</code>```

And yes, I know I'm terrible at this.

And yes, this is my first Python project - it really shows.

EDIT: the problem with the code is that it constantly tells me that Christmas is closer, even if the provided date isn't. Also I should say that the final birth date isn't perfect (a few days out), but close enough to the point that it shouldn't matter to the user. Sorry for not clarifying.

答:
You're not comparing the right values. birthmonthday is the number of seconds from the beginning of the year until the user's birthday. christmasfinal is the number of seconds from now until Christmas. It makes little sense to compare these to each other. If you want to know which is closer, you need to subtract birthmonthday from datetime1970 (the name of this variable is very weird, since it's the number of seconds from the beginning of 2017, not 1970), and compare that to christmasfinal. You also need to use the absolute value of the differences, since one could be negative and the other positive.

```<code>seconds_to_birthday = birthmonthday - datetime1970
if (abs(seconds_to_birthday) > abs(christmasfinal)):
    print("Christmas is closer. Also you gotta work on that card")
elif (abs(seconds_to_birthday) < abs(christmasfinal)):
    print("Birthday's closer, ya dingus")
else:
    print("We're exactly halfway between birthday and Christmas, you decide what to do")
</code>```

Body:
So I've been working on a script that calculates what seasonal event the current time is closer to, but I've ran into some issues regarding how to actually check. And before I get someone saying - "Yo, you know there's some easier way to pull the start off by using while loops?!" - I know, but that's really not what I asked. I just wanna see if there's any way to actually get the function to work correctly.

import datetime
yearlist = []
monthlist = []
daylist = []
holidaylist = []
#all of the time lists correspond to the ammount of years since 1970 - so, for instance, if you type that you were born in 2003, the number of seconds, displayed here
#will be yearlist[33], or 1041379200 seconds.
yearlist.append(0)#1970
yearlist.append(31536000)
yearlist.append(63072000)
yearlist.append(94694400)
yearlist.append(126230400)
yearlist.append(157766400)
yearlist.append(189302400)
yearlist.append(220924800)
yearlist.append(252460800)
yearlist.append(283996800)
yearlist.append(315532800)
yearlist.append(347155200)
yearlist.append(378691200)
yearlist.append(410227200)
yearlist.append(441763200)
yearlist.append(473385600)
yearlist.append(504921600)
yearlist.append(536457600)
yearlist.append(567993600)
yearlist.append(599616000)
yearlist.append(631152000)
yearlist.append(662688000)
yearlist.append(694224000)
yearlist.append(725846400)
yearlist.append(757382400)
yearlist.append(788918400)
yearlist.append(820454400)
yearlist.append(852076800)
yearlist.append(883612800)
yearlist.append(915148800)
yearlist.append(946684800)
yearlist.append(978307200)
yearlist.append(1009843200)
yearlist.append(1041379200)
yearlist.append(1072915200)
yearlist.append(1104537600)
yearlist.append(1136073600)
yearlist.append(1167609600)
yearlist.append(1199145600)
yearlist.append(1230768000)
yearlist.append(1262304000)
yearlist.append(1293840000)
yearlist.append(1325376000)
yearlist.append(1356998400)
yearlist.append(1388534400)
yearlist.append(1420070400)
yearlist.append(1451606400)
yearlist.append(1483228800)
yearlist.append(1514764800)
yearlist.append(1546300800)
yearlist.append(1577836800)
yearlist.append(1609459200)
yearlist.append(1640995200)
yearlist.append(1672531200)
yearlist.append(1704067200)
yearlist.append(1735689600)
yearlist.append(1767225600)
yearlist.append(1798761600)
yearlist.append(1830297600)
yearlist.append(1861920000)
yearlist.append(1893456000)
yearlist.append(1924992000)
yearlist.append(1956528000)
yearlist.append(1988150400)
yearlist.append(2019686400)
yearlist.append(2051222400)
yearlist.append(2082758400)
yearlist.append(2114380800)

monthlist.append(0)#january
monthlist.append(2592000)#february
monthlist.append(5184000)#march
monthlist.append(7776000)#arpril
monthlist.append(10368000)#may
monthlist.append(12960000)#june
monthlist.append(15552000)#july
monthlist.append(18144000)#august
monthlist.append(20736000)#september
monthlist.append(23328000)#october
monthlist.append(25920000)#november
monthlist.append(28512000)#december

daylist.append(0)#1
daylist.append(86400)#2
daylist.append(172800)#3
daylist.append(259200)#4
daylist.append(345600)#5
daylist.append(432000)#6
daylist.append(518400)#7
daylist.append(604800)#8
daylist.append(691200)#9
daylist.append(777600)#10
daylist.append(864000)#11
daylist.append(950400)#12
daylist.append(1036800)#13
daylist.append(1123200)#14
daylist.append(1209600)#15
daylist.append(1296000)#16
daylist.append(1382400)#17
daylist.append(1468800)#18
daylist.append(1555200)#19
daylist.append(1641600)#20
daylist.append(1728000)#21
daylist.append(1814400)#22
daylist.append(1900800)#23
daylist.append(1987200)#24
daylist.append(2073600)#25
daylist.append(2160000)#26
daylist.append(2246400)#27
daylist.append(2332800)#28
daylist.append(2419200)#29
daylist.append(2505600)#30
daylist.append(2592000)#31

#holiday list
holidaylist.append(30931200)#christmas

file = open("data.txt","a")
file.write("/Test write." + "\n")
time.sleep(2)
seconds=time.time()
print(seconds)
timedate=datetime.datetime.fromtimestamp(seconds).strftime('%Y-%m-%d %H:%M:%S:')
print(timedate)
file.write(timedate +"\n")
#time added

print("Hello, and welcome to the feel better about your life card generator - perfect for all of the depressives in your life.")
time.sleep(1)
name=input("OK, first things first. Have a name? ")
if name=="no":
    print("...")
    time.sleep(2)
    print("Oh.")
else:
    print(name + "? Jeez... I feel sorry for you.")
file.write("name = " + name + "\n")
    #check if time added

print("What about your Birthday - I'll be shocked if you don't have one!")
year=input("What was the year? ")
#year count starts here, btw
if year=="1970":
    birthyear=yearlist[0]+yearlist[0]
elif year=="1971":
    birthyear=yearlist[0]+yearlist[1]
elif year=="1972":
    birthyear=yearlist[0]+yearlist[2]
elif year=="1973":
    birthyear=yearlist[0]+yearlist[3]
elif year=="1974":
    birthyear=yearlist[0]+yearlist[4]
elif year=="1975":
    birthyear=yearlist[0]+yearlist[5]
elif year=="1976":
    birthyear=yearlist[0]+yearlist[6]
elif year=="1977":
    birthyear=yearlist[0]+yearlist[7]
elif year=="1978":
    birthyear=yearlist[0]+yearlist[8]
elif year=="1979":
    birthyear=yearlist[0]+yearlist[9]
elif year=="1980":
    birthyear=yearlist[0]+yearlist[10]
elif year=="1981":
    birthyear=yearlist[0]+yearlist[11]
elif year=="1982":
    birthyear=yearlist[0]+yearlist[12]
elif year=="1983":
    birthyear=yearlist[0]+yearlist[13]
elif year=="1984":
    birthyear=yearlist[0]+yearlist[14]
elif year=="1985":
    birthyear=yearlist[0]+yearlist[15]
elif year=="1986":
    birthyear=yearlist[0]+yearlist[16]
elif year=="1987":
    birthyear=yearlist[0]+yearlist[17]
elif year=="1988":
    birthyear=yearlist[0]+yearlist[18]
elif year=="1989":
    birthyear=yearlist[0]+yearlist[19]
elif year=="1990":
    birthyear=yearlist[0]+yearlist[20]
elif year=="1991":
    birthyear=yearlist[0]+yearlist[21]
elif year=="1992":
    birthyear=yearlist[0]+yearlist[22]
elif year=="1993":
    birthyear=yearlist[0]+yearlist[23]
elif year=="1994":
    birthyear=yearlist[0]+yearlist[24]
elif year=="1995":
    birthyear=yearlist[0]+yearlist[25]
elif year=="1996":
    birthyear=yearlist[0]+yearlist[26]
elif year=="1997":
    birthyear=yearlist[0]+yearlist[27]
elif year=="1998":
    birthyear=yearlist[0]+yearlist[28]
elif year=="1999":
    birthyear=yearlist[0]+yearlist[29]
elif year=="2000":
    birthyear=yearlist[0]+yearlist[30]
elif year=="2001":
    birthyear=yearlist[0]+yearlist[31]
elif year=="2002":
    birthyear=yearlist[0]+yearlist[32]
elif year=="2003":
    birthyear=yearlist[0]+yearlist[33]
elif year=="2004":
    birthyear=yearlist[0]+yearlist[34]
elif year=="2005":
    birthyear=yearlist[0]+yearlist[35]
elif year=="2006":
    birthyear=yearlist[0]+yearlist[36]
elif year=="2007":
    birthyear=yearlist[0]+yearlist[37]
elif year=="2008":
    birthyear=yearlist[0]+yearlist[38]
elif year=="2009":
    birthyear=yearlist[0]+yearlist[39]
elif year=="2010":
    birthyear=yearlist[0]+yearlist[40]
elif year=="2011":
    birthyear=yearlist[0]+yearlist[41]
elif year=="2012":
    birthyear=yearlist[0]+yearlist[42]
elif year=="2013":
    birthyear=yearlist[0]+yearlist[43]
elif year=="2014":
    birthyear=yearlist[0]+yearlist[44]
elif year=="2015":
    birthyear=yearlist[0]+yearlist[45]
elif year=="2016":
    birthyear=yearlist[0]+yearlist[46]
elif year=="2017":
    birthyear=yearlist[0]+yearlist[47]
elif year=="2018":
    birthyear=yearlist[0]+yearlist[48]
elif year=="2019":
    birthyear=yearlist[0]+yearlist[49]
elif year=="2020":
    birthyear=yearlist[0]+yearlist[50]
elif year=="2021":
    birthyear=yearlist[0]+yearlist[51]
elif year=="2022":
    birthyear=yearlist[0]+yearlist[52]
elif year=="2023":
    birthyear=yearlist[0]+yearlist[53]
elif year=="2024":
    birthyear=yearlist[0]+yearlist[54]
elif year=="2025":
    birthyear=yearlist[0]+yearlist[55]
elif year=="2026":
    birthyear=yearlist[0]+yearlist[56]
elif year=="2027":
    birthyear=yearlist[0]+yearlist[57]
elif year=="2028":
    birthyear=yearlist[0]+yearlist[58]
elif year=="2029":
    birthyear=yearlist[0]+yearlist[59]
elif year=="2030":
    birthyear=yearlist[0]+yearlist[60]
else:
    print("Damn, you're getting so old that even unix doesn't support your existence.")
    time.sleep(1)
    print("What else can I say? I'm not gonna make the counter go negative, that'll make me have to re-write most of this.")
    time.sleep(2)
    print("Go on then, leave. You broke it by being old. Congrats.")

time.sleep(1)

month=input("What month? ")
if month=="january":
    birthyearmonth = birthyear+monthlist[0]
    birthmonth = 0 + monthlist[0]
elif month=="february":
    birthyearmonth = birthyear+monthlist[1]
    birthmonth = 0 + monthlist[1]
elif month=="march":
    birthyearmonth = birthyear+monthlist[2]
    birthmonth = 0 + monthlist[2]
elif month=="april":
    birthyearmonth = birthyear+monthlist[3]
    birthmonth = 0 + monthlist[3]
elif month=="may":
    birthyearmonth = birthyear+monthlist[4]
    birthmonth = 0 + monthlist[4]
elif month=="june":
    birthyearmonth = birthyear+monthlist[5]
    birthmonth = 0 + monthlist[5]
elif month=="july":
    birthyearmonth = birthtyear+monthlist[6]
    birthmonth = 0 + monthlist[6]
elif month=="august":
    birthyearmonth = birthyear+monthlist[7]
    birthmonth = 0 + monthlist[7]
elif month=="september":
    birthyearmonth = birthyear+monthlist[8]
    birthmonth = 0 + monthlist[8]
elif month=="october":
    birthyearmonth = birthyear+monthlist[9]
    birthmonth = 0 + monthlist[9]
elif month=="november":
    birthyearmonth = birthyear+monthlist[10]
    birthmonth = 0 + monthlist[10]
elif month=="december":
    birthyearmonth = birthyear+monthlist[11]
    birthmonth = 0 + monthlist[11]
else:
    time.sleep(1)
    print("...of course you mistyped something. Typical.")
    time.sleep(1)
    print("Right, reset the shell - c'mon, this was you're fault.")
#That's the end of the month and year thing, future Laz.

time.sleep(1)
print("So - thus far we've got the year, and month. Logically, next is the day.")
time.sleep(2)
day=input("So, what date was it? ")
#here's the start of the final hurdle, Laz - don't mess this up.
if day=="1":
      birthfull = birthyearmonth+1+daylist[0]
      birthmonthday = birthmonth+daylist[0]
elif day=="2":
      birthfull = birthyearmonth+daylist[1]
      birthmonthday = birthmonth+daylist[1]
elif day=="3":
      birthfull = birthyearmonth+daylist[2]
      birthmonthday = birthmonth+daylist[2]
elif day=="4":
      birthfull = birthyearmonth+daylist[3]
      birthmonthday = birthmonth+daylist[3]
elif day=="5":
      birthfull = birthyearmonth+daylist[4]
      birthmonthday = birthmonth+daylist[4]
elif day=="6":
      birthfull = birthyearmonth+daylist[5]
      birthmonthday = birthmonth+daylist[5]
elif day=="7":
      birthfull = birthyearmonth+daylist[6]
      birthmonthday = birthmonth+daylist[6]
elif day=="8":
      birthfull = birthyearmonth+daylist[7]
      birthmonthday = birthmonth+daylist[7]
elif day=="9":
      birthfull = birthyearmonth+daylist[8]
      birthmonthday = birthmonth+daylist[8]
elif day=="10":
      birthfull = birthyearmonth+daylist[9]
      birthmonthday = birthmonth+daylist[9]
elif day=="11":
      birthfull = birthyearmonth+daylist[10]
      birthmonthday = birthmonth+daylist[10]
elif day=="12":
      birthfull = birthyearmonth+daylist[11]
      birthmonthday = birthmonth+daylist[11]
elif day=="13":
      birthfull = birthyearmonth+daylist[12]
      birthmonthday = birthmonth+daylist[12]
elif day=="14":
      birthfull = birthyearmonth+daylist[13]
      birthmonthday = birthmonth+daylist[13]
elif day=="15":
      birthfull = birthyearmonth+daylist[14]
      birthmonthday = birthmonth+daylist[14]
elif day=="16":
      birthfull = birthyearmonth+daylist[15]
      birthmonthday = birthmonth+daylist[15]
elif day=="17":
      birthfull = birthyearmonth+daylist[16]
      birthmonthday = birthmonth+daylist[16]
elif day=="18":
      birthfull = birthyearmonth+daylist[17]
      birthmonthday = birthmonth+daylist[17]
elif day=="19":
      birthfull = birthyearmonth+daylist[18]
      birthmonthday = birthmonth+daylist[18]
elif day=="20":
      birthfull = birthyearmonth+daylist[19]
      birthmonthday = birthmonth+daylist[19]
elif day=="21":
      birthfull = birthyearmonth+daylist[20]
      birthmonthday = birthmonth+daylist[20]
elif day=="22":
      birthfull = birthyearmonth+daylist[21]
      birthmonthday = birthmonth+daylist[21]
elif day=="23":
      birthfull = birthyearmonth+daylist[22]
      birthmonthday = birthmonth+daylist[22]
elif day=="24":
      birthfull = birthyearmonth+daylist[23]
      birthmonthday = birthmonth+daylist[23]
elif day=="25":
      birthfull = birthyearmonth+daylist[24]
      birthmonthday = birthmonth+daylist[24]
elif day=="26":
      birthfull = birthyearmonth+daylist[25]
      birthmonthday = birthmonth+daylist[25]
elif day=="27":
      birthfull = birthyearmonth+daylist[26]
      birthmonthday = birthmonth+daylist[26]
elif day=="28":
      birthfull = birthyearmonth+daylist[27]
      birthmonthday = birthmonth+daylist[27]
elif day=="29":
      birthfull = birthyearmonth+daylist[28]
      birthmonthday = birthmonth+daylist[28]
elif day=="30":
      birthfull = birthyearmonth+daylist[29]
      birthmonthday = birthmonth+daylist[29]
elif day=="31":
      birthfull = birthyearmonth+daylist[30]
      birthmonthday = birthmonth+daylist[30]
print(birthmonthday)
#Oooh, that was WAY harder to write than the year list.
if name=="admin":
    print("Whoops, I should've removed this - BUT SINCE IT HAS ACTUAL PURPOSE I GUESS NOT")
else:
    datetime1970 = int(seconds - yearlist[47])
    christmasfinal = holidaylist[0] - datetime1970
    print(christmasfinal)

birthactual=datetime.datetime.fromtimestamp(birthfull).strftime('%Y-%m-%d %H:%M:%S:')
print(birthactual)

if birthmonthday>christmasfinal:
    print("Christmas is closer. Also you gotta work on that card")

elif birthmonthday<christmasfinal:
    print("Birthday's closer, ya dingus")

And yes, I know I'm terrible at this.

And yes, this is my first Python project - it really shows.

EDIT: the problem with the code is that it constantly tells me that Christmas is closer, even if the provided date isn't. Also I should say that the final birth date isn't perfect (a few days out), but close enough to the point that it shouldn't matter to the user. Sorry for not clarifying.

Body:
You're not comparing the right values. birthmonthday is the number of seconds from the beginning of the year until the user's birthday. christmasfinal is the number of seconds from now until Christmas. It makes little sense to compare these to each other. If you want to know which is closer, you need to subtract birthmonthday from datetime1970 (the name of this variable is very weird, since it's the number of seconds from the beginning of 2017, not 1970), and compare that to christmasfinal. You also need to use the absolute value of the differences, since one could be negative and the other positive.

seconds_to_birthday = birthmonthday - datetime1970
if (abs(seconds_to_birthday) > abs(christmasfinal)):
    print("Christmas is closer. Also you gotta work on that card")
elif (abs(seconds_to_birthday) < abs(christmasfinal)):
    print("Birthday's closer, ya dingus")
else:
    print("We're exactly halfway between birthday and Christmas, you decide what to do")


问:
Access 2013 Module in Windows Task Scheduler
I have tried using Windows Task Scheduler to run my Access Database module although I can't figure out how to create the macro for this as I believe this is the only way to do this.
The details I have are Program/script:"C:\Program Files\Microsoft Office\Office15\MSACCESS.EXE"Add Arguments(optional):"C:\deskop\Reports.accdb" /x AutoExec I have created a macro on my access database called AutoExec but I don't know how to call my module which is called Main.

My Module contains 5 different public functions and a Sub which I changed to Function. I have now added all 5 functions as RunCode and function name to the macro is this correct? it seems to be running the macro now.

答:
Macros can only call functions, not subs. As @marlan said, can have code in load event of a form set to open by default and the optional arguments not needed. Another alternative is Windows Task Scheduler calls a script file which has code to open db, call VBA procedure, and close db. Here is structure of a VBScript executable (file extension .vbs).</p>

```<code>Dim accessApp
set accessApp = CreateObject("Access.Application")
accessApp.OpenCurrentDataBase("your path/filename here")
accessApp.Run "your procedure name here"
accessApp.Quit
set accessApp = nothing
</code>```

Body:
Macros can only call functions, not subs. As @marlan said, can have code in load event of a form set to open by default and the optional arguments not needed. Another alternative is Windows Task Scheduler calls a script file which has code to open db, call VBA procedure, and close db. Here is structure of a VBScript executable (file extension .vbs).

Dim accessApp
set accessApp = CreateObject("Access.Application")
accessApp.OpenCurrentDataBase("your path/filename here")
accessApp.Run "your procedure name here"
accessApp.Quit
set accessApp = nothing


问:
Angular2 render sanitised string containing interpolation
I'm using the following string

"Today's product of the day is {{product_code}} !"

This string above, I've sanitized and bypassed security trusted HTML
this.DomSanitizer.bypassSecurityTrustHtml(str)

 and put in my template using [innerHTML].

However this string also contains interpolation {{product_code}} that should have been evaluated and rendered with its actual value, such that the output must be

"Today's product of the day is XYZ-52-TV !"

However, that does not happen, instead the string gets rendered as is with the interpolation's double curly braces and the variable name.

How can I fix this?

UPDATE

component template:

code for trustHTML():

```<code>  trustHTML(t){
    return this.DomSanitizer.bypassSecurityTrustHtml(t);
  }
</code>```

value of str :

"Today's product of the day is {{trustHTML(product_code)}} !"

output using this value that appears is (not desired output):

Today's product of the day is {{trustHTML(product_code)}} !

I also tried value of str :

"Today's product of the day is  !"

"Today's product of the day is product_code !"

答:
DomSanitizer#bypassSecurityTrustHtml is designed to be called from a component.

Knowing this, and knowing that you will have access to that complete string from wherever you call that sanitizer, just return the completely-built string from that function, à la

```<code>{{ sanitizeProductLink(productId) }}
</code>```

which itself returns the complete string "Today's product of the day is XYZ-52-TV !".

Additional, Vague Supposition:

It begs the question, though, why you are injecting a plain string into [innerHTML] to being with. I assume from context you are building some kind link, a more clean approach is to make a static template and pass in variables, like

```<code><span>Today's special is <a [link]="['special', product.id]">{{ product.name }}!</a></span>
</code>```

or some such implementation.

Body:
I'm using the following string

"Today's product of the day is {{product_code}} !"

This string above, I've sanitized and bypassed security trusted HTML
this.DomSanitizer.bypassSecurityTrustHtml(str)

 and put in my template using [innerHTML].

However this string also contains interpolation {{product_code}} that should have been evaluated and rendered with its actual value, such that the output must be

"Today's product of the day is XYZ-52-TV !"

However, that does not happen, instead the string gets rendered as is with the interpolation's double curly braces and the variable name.

How can I fix this?

UPDATE

component template:

code for trustHTML():

  trustHTML(t){
    return this.DomSanitizer.bypassSecurityTrustHtml(t);
  }

value of str :

"Today's product of the day is {{trustHTML(product_code)}} !"

output using this value that appears is (not desired output):

Today's product of the day is {{trustHTML(product_code)}} !

I also tried value of str :

"Today's product of the day is  !"

"Today's product of the day is product_code !"

Body:
DomSanitizer#bypassSecurityTrustHtml is designed to be called from a component.

Knowing this, and knowing that you will have access to that complete string from wherever you call that sanitizer, just return the completely-built string from that function, à la

{{ sanitizeProductLink(productId) }}

which itself returns the complete string "Today's product of the day is XYZ-52-TV !".

Additional, Vague Supposition:

It begs the question, though, why you are injecting a plain string into [innerHTML] to being with. I assume from context you are building some kind link, a more clean approach is to make a static template and pass in variables, like

<span>Today's special is <a [link]="['special', product.id]">{{ product.name }}!</a></span>

or some such implementation.


问:
Swift - SLComposeViewController automatically dismissing itself
I am using SLComposeViewController for social sharing of photos.But i am getting this error in log

SLComposeViewController automatically dismissing itself

My code:-

```<code>@IBAction func fbshare(_ sender:UIButton) {
    let vc = SLComposeViewController(forServiceType:SLServiceTypeFacebook)
    vc?.add(img.image!)
    vc?.add(URL(string: "http://www.example.com/"))
    vc?.setInitialText("Initial text here.")
    self.present(vc!, animated: true, completion: nil)
}
</code>```

I am not able to get the SLComposeViewController on my screen.

答:
This is working and for SLServiceTypeFacebook too but need to dismiss one to present the other. I am still working that out.</p>

```<code>if let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter) {

        //SLServiceTypeFacebook
        //SLServiceTypeTwitter

        vc.setInitialText(self.writeDBString)
        //vc.add(UIImage(named: "myImage.jpg")!)
        vc.add(URL(string: "https://itunes.apple.com/us/app"))
        present(vc, animated: true )
}
</code>```

Body:
I am using SLComposeViewController for social sharing of photos.But i am getting this error in log

SLComposeViewController automatically dismissing itself

My code:-

@IBAction func fbshare(_ sender:UIButton) {
    let vc = SLComposeViewController(forServiceType:SLServiceTypeFacebook)
    vc?.add(img.image!)
    vc?.add(URL(string: "http://www.example.com/"))
    vc?.setInitialText("Initial text here.")
    self.present(vc!, animated: true, completion: nil)
}

I am not able to get the SLComposeViewController on my screen.

Body:
This is working and for SLServiceTypeFacebook too but need to dismiss one to present the other. I am still working that out.

if let vc = SLComposeViewController(forServiceType: SLServiceTypeTwitter) {

        //SLServiceTypeFacebook
        //SLServiceTypeTwitter

        vc.setInitialText(self.writeDBString)
        //vc.add(UIImage(named: "myImage.jpg")!)
        vc.add(URL(string: "https://itunes.apple.com/us/app"))
        present(vc, animated: true )
}


问:
Haskell couldn't match expected type float with actual type 'a'
I have run into a problem when trying to add 2 parts of a tuple together

Function Type:

```<code>close :: (Floating a, Ord a) => (a,a) -> (a,a) -> Float
</code>```

Function definition:

```<code>close y x = sqrt (((fromIntegral(snd x) - fromIntegral(snd y))^2) + ((fromIntegral(fst x) - fromIntegral(fst y)^2)))
</code>```

On feeding the function a y tuple of format ( , ) and a x tuple of format ( , ) it should calculate the distance between two coordinates.
However on launch I get an error of:

```<code>Couldn't match expected type 'Float' with actual type 'a'
a is a rigid type variable bound by...
</code>```

I do understand why the problem is arising, but I have no idea how to fix it

答: One technique to help you debug this would be to comment out your type signature and ask the system what the type is. In ghci, that'll be <code>:t close</code>. </p>

Body:
I have run into a problem when trying to add 2 parts of a tuple together

Function Type:

close :: (Floating a, Ord a) => (a,a) -> (a,a) -> Float

Function definition:

close y x = sqrt (((fromIntegral(snd x) - fromIntegral(snd y))^2) + ((fromIntegral(fst x) - fromIntegral(fst y)^2)))

On feeding the function a y tuple of format ( , ) and a x tuple of format ( , ) it should calculate the distance between two coordinates.
However on launch I get an error of:

Couldn't match expected type 'Float' with actual type 'a'
a is a rigid type variable bound by...

I do understand why the problem is arising, but I have no idea how to fix it

Body: One technique to help you debug this would be to comment out your type signature and ask the system what the type is. In ghci, that'll be :t close.


问:
function that calls to author functions (python)
I'm trying to make a map that takes a function that calls other functions, and a list of functions - so here is what I've put in:

```<code>    def function1():
      return 3

    def function2():
      return 4

    def List_Of_Functions(My_Function):
      return My_Function

    print(list(map(List_Of_Functions, [function1, function2])))
</code>```

but this is what I get in the result:

```<code>[<function function1 at 0x7f5e6797a620>, <function function2 at 0x7f5e6797a730>]
</code>```

I'm new to Python so any explanation would be much appreciated.

答:
Nowhere in the code you are calling any of the functions function1 or function2.

I think what you are after is by amending the middle method to become:

```<code>  def List_Of_Functions(My_Function):
     return My_Function()
</code>```

Without the parentheses after the My_Function, it's just passing a reference to the function and doing nothing with it.
Adding the parentheses - it's calling the function.

Body:
I'm trying to make a map that takes a function that calls other functions, and a list of functions - so here is what I've put in:

    def function1():
      return 3

    def function2():
      return 4

    def List_Of_Functions(My_Function):
      return My_Function

    print(list(map(List_Of_Functions, [function1, function2])))

but this is what I get in the result:

[<function function1 at 0x7f5e6797a620>, <function function2 at 0x7f5e6797a730>]

I'm new to Python so any explanation would be much appreciated.

Body:
Nowhere in the code you are calling any of the functions function1 or function2.

I think what you are after is by amending the middle method to become:

  def List_Of_Functions(My_Function):
     return My_Function()

Without the parentheses after the My_Function, it's just passing a reference to the function and doing nothing with it.
Adding the parentheses - it's calling the function.


问:
split a word from string and save it in a variable
I've a question.
I have a string, like this:
hello, I am a string, -how are you?-.

And I want to put any text in - - sign in another variable and remove it from original string (in short: cut it!).

How can I do it? I should do it with preg_match or preg_split?

If you help me, I will grateful to you!

答:
It's really two separate operations, but you can use the same pattern for both

```<code>$str = "hello, I am a string, -how are you?-";
$pattern = "/-(.*?)-/";

if ( preg_match( $pattern, $str, $matches ) )
{
  $matched = $matches[1];
  $str = preg_replace( $pattern, '', $str );

  echo $matched, PHP_EOL, $str;
}
</code>```

Note that this assumes that (and therefore only works when) only one section of text is demarcated by -

ContentLicense: CC BY-SA 2.5

Body:
It's really two separate operations, but you can use the same pattern for both

$str = "hello, I am a string, -how are you?-";
$pattern = "/-(.*?)-/";

if ( preg_match( $pattern, $str, $matches ) )
{
  $matched = $matches[1];
  $str = preg_replace( $pattern, '', $str );

  echo $matched, PHP_EOL, $str;
}

Note that this assumes that (and therefore only works when) only one section of text is demarcated by -


问:
Issue with yield in nested workflow
I'm trying to write my own Either builder as part of my quest to learn computation expressions in f#, but I have hit a wall with what I think is issue with Combine method. My code so far:

```<code>type Result<'a> =
    | Failure
    | Success of 'a

type EitherBuilder() =
    member this.Bind(m,f) =
        match m with
        | Failure -> Failure
        | Success(x) -> f x
    member this.Yield x =
        Success(x)
    member this.YieldFrom x =
        x
    member this.Combine(a,b) =
        match a with
        | Success(_) -> a
        | Failure -> b()
    member this.Delay y =
        fun () -> y()
    member this.Run(func) =
        func()
</code>```

With this code I test the Combine with two tests:

```<code>let either = new EitherBuilder()
...
testCase "returns success from 3 yields" <|
    fun _ ->
        let value = either {
            yield! Failure
            yield 4
            yield! Failure
            }
        value |> should equal (Success(4))
testCase "returns success with nested workflows" <|
    fun _ ->
        let value = either {
            let! x = either {
                yield! Failure
                }
            yield 5
            }
        value |> should equal (Success(5))
</code>```

The first test passes, as I would expect, but the second test fails with following message:

Exception thrown: 'NUnit.Framework.AssertionException' in
  nunit.framework.dll either tests/returns success with nested workflows:
  Failed:    Expected: <Success 5>   But was:  <Failure>

I don't get it. The x is not yielded, so why does it influence my parent workflow? If I move let! below yield the test passes. I'm staring at my Combine implementation and it looks for me that for Failure*Success pair the actual order of arguments would not influence the result, but yet it seems like it does

答:
do! and let! clauses within the expression get desugared to Bind calls. This means that your Bind is called when you do let! x = ....

More specifically, your second example gets desugared into the following:

```<code>let value =
    either.Bind(
       either.YieldFrom Failure,   // yield! Failure
       fun x ->                    // let! x =
           either.Yield 5          // yield 5
    )
</code>```

So it never even gets to yield 5 - the computation stops at let! x =.

In order for the inner computation to "never become part" of the outer one, just use let (without the bang):

```<code>let value = either {
     let x = either {
         yield! Failure
         }
     yield 5
     }
</code>```

This will correctly return Success 5.

Title: Issue with yield in nested workflow

Body:
I'm trying to write my own Either builder as part of my quest to learn computation expressions in f#, but I have hit a wall with what I think is issue with Combine method. My code so far:

type Result<'a> =
    | Failure
    | Success of 'a

type EitherBuilder() =
    member this.Bind(m,f) =
        match m with
        | Failure -> Failure
        | Success(x) -> f x
    member this.Yield x =
        Success(x)
    member this.YieldFrom x =
        x
    member this.Combine(a,b) =
        match a with
        | Success(_) -> a
        | Failure -> b()
    member this.Delay y =
        fun () -> y()
    member this.Run(func) =
        func()

With this code I test the Combine with two tests:

let either = new EitherBuilder()
...
testCase "returns success from 3 yields" <|
    fun _ ->
        let value = either {
            yield! Failure
            yield 4
            yield! Failure
            }
        value |> should equal (Success(4))
testCase "returns success with nested workflows" <|
    fun _ ->
        let value = either {
            let! x = either {
                yield! Failure
                }
            yield 5
            }
        value |> should equal (Success(5))

The first test passes, as I would expect, but the second test fails with following message:

Exception thrown: 'NUnit.Framework.AssertionException' in
  nunit.framework.dll either tests/returns success with nested workflows:
  Failed:    Expected: <Success 5>   But was:  <Failure>

I don't get it. The x is not yielded, so why does it influence my parent workflow? If I move let! below yield the test passes. I'm staring at my Combine implementation and it looks for me that for Failure*Success pair the actual order of arguments would not influence the result, but yet it seems like it does

Body:
do! and let! clauses within the expression get desugared to Bind calls. This means that your Bind is called when you do let! x = ....

More specifically, your second example gets desugared into the following:

let value =
    either.Bind(
       either.YieldFrom Failure,   // yield! Failure
       fun x ->                    // let! x =
           either.Yield 5          // yield 5
    )

So it never even gets to yield 5 - the computation stops at let! x =.

In order for the inner computation to "never become part" of the outer one, just use let (without the bang):

let value = either {
     let x = either {
         yield! Failure
         }
     yield 5
     }

This will correctly return Success 5.


问:
C# Date Converter Program
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}
</code>```

答:
Try parsing date and time with a help of DateTime.TryParseExact which has been specially designed for such tasks:

```<code> using System.Globalization;

 ...

 DateTime userDate;

 // Gathering UserInput (just one simple loop)

 do {
   Console.WriteLine("Please enter the date in the format dd/mm/yyyy");
 }
 while (!DateTime.TryParseExact(Console.ReadLine(),
   "d/m/yyyy", // be nice, let 21.5.2017 be valid; please, do not inist on 21.05.2017
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeLocal,
    out userDate));

 // If you insist on these local variables:
 int day = userDate.Day;
 int month = userDate.Month;
 int year = userDate.Year;

 // But I suggest formatting or string interpolation:
 Console.WriteLine($"{userDate:dd MM yyyy}");
</code>```

Title: C# Date Converter Program

Body:
This will be a noobish question but I am currently working on a program that will take in a user input in the format of DD/MM/YYYY and the output it in the format 1st of May 2017, for example.

But whenever the use string.substring (UserInput.substring in my case) it does not separate the values correctly. For example, when I input the date as 21/05/2001 it displays 215 2001. I have no idea why this is happening.

Im sorry as this is very noobish but I am new to using .substring and I'm sure the problem will seem obvious when someone points it out xD

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            /// Define Varibles

            string UserIntput;
            int Day;
            int Month;
            int year;

            ///Gathering UserInput

            Console.Write("Please enter the date in the format dd/mm/yyyy");
            UserIntput = Console.ReadLine();

            ///Validations

            try
            {
                while(UserIntput.Substring(2,1) != "/" || UserIntput.Substring(5,1) != "/" || UserIntput.Length != 10)
                {
                    Console.WriteLine("Invalid Input");
                    Console.Write("Please enter the date in the format dd/mm/yyyy");
                    UserIntput = Console.ReadLine();

                }

            }
            catch
            {
                Console.WriteLine("Invalid Input");
            }

            /// Defining to Variables

            Day = Convert.ToInt32(UserIntput.Substring(0, 2));

            Month = Convert.ToInt32(UserIntput.Substring(3, 2));

            year = Convert.ToInt32(UserIntput.Substring(6, 4));

            Console.WriteLine(Day + "" + Month + " " + year);
            Console.ReadLine();
        }
    }
}

Body:
Try parsing date and time with a help of DateTime.TryParseExact which has been specially designed for such tasks:

 using System.Globalization;

 ...

 DateTime userDate;

 // Gathering UserInput (just one simple loop)

 do {
   Console.WriteLine("Please enter the date in the format dd/mm/yyyy");
 }
 while (!DateTime.TryParseExact(Console.ReadLine(),
   "d/m/yyyy", // be nice, let 21.5.2017 be valid; please, do not inist on 21.05.2017
    CultureInfo.InvariantCulture,
    DateTimeStyles.AssumeLocal,
    out userDate));

 // If you insist on these local variables:
 int day = userDate.Day;
 int month = userDate.Month;
 int year = userDate.Year;

 // But I suggest formatting or string interpolation:
 Console.WriteLine($"{userDate:dd MM yyyy}");


问:
How to set initial weights in MLPClassifier?
I cannot find a way to set the initial weights of the neural network, could someone tell me how please?
I am using python package sklearn.neural_network.MLPClassifier.

Here is the code for reference:

```<code>from sklearn.neural_network import MLPClassifier
classifier = MLPClassifier(solver="sgd")
classifier.fit(X_train, y_train)
</code>```

答: multilayer_perceptron.py initializes the weights based on the nonlinear function used for hidden layers. If you want to try a different initialization, you can take a look at the function _init_coef here and modify as you desire.

Body:
I cannot find a way to set the initial weights of the neural network, could someone tell me how please?
I am using python package sklearn.neural_network.MLPClassifier.

Here is the code for reference:

from sklearn.neural_network import MLPClassifier
classifier = MLPClassifier(solver="sgd")
classifier.fit(X_train, y_train)


问:
SQl 2008 cross database performance on same physical machine and same server instance
Is there any performance hit when doing a select across another DB on the same physical machine? So I have 2 databases on the same physical machine running within the same SQL 2008 instance.

For instance in SomStoreProc on_this_db I run

```<code>SELECT someFields FROM the_other_db.dbo.someTable
</code>```

So far from what I have read on the internet, most people seem to indicate NO.

答:
Even if it is not a performance hit, it could be a problem in data integrity as FKs can't be enforced across databases.

However, it is more likely your procs need to be tuned especially if they are thousands of lines long.  To begin with look for cursors, correlated subqueries and bad indexing. Also look for where clauses that are nonsaragable and scalar functions that are runing row-by-agonizing-row.

Of course  the best way to prove that the separate database is not the issue is to take one slow proc and convert those tables to one database and test performance both ways. Please at least convince them to do this smaller test before they go ahead and make the horribly complicated and time consuming change to one database and then find out they still have performance problems.

And remember, the execution plan is your friend is looking at these things.

Body:
Is there any performance hit when doing a select across another DB on the same physical machine? So I have 2 databases on the same physical machine running within the same SQL 2008 instance.

For instance in SomStoreProc on_this_db I run

SELECT someFields FROM the_other_db.dbo.someTable

So far from what I have read on the internet, most people seem to indicate NO.


问:
ETL Data from Amazon DMS to S3 to Redshift
I am currently building a data lake within S3 and have successfully moved data from a mysql DB to S3 using DMS.  Within DMS I chose the option 'Migrate existing data and replicate ongoing changes'.  I transformed the data to csv, but in the future will probably choose parquet.  This method creates an initial csv file that has all the raw data from the database tables.  It then creates subsequent csv files with inserts, deletes, updates.

Now I am looking for a strategy to copy the data from S3 into Redshift.  I am looking for a strategy to copy the bulk data and copy the continual changes from S3 into Redshift.  I will likely need to aggregate and summarize much of this data.  Preferably I'll use AWS Glue, which uses Python.  This ETL process will have to read from csv files in S3 and know to ignore files that have already been processed.

How can I facilitate this? Any ideas are welcome.  Ideally I'm hoping for some Python (or Java) scripts that precisely do the process as described.

Thanks.

答:
Using Lambda functions and triggers, you can setup in such a way that Redshift cluster is automatically loaded when a file is uploaded to S3.

Refer to below link

A Zero-Administration Amazon Redshift Database Loader


问:
MSBuild error MSB3021: Unable to copy file. Could not find file 'obj\Release\myWebProject1.dll'
When using TeamCity to compile my MSBuild XML task script, it fails with this:

```<code>[10:43:03]: myWebProject1\ myWebProject 1 .csproj (3s)
[10:43:07]: [ myWebProject1\ myWebProject1 .csproj] _CopyWebApplicationLegacy
[10:43:07]: [_CopyWebApplicationLegacy] Copy
[10:43:07]: [Copy] C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets(131, 5): error MSB3021: Unable to copy file "obj\Release\myWebProject1.dll" to "C:\MSBUILDRELEASE\myWebProject1\\bin\myWebProject1.dll". Could not find file 'obj\Release\myWebProject1.dll'.
</code>```

When I run it locally, it works.

When I compare my local output to my build server output, there are files missing on my build server. Like the global.asax file is missing from my build server output directory (but not when I compile this locally). Why is that?

Here is my current MSBuildScript:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
  ToolsVersion="4.0"
  DefaultTargets="Build">

  <PropertyGroup>
    <OutputDir>C:\MSBUILDRELEASE</OutputDir>
  </PropertyGroup>

  <ItemGroup>
    <ProjectToBuild Include="UtilityApp.sln" >
      <Properties>OutputPath=$(OutputDir);Configuration=MSBuildRelease;Platform=x86</Properties>
    </ProjectToBuild>
  </ItemGroup>

  <Target Name="Build">
    <MSBuild Projects="@(ProjectToBuild)"/>
            <CallTarget Targets="Publish WebProject1" />
            <CallTarget Targets="Publish WebProject2" />
  </Target>

<Target Name="Publish WebProject1">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject1\WebProject1.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject1\;
      OutDir=$(OutputDir)\WebProject1\;Configuration=Release;Platform=AnyCPU" />
</Target>

<Target Name="Publish WebProject2">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject2\WebProject2.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject2\;
      OutDir=$(OutputDir)\WebProject2\;Configuration=Release;Platform=AnyCPU" />
</Target>

</Project>
</code>```

I can run this script locally and it seems to work fine (no errors generated). When I run it on my build server, it fails with MSBuild error MSB3021.

Now when I compare my local build output files to my server build output files, the server output does not have as many files. For instance, the global.ASAX file is missing in the output on my buildserver. Why would it work local for me, but not on my TeamCity build server? What's the difference and how can I fix it?

I noticed the TeamCity build agent error message has a funny directory path:
"C:\MSBUILDRELEASE\myWebProject1\bin\myWebProject1.dll"

^ There are two slashes before the bin folder. I do not specify that anywhere. What gives? I have a feeling I am not building my Web Projects correctly (maybe use a different task approach?). It seems to work locally but not on my build server.

Am I building my web projects correctly? These are simply web projects for Web Service (ASMX) deployment. Help?

答:
Step 1: Restart your Visual Studio.

Step 2: Build >> Reconfigure app.

I got it right this way.

Body:
When using TeamCity to compile my MSBuild XML task script, it fails with this:

[10:43:03]: myWebProject1\ myWebProject 1 .csproj (3s)
[10:43:07]: [ myWebProject1\ myWebProject1 .csproj] _CopyWebApplicationLegacy
[10:43:07]: [_CopyWebApplicationLegacy] Copy
[10:43:07]: [Copy] C:\Program Files\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets(131, 5): error MSB3021: Unable to copy file "obj\Release\myWebProject1.dll" to "C:\MSBUILDRELEASE\myWebProject1\\bin\myWebProject1.dll". Could not find file 'obj\Release\myWebProject1.dll'.

When I run it locally, it works.

When I compare my local output to my build server output, there are files missing on my build server. Like the global.asax file is missing from my build server output directory (but not when I compile this locally). Why is that?

Here is my current MSBuildScript:

<?xml version="1.0" encoding="utf-8"?>
<Project
  xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
  ToolsVersion="4.0"
  DefaultTargets="Build">

  <PropertyGroup>
    <OutputDir>C:\MSBUILDRELEASE</OutputDir>
  </PropertyGroup>

  <ItemGroup>
    <ProjectToBuild Include="UtilityApp.sln" >
      <Properties>OutputPath=$(OutputDir);Configuration=MSBuildRelease;Platform=x86</Properties>
    </ProjectToBuild>
  </ItemGroup>

  <Target Name="Build">
    <MSBuild Projects="@(ProjectToBuild)"/>
            <CallTarget Targets="Publish WebProject1" />
            <CallTarget Targets="Publish WebProject2" />
  </Target>

<Target Name="Publish WebProject1">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject1\WebProject1.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject1\;
      OutDir=$(OutputDir)\WebProject1\;Configuration=Release;Platform=AnyCPU" />
</Target>

<Target Name="Publish WebProject2">
 <RemoveDir Directories="$(OutputFolder)"
       ContinueOnError="true" />
 <MSBuild Projects="WebProject2\WebProject2.csproj"
      Targets="ResolveReferences;_CopyWebApplication"
      Properties="WebProjectOutputDir=$(OutputDir)\WebProject2\;
      OutDir=$(OutputDir)\WebProject2\;Configuration=Release;Platform=AnyCPU" />
</Target>

</Project>

I can run this script locally and it seems to work fine (no errors generated). When I run it on my build server, it fails with MSBuild error MSB3021.

Now when I compare my local build output files to my server build output files, the server output does not have as many files. For instance, the global.ASAX file is missing in the output on my buildserver. Why would it work local for me, but not on my TeamCity build server? What's the difference and how can I fix it?

I noticed the TeamCity build agent error message has a funny directory path:
"C:\MSBUILDRELEASE\myWebProject1\bin\myWebProject1.dll"

^ There are two slashes before the bin folder. I do not specify that anywhere. What gives? I have a feeling I am not building my Web Projects correctly (maybe use a different task approach?). It seems to work locally but not on my build server.

Am I building my web projects correctly? These are simply web projects for Web Service (ASMX) deployment. Help?


问:
constexpr base class member set by derived class
I want to do something like this:

```<code>// a base class for a family of devices
class foobar_base()
{
    int _n;

public:

    foo_base(int num_of_things) : _n(num_of_things){}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _n;}

};

// a specific device that has 5 things
class foo: public foobar_base
{
public:
    // foo has 5 things
    foo():foo_base(5){}
};

// a specific device that has 10 things
class bar: public foobar_base
{
public:
    // bar has 10 things
    bar():foo_base(10){}
};

// some class or code that wants to use the family of devices
// represented by the base class...
class foobar_user()
{
    shared_ptr<foobar_base> f(new foo())

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    shared_ptr<foobar_base> b(new bar())

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

};
</code>```

What I'm trying to do is use information coming from the derived classes via a base class pointer, where constants are required, as in the line:

```<code>    int array_for_foo_things[f->num_of_things()];
</code>```

Obviously, I can use vectors instead of arrays as a workaround, but the desire is to find a way to get a constexpr from a base class pointer that is set from the derived classes of the base class.

答:
Following the idea of user0042, you mean something like this?

```<code>#include <iostream>
#include <memory>

// a base class for a family of devices
template<int _N>
class foobar_base
{
    // int _n;

public:

    foobar_base() {}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _N;}
};

// a specific device that has 5 things
class foo: public foobar_base<5>
{
public:
    // foo has 5 things
    foo() {}
};

// a specific device that has 10 things
class bar: public foobar_base<10>
{
public:
    // bar has 10 things
    bar(){}
};

// some class or code that wants to use the family of devices
// represented by the base class...
int main()
{
    std::shared_ptr<foobar_base<5>> f(new foo());

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    std::shared_ptr<foobar_base<10>> b(new bar());

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

    std::cout<<"foo: "<<sizeof(array_for_foo_things)/sizeof(int)<<std::endl;
    std::cout<<"bar: "<<sizeof(array_for_bar_things)/sizeof(int)<<std::endl;
}
</code>```

Body:
I want to do something like this:

// a base class for a family of devices
class foobar_base()
{
    int _n;

public:

    foo_base(int num_of_things) : _n(num_of_things){}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _n;}

};

// a specific device that has 5 things
class foo: public foobar_base
{
public:
    // foo has 5 things
    foo():foo_base(5){}
};

// a specific device that has 10 things
class bar: public foobar_base
{
public:
    // bar has 10 things
    bar():foo_base(10){}
};

// some class or code that wants to use the family of devices
// represented by the base class...
class foobar_user()
{
    shared_ptr<foobar_base> f(new foo())

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    shared_ptr<foobar_base> b(new bar())

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

};

What I'm trying to do is use information coming from the derived classes via a base class pointer, where constants are required, as in the line:

    int array_for_foo_things[f->num_of_things()];

Obviously, I can use vectors instead of arrays as a workaround, but the desire is to find a way to get a constexpr from a base class pointer that is set from the derived classes of the base class.

Body:
Following the idea of user0042, you mean something like this?

#include <iostream>
#include <memory>

// a base class for a family of devices
template<int _N>
class foobar_base
{
    // int _n;

public:

    foobar_base() {}

    // I would like to use this from derived classes, where
    // constants are required, such as array sizes...
    constexpr int num_of_things() const {return _N;}
};

// a specific device that has 5 things
class foo: public foobar_base<5>
{
public:
    // foo has 5 things
    foo() {}
};

// a specific device that has 10 things
class bar: public foobar_base<10>
{
public:
    // bar has 10 things
    bar(){}
};

// some class or code that wants to use the family of devices
// represented by the base class...
int main()
{
    std::shared_ptr<foobar_base<5>> f(new foo());

    // I want this to have the number of things that foo has
    int array_for_foo_things[f->num_of_things()];

    std::shared_ptr<foobar_base<10>> b(new bar());

    // and this to have the number of things that bar has
    int array_for_bar_things[b->num_of_things()];

    std::cout<<"foo: "<<sizeof(array_for_foo_things)/sizeof(int)<<std::endl;
    std::cout<<"bar: "<<sizeof(array_for_bar_things)/sizeof(int)<<std::endl;
}


问:
Data from GET request doesn't exist when used in another class in javascript
I have a function for making GET request like this.

```<code>export class OneClass {
  constructor() {
    this.data = [];

    getData() {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', '/data.json', true);
      xhr.onreadystatechange = () => {
        * push response to this.data *
      };
      xhr.send();
    }
  }
</code>```

After that I want to use this.data in another class, AnotherClass is created on DOMContentLoad

```<code>var oneClass = new OneClass();

class AnotherClass {
  constructor() {
    oneClass.getData();
    this.anotherClassMethod()
  }
  anotherClassMethod() {
    * use oneClass.data *
  }
}
</code>```

The idea is that anotherClassMethod() should output oneClass.data as soon as page is loaded but now when it is called array is still empty.

I understand that my method runs sooner than data is created and that is the reason for it but I'm not sure what to change to make this code work.

答:
Are you checking the response being valid? If so, why not using the standard way of callback? I've didn't see you implementing it:

```<code>export class OneClass{
  constructor() {
    this.data = [];

     getData(callback) {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', '/data.json', true);
      xhr.onreadystatechange = (response) => {
        callback(response);
    };
    xhr.send();
  }
}
</code>```

The previous one creates your class with a paremeter for returning to his call stack after finished.
Then, lets wait for the response and manipulate the data:

```<code>var oneClass= new OneClass();

class AnotherClass{
  constructor() {
    oneClass.getData(this.anotherClassMethod);

  }
 anotherClassMethod(data){
    *use oneClass.data*
 }
}
</code>```

More info on Callbacks

Body:
I have a function for making GET request like this.

export class OneClass {
  constructor() {
    this.data = [];

    getData() {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', '/data.json', true);
      xhr.onreadystatechange = () => {
        * push response to this.data *
      };
      xhr.send();
    }
  }

After that I want to use this.data in another class, AnotherClass is created on DOMContentLoad

var oneClass = new OneClass();

class AnotherClass {
  constructor() {
    oneClass.getData();
    this.anotherClassMethod()
  }
  anotherClassMethod() {
    * use oneClass.data *
  }
}

The idea is that anotherClassMethod() should output oneClass.data as soon as page is loaded but now when it is called array is still empty.

I understand that my method runs sooner than data is created and that is the reason for it but I'm not sure what to change to make this code work.

Body:
Are you checking the response being valid? If so, why not using the standard way of callback? I've didn't see you implementing it:

export class OneClass{
  constructor() {
    this.data = [];

     getData(callback) {
      let xhr = new XMLHttpRequest();
      xhr.open('GET', '/data.json', true);
      xhr.onreadystatechange = (response) => {
        callback(response);
    };
    xhr.send();
  }
}

The previous one creates your class with a paremeter for returning to his call stack after finished.
Then, lets wait for the response and manipulate the data:

var oneClass= new OneClass();

class AnotherClass{
  constructor() {
    oneClass.getData(this.anotherClassMethod);

  }
 anotherClassMethod(data){
    *use oneClass.data*
 }
}

More info on Callbacks


问:
exiting a recursive function JavaScript
I have some code where I am able to exit out of the code however whatever is returned is undefined which is weird given if i console.log what I want to return it gives the correct value. Here is my code:

function encryptPass(text, result) {
        var a = text.length -1;
        var c = text.charCodeAt(a);
        if      (65 <= c && c <=  90) result += String.fromCharCode((c - 65 + 4) % 26 + 65);  // Uppercase
        else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97);  // Lowercase
        else                          result += text.char;  // Copy

        if (a == 0) {
            console.log(result);
            return result;
        } else {
          encryptPass(text.substr(0, a), result);
        }
       return;
    }
console.log('lemons '+ encryptPass('hello',''));```

答:
You have 2 problems:

```<code>    if (a == 0) {
        encrypted = result;
        return 'encrypted'; // you return the word encrypted instead of the variable results
    } else {
      encryptPass(text.substr(0, a), result);
    }
    return; // you return undefined
</code>```

Solution:

function encryptPass(text, result) {
  var a = text.length - 1;
  var c = text.charCodeAt(a);
  if (65 <= c && c <= 90) result += String.fromCharCode((c - 65 + 4) % 26 + 65); // Uppercase
  else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97); // Lowercase
  else result += text.char; // Copy

  if (a == 0) {
    return result; // return the result
  }

  // you can skip the else check, since this is only option left
  return encryptPass(text.substr(0, a), result); // return the results of encryptPass
}
console.log('lemons ' + encryptPass('hello', ''));```

Title: exiting a recursive function JavaScript

Body:
You have 2 problems:

    if (a == 0) {
        encrypted = result;
        return 'encrypted'; // you return the word encrypted instead of the variable results
    } else {
      encryptPass(text.substr(0, a), result);
    }
    return; // you return undefined

Solution:

function encryptPass(text, result) {
  var a = text.length - 1;
  var c = text.charCodeAt(a);
  if (65 <= c && c <= 90) result += String.fromCharCode((c - 65 + 4) % 26 + 65); // Uppercase
  else if (97 <= c && c <= 122) result += String.fromCharCode((c - 97 + 4) % 26 + 97); // Lowercase
  else result += text.char; // Copy

  if (a == 0) {
    return result; // return the result
  }

  // you can skip the else check, since this is only option left
  return encryptPass(text.substr(0, a), result); // return the results of encryptPass
}
console.log('lemons ' + encryptPass('hello', ''));


问:
When serving JavaScript files, is it better to use the application/javascript or application/x-javascript
The whole question fits in the title. And to add some context: I'm not asking what is the best according to what the specs are saying, but rather what works the best given the mix of browsers deployed nowadays.

Some data points:

Google uses text/javascript for the JS used on their home page.

Google uses text/javascript on Google Docs.

Google uses application/x-javascript to serve JavaScript files with their Ajax libraries service.

Yahoo uses application/x-javascript to serve their JS.

Yahoo uses application/x-javascript for the JavaScript served on their home page.

答: If you choose to use application/javascript for js in your pages, IE7 and IE8 will not run your script!  Blame Microsoft all you want, but if you want most people to run your pages use text/javascript.</p>