问:
How to test awt.* with SpringBoot?
I have a class which produces screenshot:

```<code>@Component
public class ImagesHandlerImpl implements ImagesHandler {
    ....
    public boolean doScreen() throws IOException, AWTException {
        final Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        ...
    }
}
</code>```

My app created with spring boot, and I need test it. But I get java.awt.HeadlessException

My test:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = ImagesHandlerImpl.class)
@ContextConfiguration(classes = App.class)
public class ImagesHandlerImplTest {
    ...
    @Test
    public void whenDoScreenThenFilenameLikeTemplate() throws IOException, AWTException {
        imagesHandler.doScreen();
        final String name = dir.listFiles()[0].getName();
        assertThat("SCREEN_0", is(name));
    }
}
</code>```

I try to prevent HeadlessException:

```<code>@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
        builder.headless(false).run(args);
    }
}
</code>```

I use spring-boot version 1.5.6.RELEASE.

But it didn't help. I get log:

java.awt.HeadlessException    at
  sun.awt.HeadlessToolkit.getScreenSize(HeadlessToolkit.java:284)   at
  org.robinhood.image.ImagesHandlerImpl.doScreen(ImagesHandlerImpl.java:42)
    at
  org.robinhood.image.ImagesHandlerImplTest.whenDoScreenThenCreatePrintScreen(ImagesHandlerImplTest.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at
  org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Help me. How to fix this issue?
Thank You!

答:
The spring test runner does not invoke the main method of App class.
And it will turn on Headless mode by default.

You can specify JVM argument -Djava.awt.headless=false for executing the test case.
Another solution is setting the property during bean initialization.

```<code>@Component
public class ImagesHandlerImpl implements ImagesHandler, InitializingBean {
  @Override
  public void afterPropertiesSet() throws Exception {
    System.setProperty("java.awt.headless", "false");
  }

  public boolean doScreen() throws Exception {
    //...
  }
}
</code>```

Title: How to test awt.* with SpringBoot?

Body:
I have a class which produces screenshot:

@Component
public class ImagesHandlerImpl implements ImagesHandler {
    ....
    public boolean doScreen() throws IOException, AWTException {
        final Rectangle rectangle = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
        ...
    }
}

My app created with spring boot, and I need test it. But I get java.awt.HeadlessException

My test:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = ImagesHandlerImpl.class)
@ContextConfiguration(classes = App.class)
public class ImagesHandlerImplTest {
    ...
    @Test
    public void whenDoScreenThenFilenameLikeTemplate() throws IOException, AWTException {
        imagesHandler.doScreen();
        final String name = dir.listFiles()[0].getName();
        assertThat("SCREEN_0", is(name));
    }
}

I try to prevent HeadlessException:

@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplicationBuilder builder = new SpringApplicationBuilder(App.class);
        builder.headless(false).run(args);
    }
}

I use spring-boot version 1.5.6.RELEASE.

But it didn't help. I get log:

java.awt.HeadlessException    at
  sun.awt.HeadlessToolkit.getScreenSize(HeadlessToolkit.java:284)   at
  org.robinhood.image.ImagesHandlerImpl.doScreen(ImagesHandlerImpl.java:42)
    at
  org.robinhood.image.ImagesHandlerImplTest.whenDoScreenThenCreatePrintScreen(ImagesHandlerImplTest.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)     at
  org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at
  org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at
  org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at
  org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)  at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)   at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)   at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)  at
  org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at
  org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)    at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)   at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Help me. How to fix this issue?
Thank You!

Body:
The spring test runner does not invoke the main method of App class.
And it will turn on Headless mode by default.

You can specify JVM argument -Djava.awt.headless=false for executing the test case.
Another solution is setting the property during bean initialization.

@Component
public class ImagesHandlerImpl implements ImagesHandler, InitializingBean {
  @Override
  public void afterPropertiesSet() throws Exception {
    System.setProperty("java.awt.headless", "false");
  }

  public boolean doScreen() throws Exception {
    //...
  }
}


来源: stackexchange

问:
Python File Reading & Writing
So I need to write a program that reads a text file, and copies its contents to another file. I then have to add a column at the end of the text file, and populate that column with an int that is calculated using the function calc_bill. I can get it to copy the contents of the original file to the new one, but I cannot seem to get my program to read in the ints necessary for calc_bill to run.
Any help would be greatly appreciated.

Here are the first 3 lines of the text file I am reading from:

```<code>CustomerID  Title   FirstName   MiddleName  LastName    Customer Type
1   Mr. Orlando N.  Gee Residential     297780  302555
2   Mr. Keith   NULL    Harris  Residential     274964  278126
</code>```

It is copying the file exactly as it is supposed to to the new file. What is not working is writing the bill_amount (calc_bill)/ billVal(main) to the new file in a new column. Here is the expected output to the new file:

```<code>CustomerID  Title   FirstName   MiddleName  LastName    Customer Type   Company Name    Start Reading   End Reading  BillVal
1   Mr. Orlando N.  Gee Residential     297780  302555       some number
2   Mr. Keith   NULL    Harris  Residential     274964  278126    some number
</code>```

And here is my code:

```<code>def main():
    file_in = open("water_supplies.txt", "r")
    file_in.readline()
    file_out = input("Please enter a file name for the output:")
    output_file = open(file_out, 'w')
    lines = file_in.readlines()
    for line in lines:
        lines = [line.split('\t')]
        #output_file.write(str(lines)+ "\n")
        billVal = 0
        c_type = line[5]
        start = int(line[7])
        end = int(line[8])
        billVal = calc_bill(c_type, start, end)
        output_file.write(str(lines)+ "\t" + str(billVal) + "\n")

def calc_bill(customer_type, start_reading, end_reading):
    price_per_gallon = 0

    if customer_type == "Residential":
        price_per_gallon = .012

    elif customer_type == "Commercial":
        price_per_gallon = .011

    elif customer_type == "Industrial":
        price_per_gallon = .01

    if start_reading >= end_reading:
        print("Error: please try again")

    else:
        reading = end_reading - start_reading

    bill_amount = reading * price_per_gallon
    return bill_amount
main()
</code>```

答:
There are the issues mentioned above, but here is a small change to your main() method that works correctly.

```<code>def main():
    file_in = open("water_supplies.txt", "r")
    # skip the headers in the input file, and save for output
    headers = file_in.readline()
    # changed to raw_input to not require quotes
    file_out = raw_input("Please enter a file name for the output: ")
    output_file = open(file_out, 'w')
    # write the headers back into output file
    output_file.write(headers)
    lines = file_in.readlines()
    for line in lines:
        # renamed variable here to split
        split = line.split('\t')
        bill_val = 0
        c_type = split[5]
        start = int(split[6])
        end = int(split[7])
        bill_val = calc_bill(c_type, start, end)
        # line is already a string, don't need to cast it
        # added rstrip() to remove trailing newline
        output_file.write(line.rstrip() + "\t" + str(bill_val) + "\n")
</code>```

Note that the line variable in your loop includes the trailing newline, so you will need to strip that off as well if you're going to write it to the output file as-is. Your start and end indices were off by 1 as well, so I changed to split[6] and split[7].

It is a good idea to not require the user to include the quotes for the filename, so keep that in mind as well. An easy way is to just use raw_input instead of input.

Sample input file (from OP):

```<code>CustomerID      Title   FirstName       MiddleName      LastName        Customer Type
1       Mr.     Orlando N.      Gee     Residential     297780  302555
2       Mr.     Keith   NULL    Harris  Residential     274964  278126

$ python test.py
Please enter a file name for the output:test.out
</code>```

Output (test.out):

```<code>1       Mr.     Orlando N.      Gee     Residential     297780  302555  57.3
2       Mr.     Keith   NULL    Harris  Residential     274964  278126  37.944
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python File Reading & Writing

Body:
So I need to write a program that reads a text file, and copies its contents to another file. I then have to add a column at the end of the text file, and populate that column with an int that is calculated using the function calc_bill. I can get it to copy the contents of the original file to the new one, but I cannot seem to get my program to read in the ints necessary for calc_bill to run.
Any help would be greatly appreciated.

Here are the first 3 lines of the text file I am reading from:

CustomerID  Title   FirstName   MiddleName  LastName    Customer Type
1   Mr. Orlando N.  Gee Residential     297780  302555
2   Mr. Keith   NULL    Harris  Residential     274964  278126

It is copying the file exactly as it is supposed to to the new file. What is not working is writing the bill_amount (calc_bill)/ billVal(main) to the new file in a new column. Here is the expected output to the new file:

CustomerID  Title   FirstName   MiddleName  LastName    Customer Type   Company Name    Start Reading   End Reading  BillVal
1   Mr. Orlando N.  Gee Residential     297780  302555       some number
2   Mr. Keith   NULL    Harris  Residential     274964  278126    some number

And here is my code:

def main():
    file_in = open("water_supplies.txt", "r")
    file_in.readline()
    file_out = input("Please enter a file name for the output:")
    output_file = open(file_out, 'w')
    lines = file_in.readlines()
    for line in lines:
        lines = [line.split('\t')]
        #output_file.write(str(lines)+ "\n")
        billVal = 0
        c_type = line[5]
        start = int(line[7])
        end = int(line[8])
        billVal = calc_bill(c_type, start, end)
        output_file.write(str(lines)+ "\t" + str(billVal) + "\n")

def calc_bill(customer_type, start_reading, end_reading):
    price_per_gallon = 0

    if customer_type == "Residential":
        price_per_gallon = .012

    elif customer_type == "Commercial":
        price_per_gallon = .011

    elif customer_type == "Industrial":
        price_per_gallon = .01

    if start_reading >= end_reading:
        print("Error: please try again")

    else:
        reading = end_reading - start_reading

    bill_amount = reading * price_per_gallon
    return bill_amount
main()

Body:
There are the issues mentioned above, but here is a small change to your main() method that works correctly.

def main():
    file_in = open("water_supplies.txt", "r")
    # skip the headers in the input file, and save for output
    headers = file_in.readline()
    # changed to raw_input to not require quotes
    file_out = raw_input("Please enter a file name for the output: ")
    output_file = open(file_out, 'w')
    # write the headers back into output file
    output_file.write(headers)
    lines = file_in.readlines()
    for line in lines:
        # renamed variable here to split
        split = line.split('\t')
        bill_val = 0
        c_type = split[5]
        start = int(split[6])
        end = int(split[7])
        bill_val = calc_bill(c_type, start, end)
        # line is already a string, don't need to cast it
        # added rstrip() to remove trailing newline
        output_file.write(line.rstrip() + "\t" + str(bill_val) + "\n")

Note that the line variable in your loop includes the trailing newline, so you will need to strip that off as well if you're going to write it to the output file as-is. Your start and end indices were off by 1 as well, so I changed to split[6] and split[7].

It is a good idea to not require the user to include the quotes for the filename, so keep that in mind as well. An easy way is to just use raw_input instead of input.

Sample input file (from OP):

CustomerID      Title   FirstName       MiddleName      LastName        Customer Type
1       Mr.     Orlando N.      Gee     Residential     297780  302555
2       Mr.     Keith   NULL    Harris  Residential     274964  278126

$ python test.py
Please enter a file name for the output:test.out

Output (test.out):

1       Mr.     Orlando N.      Gee     Residential     297780  302555  57.3
2       Mr.     Keith   NULL    Harris  Residential     274964  278126  37.944


问:
SSE/AVX - VMULPD produces all zeros for small integer inputs?
I'm using X64dbg to test SSE/AVX assembly instructions to better understand their behavior before using them to write code. I've been able to test the vmovapd, vbroadcastsd, vsubpd, and vaddpd instructions this way without issue.

I loaded YMM registers as follows:

```<code>YMM0: 0000000000000004000000000000000400000000000000040000000000000004
YMM1: 0000000000000002000000000000000200000000000000020000000000000002
YMM2: 0101010101010101010101010101010101010101010101010101010101010101
</code>```

Then, I execute this instruction:

```<code>VMULPD ymm2, ymm1, ymm0
</code>```

I'm trying to multiply YMM0 with YMM1, and store the result in YMM2, however after I execute this instruction, YMM2 contains the following:

```<code>0000000000000000000000000000000000000000000000000000000000000000
</code>```

But I would expect this:

```<code>0000000000000008000000000000000800000000000000080000000000000008
(That's four 8's from 4.0 * 2.0)
</code>```

According to the Intel 64 and IA-32 Software Developer's Manual on page 798, this should work:

```<code>VMULPD ymm1, ymm2, ymm3/m256

Multiply packed double-precision floating-point values
in ymm3/m256 with ymm2 and store result in ymm1.
</code>```

So what am I missing here?

答:
The values you loaded represent denormal (very small) doubles.  Their products underflow to +0.0, even without FTZ / DAZ (flush to zero / denormals-are-zero) enabled.

And BTW, writing 0 into ymm2 isn't "does nothing".  VMULPD's destination operand is write-only, so seeing it change from the debug-sentinel you loaded to all-zero proves that it did do something.

If you were looking for 64-bit packed-integer multiply, then tough.  AVX2 has no packed 64-bit multiply.  It does have 32x32 -> 64-bit multiply (vpmuludq) and packed 32x32 -> 32-bit (VPMULLD 2 uops on many CPUs).  It may be profitable to vectorize 64x64 -> 64bit multiply using AVX2, see Fastest way to multiply an array of int64_t?.

AVX512 has 64x64 -> 64 bit multiply, though.

If your integers (and their product) can be exactly represented by double, it might be worth it to use packed-conversion to double and use vmulpd on that, because the hardware has excellent throughput for add / mul / FMA with packed double.  (Haswell/Skylake: 2 vectors per clock, much better than vpmulld)

Fun fact:

IEEE float/double has the interesting property that (other than the sign bit) comparing as integers "works".  This is why the exponent is biased, so that integer adding 1 to the binary representation produces the next representable value.  (Implementing nextafterf is fun on SSE; I looked at it a while ago but never got around to sending a patch.)

See also https://www.h-schmidt.net/FloatConverter/IEEE754.html for int -> float binary representation.  (for single-precision, but https://en.wikipedia.org/wiki/Double-precision_floating-point_format IEEE binary64 works the same as binary32.)

Body:
I'm using X64dbg to test SSE/AVX assembly instructions to better understand their behavior before using them to write code. I've been able to test the vmovapd, vbroadcastsd, vsubpd, and vaddpd instructions this way without issue.

I loaded YMM registers as follows:

YMM0: 0000000000000004000000000000000400000000000000040000000000000004
YMM1: 0000000000000002000000000000000200000000000000020000000000000002
YMM2: 0101010101010101010101010101010101010101010101010101010101010101

Then, I execute this instruction:

VMULPD ymm2, ymm1, ymm0

I'm trying to multiply YMM0 with YMM1, and store the result in YMM2, however after I execute this instruction, YMM2 contains the following:

0000000000000000000000000000000000000000000000000000000000000000

But I would expect this:

0000000000000008000000000000000800000000000000080000000000000008
(That's four 8's from 4.0 * 2.0)

According to the Intel 64 and IA-32 Software Developer's Manual on page 798, this should work:

VMULPD ymm1, ymm2, ymm3/m256

Multiply packed double-precision floating-point values
in ymm3/m256 with ymm2 and store result in ymm1.

So what am I missing here?


问:
Interpolating dates across N python Lists
I am attempting to write a date interpolation algorithm for a dictionary:

each dictionary entry has N keys

Each key for the entry has a corresponding list of dates

No dates can be duplicated across the key lists

If I was to flatten all the lists for an entry after processing I would end up with a continuous list of daily dates

interpolation should only be between dates that do not appear in other lists (see below simplified example

Ex. D =  {"Entry":{"list1":[1,2,9,12],"list2":[4,6]}}

Dfinal = {"Entry":{"list1":[1,2,3,7,8,9,10,11,12],"list2":[4,5,6]}}

In my sample code I merge all the lists into one, sort that list and then get the index of each of the dates which I then can interpolate between if the outer index is is the same ie. [0][1] [0][2] the problem I am having is figuring out how to switch and interpolate on another list when I hit a date that exists in another list. I am almost there I just am not sure how to finish this its quite the puzzle!

```<code>from datetime import date, timedelta as td
import datetime
import numpy as np
import calendar

#Interpolate Dates
def datesBetween(StartDate,EndDate):
    dates = []
    year1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').year
    year2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').year
    Month1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').month
    Month2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').month
    day1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').day
    day2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').day
    d1 = date(year1, Month1, day1)
    d2 = date(year2, Month2, day2)
    delta = d2 - d1
    dates.append(datetime.datetime.strptime(str(StartDate),'%d%b%Y').strftime('%d%b%Y'))
    d0 = datetime.datetime.strptime(str(StartDate),'%d%b%Y')
    for i in range(delta.days):
        d0 += datetime.timedelta(days=1)
        dates.append(d0.strftime('%d%b%Y'))
    return dates

#Sort Dates
def date_key(a):
    a = datetime.datetime.strptime(a, '%d%b%Y').date()
    return a

dates1 = ['28aug2017', '29aug2017', '30aug2017', '31aug2017', '01sep2017', '12sep2017','13sep2017', '14sep2017','20sep2017', '21sep2017', '25sep2017', '26sep2017','27sep2017', '28sep2017', '29sep2017', '02oct2017']

dates2 = ['05sep2017', '06sep2017', '07sep2017', '08sep2017', '11sep2017', '03oct2017']

dates3 = [ '15sep2017', '18sep2017', '19sep2017']

master = [dates1,dates2,dates3]

conc = []
for lst in master:
    conc = conc + lst

sortedDates = sorted(conc,key=date_key)

indexMain = []
indexSub = []

for d in sortedDates:
    indexMain.append(next((i for i, sublist in enumerate(master) if str(d) in sublist), -1))
    indexSub.append(next((sublist for sublist in master if str(d) in sublist)).index(str(d)))

#interpolation of the respective lists
i = 0
while i < len(indexMain)-1:

    d1 = master[indexMain[i]][indexSub[i]]
    d2 = master[indexMain[i+1]][indexSub[i+1]]

    if indexMain[i] == indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp:
            if val not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val))

    if indexMain[i] != indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp[:len(temp)-1]:
            if val not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val))

    i += 1

print(master[0])
print(master[1])
print(master[2])
</code>```

答:
SOLVED

```<code>from datetime import date, timedelta as td
import datetime
import numpy as np
import calendar

#Interpolate Dates
def datesBetween(StartDate,EndDate):
    dates = []
    year1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').year
    year2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').year
    Month1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').month
    Month2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').month
    day1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').day
    day2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').day
    d1 = date(year1, Month1, day1)
    d2 = date(year2, Month2, day2)
    delta = d2 - d1
    dates.append(datetime.datetime.strptime(str(StartDate),'%d%b%Y').strftime('%d%b%Y'))
    d0 = datetime.datetime.strptime(str(StartDate),'%d%b%Y')
    for i in range(delta.days):
        d0 += datetime.timedelta(days=1)
        dates.append(d0.strftime('%d%b%Y'))
    return dates

#Sort Dates
def date_key(a):
    a = datetime.datetime.strptime(a, '%d%b%Y').date()
    return a

dates1 = ['28aug2017', '31aug2017', '01sep2017']

dates2 = ['30aug2017']

dates3 = [ '03sep2017', '05sep2017']

master = [dates1,dates2,dates3]

conc = []
for lst in master:
    conc = conc + lst

sortedDates = sorted(conc,key=date_key)

indexMain = []
indexSub = []

for d in sortedDates:
    indexMain.append(next((i for i, sublist in enumerate(master) if str(d) in sublist), -1))
    indexSub.append(next((sublist for sublist in master if str(d) in sublist)).index(str(d)))

i = 0
print(len(indexMain)-1)
while i < len(indexMain)-1:
    d1 = master[indexMain[i]][indexSub[i]]
    d2 = master[indexMain[i+1]][indexSub[i+1]]
    if indexMain[i] == indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp:
            if str(val).lower() not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val).lower())
        i += 1
    else:
        temp = datesBetween(str(d1),str(d2))
        temp = temp[:len(temp)-1]
        for val in temp:
            if str(val).lower() not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val).lower())
        i += 1

print(sorted(master[0],key=date_key))
print(sorted(master[1],key=date_key))
print(sorted(master[2],key=date_key))
</code>```

Body:
I am attempting to write a date interpolation algorithm for a dictionary:

each dictionary entry has N keys

Each key for the entry has a corresponding list of dates

No dates can be duplicated across the key lists

If I was to flatten all the lists for an entry after processing I would end up with a continuous list of daily dates

interpolation should only be between dates that do not appear in other lists (see below simplified example

Ex. D =  {"Entry":{"list1":[1,2,9,12],"list2":[4,6]}}

Dfinal = {"Entry":{"list1":[1,2,3,7,8,9,10,11,12],"list2":[4,5,6]}}

In my sample code I merge all the lists into one, sort that list and then get the index of each of the dates which I then can interpolate between if the outer index is is the same ie. [0][1] [0][2] the problem I am having is figuring out how to switch and interpolate on another list when I hit a date that exists in another list. I am almost there I just am not sure how to finish this its quite the puzzle!

from datetime import date, timedelta as td
import datetime
import numpy as np
import calendar

#Interpolate Dates
def datesBetween(StartDate,EndDate):
    dates = []
    year1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').year
    year2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').year
    Month1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').month
    Month2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').month
    day1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').day
    day2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').day
    d1 = date(year1, Month1, day1)
    d2 = date(year2, Month2, day2)
    delta = d2 - d1
    dates.append(datetime.datetime.strptime(str(StartDate),'%d%b%Y').strftime('%d%b%Y'))
    d0 = datetime.datetime.strptime(str(StartDate),'%d%b%Y')
    for i in range(delta.days):
        d0 += datetime.timedelta(days=1)
        dates.append(d0.strftime('%d%b%Y'))
    return dates

#Sort Dates
def date_key(a):
    a = datetime.datetime.strptime(a, '%d%b%Y').date()
    return a

dates1 = ['28aug2017', '29aug2017', '30aug2017', '31aug2017', '01sep2017', '12sep2017','13sep2017', '14sep2017','20sep2017', '21sep2017', '25sep2017', '26sep2017','27sep2017', '28sep2017', '29sep2017', '02oct2017']

dates2 = ['05sep2017', '06sep2017', '07sep2017', '08sep2017', '11sep2017', '03oct2017']

dates3 = [ '15sep2017', '18sep2017', '19sep2017']

master = [dates1,dates2,dates3]

conc = []
for lst in master:
    conc = conc + lst

sortedDates = sorted(conc,key=date_key)

indexMain = []
indexSub = []

for d in sortedDates:
    indexMain.append(next((i for i, sublist in enumerate(master) if str(d) in sublist), -1))
    indexSub.append(next((sublist for sublist in master if str(d) in sublist)).index(str(d)))

#interpolation of the respective lists
i = 0
while i < len(indexMain)-1:

    d1 = master[indexMain[i]][indexSub[i]]
    d2 = master[indexMain[i+1]][indexSub[i+1]]

    if indexMain[i] == indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp:
            if val not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val))

    if indexMain[i] != indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp[:len(temp)-1]:
            if val not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val))

    i += 1

print(master[0])
print(master[1])
print(master[2])

Body:
SOLVED

from datetime import date, timedelta as td
import datetime
import numpy as np
import calendar

#Interpolate Dates
def datesBetween(StartDate,EndDate):
    dates = []
    year1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').year
    year2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').year
    Month1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').month
    Month2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').month
    day1 = datetime.datetime.strptime(str(StartDate),'%d%b%Y').day
    day2 = datetime.datetime.strptime(str(EndDate),'%d%b%Y').day
    d1 = date(year1, Month1, day1)
    d2 = date(year2, Month2, day2)
    delta = d2 - d1
    dates.append(datetime.datetime.strptime(str(StartDate),'%d%b%Y').strftime('%d%b%Y'))
    d0 = datetime.datetime.strptime(str(StartDate),'%d%b%Y')
    for i in range(delta.days):
        d0 += datetime.timedelta(days=1)
        dates.append(d0.strftime('%d%b%Y'))
    return dates

#Sort Dates
def date_key(a):
    a = datetime.datetime.strptime(a, '%d%b%Y').date()
    return a

dates1 = ['28aug2017', '31aug2017', '01sep2017']

dates2 = ['30aug2017']

dates3 = [ '03sep2017', '05sep2017']

master = [dates1,dates2,dates3]

conc = []
for lst in master:
    conc = conc + lst

sortedDates = sorted(conc,key=date_key)

indexMain = []
indexSub = []

for d in sortedDates:
    indexMain.append(next((i for i, sublist in enumerate(master) if str(d) in sublist), -1))
    indexSub.append(next((sublist for sublist in master if str(d) in sublist)).index(str(d)))

i = 0
print(len(indexMain)-1)
while i < len(indexMain)-1:
    d1 = master[indexMain[i]][indexSub[i]]
    d2 = master[indexMain[i+1]][indexSub[i+1]]
    if indexMain[i] == indexMain[i+1]:
        temp = datesBetween(str(d1),str(d2))
        for val in temp:
            if str(val).lower() not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val).lower())
        i += 1
    else:
        temp = datesBetween(str(d1),str(d2))
        temp = temp[:len(temp)-1]
        for val in temp:
            if str(val).lower() not in master[indexMain[i]]:
                master[indexMain[i]].append(str(val).lower())
        i += 1

print(sorted(master[0],key=date_key))
print(sorted(master[1],key=date_key))
print(sorted(master[2],key=date_key))


问:
Azure Search using REST c#
I am trying to run the following code:

```<code>public class Item
{
    [JsonProperty(PropertyName = "api-key")]
    public string apikey { get; set; }

}

[[some method]]{
            var url = "https://[search service name].search.windows.net/indexes/temp?api-version=2016-09-01";

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Put,url))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var sItem = new Item { apikey = [AzureSearchAdminKey] };
                    var tststring = JsonConvert.SerializeObject(sItem);
                    var body=new  StringContent(tststring, Encoding.UTF8,"application/json" );

                    request.Content =  body;

                    request.Method = HttpMethod.Put;

                    using (HttpResponseMessage response = httpClient.SendAsync(request).Result)
                    {
                        var stringr = response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(stringr);
                        Console.ReadLine();
                    }

                }
            }

}
</code>```

I get the following error:
"Error reading JObject from JsonReader. Path '', line 0, position 0."

Could someone from search team tell me what I did wrong?

答:
The api key should be in the HTTP header, and the index definition should be in the HTTP body.

Here's some sample code for creating a data source, index, and indexer, which reads from an Azure SQL DB and indexes its rows.

class Program
{
    static void Main(string[] args)
    {
        var searchServiceName = "[search service name]";
        var apiKey = "[api key]";

        var dataSourceName = "[data source name]";
        var indexName = "[index name]";
        var indexerName = "[indexer name]";

        var azureSqlConnectionString = "[Azure SQL connection string]";
        var azureSqlTableName = "[table name]";

        using (var httpClient = new HttpClient())
        {
            var dataSourceDefinition = AzureSqlDatasourceDefinition(azureSqlConnectionString, azureSqlTableName);
            var putDataSourceRequest = PutDataSourceRequest(searchServiceName, apiKey, dataSourceName, dataSourceDefinition);
            Console.WriteLine($"Put data source {putDataSourceRequest.RequestUri}");
            Console.WriteLine();
            var putDataSourceResponse = httpClient.SendAsync(putDataSourceRequest).Result;
            var putDataSourceResponseContent = putDataSourceResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putDataSourceResponseContent);
            Console.WriteLine();

            var indexDefinition = IndexDefinition();
            var putIndexRequest = PutIndexRequest(searchServiceName, apiKey, indexName, indexDefinition);
            Console.WriteLine($"Put index {putIndexRequest.RequestUri}");
            Console.WriteLine();
            var putIndexResponse = httpClient.SendAsync(putIndexRequest).Result;
            var putIndexResponseContent = putIndexResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putIndexResponseContent);
            Console.WriteLine();

            var indexerDefinition = IndexerDefinition(dataSourceName, indexName);
            var putIndexerRequest = PutIndexerRequest(searchServiceName, apiKey, indexerName, indexerDefinition);
            Console.WriteLine($"Put indexer {putIndexerRequest.RequestUri}");
            Console.WriteLine();
            var putIndexerResponse = httpClient.SendAsync(putIndexerRequest).Result;
            var putIndexerResponseContent = putIndexerResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putIndexerResponseContent);
            Console.WriteLine();

            var runIndexerRequest = RunIndexerRequest(searchServiceName, apiKey, indexerName);
            Console.WriteLine($"Run indexer {runIndexerRequest.RequestUri}");
            Console.WriteLine();
            var runIndexerResponse = httpClient.SendAsync(runIndexerRequest).Result;
            Console.WriteLine($"Success: {runIndexerResponse.IsSuccessStatusCode}");
            Console.ReadLine();
        }
    }

    static HttpRequestMessage PutDataSourceRequest(string searchServiceName, string apiKey, string dataSourceName,
        string datasourceDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/datasources/{dataSourceName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(datasourceDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage PutIndexRequest(string searchServiceName, string apiKey, string indexName,
        string indexDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/indexes/{indexName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(indexDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage PutIndexerRequest(string searchServiceName, string apiKey, string indexerName,
        string indexerDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/indexers/{indexerName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(indexerDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage RunIndexerRequest(string searchServiceName, string apiKey, string indexerName)
    {
        var request = new HttpRequestMessage(HttpMethod.Post,
            $"https://{searchServiceName}.search.windows.net/indexers/{indexerName}/run?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        return request;
    }

    static string AzureSqlDatasourceDefinition(string connectionString, string tableName)
    {
        return @"
{
  ""description"": ""azure sql datasource"",
  ""type"": ""azuresql"",
  ""credentials"": { ""connectionString"": """ + connectionString + @""" },
  ""container"": { ""name"": """ + tableName + @""" },
  ""dataChangeDetectionPolicy"": {
    ""@odata.type"": ""#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"",
    ""highWaterMarkColumnName"": ""highwatermark""
  },
  ""dataDeletionDetectionPolicy"": {
    ""@odata.type"": ""#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"",
  ""softDeleteColumnName"": ""deleted"",
  ""softDeleteMarkerValue"": ""true""
  }
}
";
    }

    static string IndexDefinition()
    {
        return @"
{
  ""fields"": [
    {
      ""name"": ""id"",
      ""type"": ""Edm.String"",
      ""key"": true,
      ""searchable"": true,
      ""sortable"": true,
      ""retrievable"": true
    },
    {
      ""name"": ""field1"",
      ""type"": ""Edm.String"",
      ""searchable"": true,
      ""retrievable"": true
    },
    {
      ""name"": ""field3"",
      ""type"": ""Edm.Int32"",
      ""retrievable"": true
    }
  ]
}
";
    }

    static string IndexerDefinition(string dataSourceName, string indexName)
    {
        return @"
{
  ""description"": ""indexer for azure sql datasource"",
  ""dataSourceName"": """ + dataSourceName + @""",
  ""targetIndexName"": """ + indexName + @""",
  ""schedule"": { ""interval"": ""P1D"" }
}
";
    }
}
```

<p>The indexer is scheduled to run once per day. You can set it to run more frequently if the data changes often, but it might affect your search throughput.</p>

<p>This is the table definition if you're interested</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TABLE [dbo].[testtable](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [field1] [nchar](10) NULL,
    [field2] [nchar](10) NULL,
    [field3] [int] NULL,
    [highwatermark] [timestamp] NOT NULL,
    [deleted] [bit] NOT NULL
) ON [PRIMARY]

INSERT INTO [dbo].[testtable] (field1, field2, field3, deleted) VALUES ('abc', 'def', 123, 0)
</code>```

Title: Azure Search using REST c#

Body:
I am trying to run the following code:

public class Item
{
    [JsonProperty(PropertyName = "api-key")]
    public string apikey { get; set; }

}

[[some method]]{
            var url = "https://[search service name].search.windows.net/indexes/temp?api-version=2016-09-01";

            using (var httpClient = new HttpClient())
            {
                using (var request = new HttpRequestMessage(HttpMethod.Put,url))
                {
                    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    var sItem = new Item { apikey = [AzureSearchAdminKey] };
                    var tststring = JsonConvert.SerializeObject(sItem);
                    var body=new  StringContent(tststring, Encoding.UTF8,"application/json" );

                    request.Content =  body;

                    request.Method = HttpMethod.Put;

                    using (HttpResponseMessage response = httpClient.SendAsync(request).Result)
                    {
                        var stringr = response.Content.ReadAsStringAsync().Result;
                        Console.WriteLine(stringr);
                        Console.ReadLine();
                    }

                }
            }

}

I get the following error:
"Error reading JObject from JsonReader. Path '', line 0, position 0."

Could someone from search team tell me what I did wrong?

Body:
The api key should be in the HTTP header, and the index definition should be in the HTTP body.

Here's some sample code for creating a data source, index, and indexer, which reads from an Azure SQL DB and indexes its rows.

class Program
{
    static void Main(string[] args)
    {
        var searchServiceName = "[search service name]";
        var apiKey = "[api key]";

        var dataSourceName = "[data source name]";
        var indexName = "[index name]";
        var indexerName = "[indexer name]";

        var azureSqlConnectionString = "[Azure SQL connection string]";
        var azureSqlTableName = "[table name]";

        using (var httpClient = new HttpClient())
        {
            var dataSourceDefinition = AzureSqlDatasourceDefinition(azureSqlConnectionString, azureSqlTableName);
            var putDataSourceRequest = PutDataSourceRequest(searchServiceName, apiKey, dataSourceName, dataSourceDefinition);
            Console.WriteLine($"Put data source {putDataSourceRequest.RequestUri}");
            Console.WriteLine();
            var putDataSourceResponse = httpClient.SendAsync(putDataSourceRequest).Result;
            var putDataSourceResponseContent = putDataSourceResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putDataSourceResponseContent);
            Console.WriteLine();

            var indexDefinition = IndexDefinition();
            var putIndexRequest = PutIndexRequest(searchServiceName, apiKey, indexName, indexDefinition);
            Console.WriteLine($"Put index {putIndexRequest.RequestUri}");
            Console.WriteLine();
            var putIndexResponse = httpClient.SendAsync(putIndexRequest).Result;
            var putIndexResponseContent = putIndexResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putIndexResponseContent);
            Console.WriteLine();

            var indexerDefinition = IndexerDefinition(dataSourceName, indexName);
            var putIndexerRequest = PutIndexerRequest(searchServiceName, apiKey, indexerName, indexerDefinition);
            Console.WriteLine($"Put indexer {putIndexerRequest.RequestUri}");
            Console.WriteLine();
            var putIndexerResponse = httpClient.SendAsync(putIndexerRequest).Result;
            var putIndexerResponseContent = putIndexerResponse.Content.ReadAsStringAsync().Result;
            Console.WriteLine(putIndexerResponseContent);
            Console.WriteLine();

            var runIndexerRequest = RunIndexerRequest(searchServiceName, apiKey, indexerName);
            Console.WriteLine($"Run indexer {runIndexerRequest.RequestUri}");
            Console.WriteLine();
            var runIndexerResponse = httpClient.SendAsync(runIndexerRequest).Result;
            Console.WriteLine($"Success: {runIndexerResponse.IsSuccessStatusCode}");
            Console.ReadLine();
        }
    }

    static HttpRequestMessage PutDataSourceRequest(string searchServiceName, string apiKey, string dataSourceName,
        string datasourceDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/datasources/{dataSourceName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(datasourceDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage PutIndexRequest(string searchServiceName, string apiKey, string indexName,
        string indexDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/indexes/{indexName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(indexDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage PutIndexerRequest(string searchServiceName, string apiKey, string indexerName,
        string indexerDefinition)
    {
        var request = new HttpRequestMessage(HttpMethod.Put,
            $"https://{searchServiceName}.search.windows.net/indexers/{indexerName}?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        var body = new StringContent(indexerDefinition, Encoding.UTF8, "application/json");
        request.Content = body;
        return request;
    }

    static HttpRequestMessage RunIndexerRequest(string searchServiceName, string apiKey, string indexerName)
    {
        var request = new HttpRequestMessage(HttpMethod.Post,
            $"https://{searchServiceName}.search.windows.net/indexers/{indexerName}/run?api-version=2016-09-01");
        request.Headers.Add("api-key", apiKey);
        return request;
    }

    static string AzureSqlDatasourceDefinition(string connectionString, string tableName)
    {
        return @"
{
  ""description"": ""azure sql datasource"",
  ""type"": ""azuresql"",
  ""credentials"": { ""connectionString"": """ + connectionString + @""" },
  ""container"": { ""name"": """ + tableName + @""" },
  ""dataChangeDetectionPolicy"": {
    ""@odata.type"": ""#Microsoft.Azure.Search.HighWaterMarkChangeDetectionPolicy"",
    ""highWaterMarkColumnName"": ""highwatermark""
  },
  ""dataDeletionDetectionPolicy"": {
    ""@odata.type"": ""#Microsoft.Azure.Search.SoftDeleteColumnDeletionDetectionPolicy"",
  ""softDeleteColumnName"": ""deleted"",
  ""softDeleteMarkerValue"": ""true""
  }
}
";
    }

    static string IndexDefinition()
    {
        return @"
{
  ""fields"": [
    {
      ""name"": ""id"",
      ""type"": ""Edm.String"",
      ""key"": true,
      ""searchable"": true,
      ""sortable"": true,
      ""retrievable"": true
    },
    {
      ""name"": ""field1"",
      ""type"": ""Edm.String"",
      ""searchable"": true,
      ""retrievable"": true
    },
    {
      ""name"": ""field3"",
      ""type"": ""Edm.Int32"",
      ""retrievable"": true
    }
  ]
}
";
    }

    static string IndexerDefinition(string dataSourceName, string indexName)
    {
        return @"
{
  ""description"": ""indexer for azure sql datasource"",
  ""dataSourceName"": """ + dataSourceName + @""",
  ""targetIndexName"": """ + indexName + @""",
  ""schedule"": { ""interval"": ""P1D"" }
}
";
    }
}

The indexer is scheduled to run once per day. You can set it to run more frequently if the data changes often, but it might affect your search throughput.

This is the table definition if you're interested

CREATE TABLE [dbo].[testtable](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [field1] [nchar](10) NULL,
    [field2] [nchar](10) NULL,
    [field3] [int] NULL,
    [highwatermark] [timestamp] NOT NULL,
    [deleted] [bit] NOT NULL
) ON [PRIMARY]

INSERT INTO [dbo].[testtable] (field1, field2, field3, deleted) VALUES ('abc', 'def', 123, 0)

ContentLicense: CC BY-SA 4.0


问:
Makefile multiple definitions errors
In my makefile I have

```<code>readline: readline.h readline.c
    gcc -c -o readline readline.c
car: car.c car.h readline.h
    gcc -c -o car car.c
dealer.o: dealer.c car.h
    gcc -c -o dealer dealer.c
dealer: car.o dealer.o readline.o
    gcc car.o dealer.o readline.o
</code>```

readline.h contains a function prototype that reads in strings that my professor gave us, readline.c is the function,car.c contains a struct with car information, and the various functions for operating on a linked list, dealer.c is where the main function is.

This is my first time with makefiles but I have been getting various errors that are hard to understand saying something about multiple definition of certain functions (some actually in my code and some I guess deep in my code for the system) I don't know why I'm getting these errors.

My goal is to make the main program by linking all the components together.

Errors:

```<code>gcc car.o dealer.o readline.o
dealer.o: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.text+0x0): first defined here
dealer.o: In function `printList':
(.text+0x4ee): multiple definition of `printList'
car.o:car.c:(.text+0x33a): first defined here
dealer.o: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crti.o:(.fini+0x0): first defined here
dealer.o:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.rodata.cst4+0x0): first defined here
dealer.o: In function `__data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.data+0x0): first defined here
dealer.o:(.rodata+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/crtbegin.o:(.rodata+0x0): first defined here
dealer.o: In function `clearList':
(.text+0x5e2): multiple definition of `clearList'
car.o:car.c:(.text+0x42e): first defined here
dealer.o: In function `append_to_list':
(.text+0x1b4): multiple definition of `append_to_list'
car.o:car.c:(.text+0x0): first defined here
dealer.o: In function `find_car':
(.text+0x3db): multiple definition of `find_car'
car.o:car.c:(.text+0x227): first defined here
dealer.o: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crti.o:(.init+0x0): first defined here
readline.o: In function `readLine':
readline.c:(.text+0x0): multiple definition of `readLine'
dealer.o:(.text+0x620): first defined here
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/crtend.o:(.dtors+0x0): multiple definition of `__DTOR_END__'
dealer.o:(.dtors+0x8): first defined here
/usr/bin/ld: error in dealer.o(.eh_frame); no .eh_frame_hdr table will be created.
collect2: ld returned 1 exit status
make: *** [dealer] Error 1
</code>```

I understand what makefiles are for and what they are suppose to do but I cant seem to get this working.

答:
Your makefile makes no sense.

```<code>readline: readline.h readline.c
    gcc -c -o readline readline.c
</code>```

So your target is "readline", but you use -c, so really it is just "readline.o" - very non standard naming convention. Specifically designed to confuse? This will produce an object file (not an exe) called "readline"

```<code>car: car.c car.h readline.h
    gcc -c -o car car.c
</code>```

Same as "readline". This will produce an object file (not an exe) called "car"

```<code>dealer.o: dealer.c car.h
    gcc -c -o dealer dealer.c
</code>```

Not even close: the gcc is creating and object file (not an exe) called "dealer" but the target is "dealer.o". At least this time the -c is used properly - you are trying to make a ".o", it's just that the -o is wrong. Since the target is dealer.o (which is not produced) this will always run trying in vain to make dealer.o

```<code>dealer: car.o dealer.o readline.o
    gcc car.o dealer.o readline.o
</code>```

No -o, so you don't create "dealer", you create "a.out". Nothing even builds car.o, dealer.o or readline.o and so it will never create anything useful. At least there is no -c so this is perhaps closer to correct...

Title: Makefile multiple definitions errors

Body:
In my makefile I have

readline: readline.h readline.c
    gcc -c -o readline readline.c
car: car.c car.h readline.h
    gcc -c -o car car.c
dealer.o: dealer.c car.h
    gcc -c -o dealer dealer.c
dealer: car.o dealer.o readline.o
    gcc car.o dealer.o readline.o

readline.h contains a function prototype that reads in strings that my professor gave us, readline.c is the function,car.c contains a struct with car information, and the various functions for operating on a linked list, dealer.c is where the main function is.

This is my first time with makefiles but I have been getting various errors that are hard to understand saying something about multiple definition of certain functions (some actually in my code and some I guess deep in my code for the system) I don't know why I'm getting these errors.

My goal is to make the main program by linking all the components together.

Errors:

gcc car.o dealer.o readline.o
dealer.o: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.text+0x0): first defined here
dealer.o: In function `printList':
(.text+0x4ee): multiple definition of `printList'
car.o:car.c:(.text+0x33a): first defined here
dealer.o: In function `_fini':
(.fini+0x0): multiple definition of `_fini'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crti.o:(.fini+0x0): first defined here
dealer.o:(.rodata+0x0): multiple definition of `_IO_stdin_used'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.rodata.cst4+0x0): first defined here
dealer.o: In function `__data_start':
(.data+0x0): multiple definition of `__data_start'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.data+0x0): first defined here
dealer.o:(.rodata+0x8): multiple definition of `__dso_handle'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/crtbegin.o:(.rodata+0x0): first defined here
dealer.o: In function `clearList':
(.text+0x5e2): multiple definition of `clearList'
car.o:car.c:(.text+0x42e): first defined here
dealer.o: In function `append_to_list':
(.text+0x1b4): multiple definition of `append_to_list'
car.o:car.c:(.text+0x0): first defined here
dealer.o: In function `find_car':
(.text+0x3db): multiple definition of `find_car'
car.o:car.c:(.text+0x227): first defined here
dealer.o: In function `_init':
(.init+0x0): multiple definition of `_init'
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crti.o:(.init+0x0): first defined here
readline.o: In function `readLine':
readline.c:(.text+0x0): multiple definition of `readLine'
dealer.o:(.text+0x620): first defined here
/usr/lib/gcc/x86_64-redhat-linux/4.4.7/crtend.o:(.dtors+0x0): multiple definition of `__DTOR_END__'
dealer.o:(.dtors+0x8): first defined here
/usr/bin/ld: error in dealer.o(.eh_frame); no .eh_frame_hdr table will be created.
collect2: ld returned 1 exit status
make: *** [dealer] Error 1

I understand what makefiles are for and what they are suppose to do but I cant seem to get this working.

Body:
Your makefile makes no sense.

readline: readline.h readline.c
    gcc -c -o readline readline.c

So your target is "readline", but you use -c, so really it is just "readline.o" - very non standard naming convention. Specifically designed to confuse? This will produce an object file (not an exe) called "readline"

car: car.c car.h readline.h
    gcc -c -o car car.c

Same as "readline". This will produce an object file (not an exe) called "car"

dealer.o: dealer.c car.h
    gcc -c -o dealer dealer.c

Not even close: the gcc is creating and object file (not an exe) called "dealer" but the target is "dealer.o". At least this time the -c is used properly - you are trying to make a ".o", it's just that the -o is wrong. Since the target is dealer.o (which is not produced) this will always run trying in vain to make dealer.o

dealer: car.o dealer.o readline.o
    gcc car.o dealer.o readline.o

No -o, so you don't create "dealer", you create "a.out". Nothing even builds car.o, dealer.o or readline.o and so it will never create anything useful. At least there is no -c so this is perhaps closer to correct...


问:
Are email headers encrypted if using secure SMTP with TLS?
I'm using nodemailer and mailgun to send transactional email from a web application. I have set secure=true when I create the SMTP transport which means:

secure – if true the connection will use TLS when connecting to server. If false (the default) then TLS is used if server supports the STARTTLS extension. In most cases set this value to true if you are connecting to port 465.

For email address confirmation and password reset emails, I add the token to the email header as X-Email-Token to make it easier to test (can just get the value from the header rather than parse the body of the email). Could a mail server that can't read the body of the message read this header field?

答:
Could a mail server that can't read the body of the message read this header field?

Misconception alert: The secure=true option and/or the use of SSL (now obsolete) or TLS to secure e-mail transmission will only secure the communication between the SMTP client and the SMTP server from connection eavesdroppers for that specific connection.

The receiving SMTP server is not necessarily the final recipient's email server.

The recieving SMTP server is capable of forwarding the message on to another SMTP server without using TLS.

The receiving SMTP server could be malicious (e.g. in case someone planted fraudulent DNS MX records) and can read the message contents and do something nefarious with the information contained within.

Given this - TLS does not  provide any kind of "real" e-mail message encryption. SMTP is still the e-mail equivalent of writing messages on postcards without envelopes.

By analogy: using TLS with SMTP is like you driving from your home to an outbound mailbox in the street in a creepy van with tinted-windows, but you put a naked postcard into the mailbox - which means anyone at the postal-service and beyond can still read the message - but at least no-one in the street could read the message while you drove it to the outbound mailbox.

Regarding the distinction between Headers and Body:

An MTA (Mail Transfer Agent, i.e. a mail server) will be able to read the message body and the message headers. In SMTP there is no real distinction between them and TLS is completely blind to all of this as it's only concerned with protecting arbitrary byte streams.

TLS only provides transport-level security, which is the connection between MTA hosts - it doesn't stop an MTA from reading the email. For that you need proper message encryption such as PGP or S/MIME and the recipient's public key.

Opinionated rant: for the effort Google and other Internet companies put into securing the web, it's surprising that there's no real push to secure e-mail. It would not be hard for major e-mail providers like Office 365, Gmail, Outlook.com and others to provide for, at least, message signing (this could be done painlessly by providing message signing provided emails are sent through their own outbound SMTP servers and the user has two-factor auth). The same companies are also capable of setting up a good PKI for the distribution of public-keys. Message signing would pretty much eliminate spam from trusted domain-names overnight, so this is somewhat embarrassing for our species that we still have this problem.


问:
Undefined variable: users (View: C:\xampp\htdocs\rentalmobil\resources\views\admin\user.blade.php)

SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}
</code>```

here is my controller. my controller name is UserController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}
</code>```

and here is my view, it is located in view/admin/ named user.blade.php:

```<code>@extends('admin.header')

@section('content')
<div class="col-md-12">
    <div class="card">
        <div class="header">
            <h4 class="title">Striped Table</h4>
            <p class="category">Here is a subtitle for this table</p>
        </div>
        <div class="content table-responsive table-full-width">
            <table class="table table-striped">
                <thead>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Salary</th>
                    <th>Country</th>
                    <th>City</th>
                </thead>
                <tbody>
                    <tr>
                        <td>1</td>
                        <td>{{ $users->email }}</td>
                        <td>$36,738</td>
                        <td>Niger</td>
                        <td>Oud-Turnhout</td>
                    </tr>
                </tbody>
            </table>

        </div>
    </div>
</div>
@endsection
</code>```

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(

答:
First, the variable will be called admin in the view, because that's how you passed it when you wrote 'admin' => $users.

Second, it's going to be a collection of users, so $users->email isn't going to work. You need to @foreach through each user.

Body:
SOLVED

i am confusing that i think i have already make a true code with laravel. i have seen on many references for me to know how to read database. yes i'm newbie and still learning. well here is my code

from model. admin.php is the name of folder:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Admin extends Model
{
    protected $table = "admin";
}

here is my controller. my controller name is UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Admin;

class UserController extends Controller
{
    public function users(){
        $users = Admin::all();
        return view('admin.user', ['admin' => $users]);
    }

}

and here is my view, it is located in view/admin/ named user.blade.php:

@extends('admin.header')

@section('content')

Striped Table

Here is a subtitle for this table

                    ID
                    Name
                    Salary
                    Country
                    City

                        1
                        {{ $users->email }}
                        $36,738
                        Niger
                        Oud-Turnhout

@endsection

and here is my error

i call from my browser with this http://localhost:8000/users

sorry for bad English :(


答:
This is a different use case for encryption than you're thinking of. With SSL/TLS, both you and the server can read the entire message (including the headers), but somebody who is between you and the server can't.

If you want the server to not be able to read the message, you instead need to use something like GPG, and you're correct that you can't encrypt the headers that way or the server won't be able to deliver the message.

Title: Are email headers encrypted if using secure SMTP with TLS?

Body:
I'm using nodemailer and mailgun to send transactional email from a web application. I have set secure=true when I create the SMTP transport which means:

secure – if true the connection will use TLS when connecting to server. If false (the default) then TLS is used if server supports the STARTTLS extension. In most cases set this value to true if you are connecting to port 465.

For email address confirmation and password reset emails, I add the token to the email header as X-Email-Token to make it easier to test (can just get the value from the header rather than parse the body of the email). Could a mail server that can't read the body of the message read this header field?


问:
reflection of erb variables
I'm using a puppet template, which does an erb interpretation of the template file.  I'd like to know all the variables available to me, however, there are variables available (e.g., fqdn) that are not listed by any of the reflection methods I'm aware of, specifically, none of these:

```<code><% Module.constants.each do |v| %># module constant: <%= v %>
<% end %>
<% Kernel.local_variables.each do |v| %># local variable: <%= v %>
<% end %>
<% Kernel.instance_variables.each do |v| %># instance variable: <%= v %>
<% end %>
<% Module.class_variables.each do |v| %># class variable: <%= v %>
<% end %>
<% Kernel.global_variables.each do |v| %># global variable: <%= v %>
<% end %>
</code>```

Is there an extra reflection method for erb that will reveal these to me?

答: Don't really know about puppet templates, but if fqdn is a local variable, then calling local_variables (as in self.local_variables) should display it.

ContentLicense: CC BY-SA 2.5

Title: reflection of erb variables

Body:
I'm using a puppet template, which does an erb interpretation of the template file.  I'd like to know all the variables available to me, however, there are variables available (e.g., fqdn) that are not listed by any of the reflection methods I'm aware of, specifically, none of these:

<% Module.constants.each do |v| %># module constant: <%= v %>
<% end %>
<% Kernel.local_variables.each do |v| %># local variable: <%= v %>
<% end %>
<% Kernel.instance_variables.each do |v| %># instance variable: <%= v %>
<% end %>
<% Module.class_variables.each do |v| %># class variable: <%= v %>
<% end %>
<% Kernel.global_variables.each do |v| %># global variable: <%= v %>
<% end %>

Is there an extra reflection method for erb that will reveal these to me?


问:
Django form validation don't function
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

```<code>class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer
</code>```

Also I have try this way:

```<code>def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)
</code>```

In this case the view corresponding to this form is the following one:

```<code>def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)
</code>```

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

```<code><div class="col-md-6">
        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}
    </div>

<script>

    $(function() {
        var counter = 94;
        $( "#enviar" ).click(function() {
            counter = counter + 1;
                //alert(counter);
                localStorage.setItem("counter",counter);
                alert('Su pregunta ha sido enviada correctamente. ' +
                    'Envía otra y tendras más posibilidades de ganar los Airpods.');
            });
        $('#askFortm').on('submit', function(e) {
              e.preventDefault();
              setTimeout(function() {
                   window.location.reload();
              },0);
              this.submit();
        });
    });

    </script>
</code>```

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.

答:
```<code>class QuestionForm(forms.Form):
    subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
    question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
    answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
    answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

    def clean_question(self):
        question = self.cleaned_data.get('question')
        a = "0"
        if a not in question:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return question

    def clean_answer(self):
        answer = self.cleaned_data.get('answer')
        a = "0"
        if a not in answer:
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return answer
</code>```

Title: Django form validation don't function

Body:
I try to put validations in my form but after I follow the official documentation and tutorials I don't obtain the solution.
This is my code:
(The variables of class are indented)

class QuestionForm(forms.Form):
subject = forms.CharField(widget=forms.Select(attrs={'class': 'select'},
                          choices=SUBJECTS_SELE),
                          label='Materia')
question = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                           label='Pregunta',
                           max_length=5000)
answer = forms.CharField(widget=forms.Textarea(attrs={'class': 'form-control', 'rows': 1}),
                         label='Respuesta correcta',
                         max_length=1000)
answerOne = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'rows': 1}),
                            label='Respuesta incorrecta',
                            max_length=1000,
                            required=True)

def clean_question(self):
     question = self.cleaned_data.get('question')
     a = "0"
     if not a in question:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return question

def clean_answer(self):
     answer = self.cleaned_data.get('answer')
     a = "0"
     if not a in answer:
         raise forms.ValidationError("Es obligatorio llenar este campo")
     return answer

Also I have try this way:

def clean(self, *args, **kwargs):
        question = self.cleaned_data.get('question')
        answer = self.cleaned_data.get('answer')
        if question != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        if answer != "0":
            raise forms.ValidationError("Es obligatorio llenar este campo")
        return super(QuestionForm, self).clean(*args, **kwargs)

In this case the view corresponding to this form is the following one:

def ayudanos(request):
    form = QuestionForm(request.POST or None)
    if form.is_valid():
        form_data = form.cleaned_data
        subject = form_data.get("subject")
        question = form_data.get("question")
        answer = form_data.get("answer")
        answerOne = form_data.get("answerOne")
        answerTwo = form_data.get("answerTwo")
        name = form_data.get("name")
        obj = QuestionSele.objects.create(subject=subject, question=question, answer=answer, answerOne=answerOne,
                                          answerTwo=answerTwo, name=name)
    context = {
        "form": form
    }
    return render(request, "ayudanos.html", context)

Where the variables passed to the object is for save in a BBDD.

ACTUALIZED--------------------

After try the options people recommended my in the comments, I didn't see the validation message, and the moment I have remove the part of code which reload page after doing the form I could see the validation message.

my html and JavaScript:

        {% if form %}
        <form action="" method="POST" id="askFortm"> {% csrf_token %}
          {{ form.as_p }}
          <button class="btn btn-lg btn-primary enviar" id="enviar" type="submit" value="Enviar">Introducir otra
              pregunta</button>
          </form>
          {% endif %}

I suppose that the problem can be relation with the reload page,  is possible I have to compare the csrf_token or something like this?
Can you help me, thanks.


问:
How do I read a text file as a list of lists in python
I have a large text file like this separated into different lines:

35 4 23 12 8 \n
23 6 78 3 5 \n
27 4 9 10 \n
73 5 \n

I need to convert it to a list of lists, each line a separate element like this:

[[35, 4, 23, 12, 8], [23, 6, 78, 3, 5], [27, 4, 9, 10], [73, 5], .......]

答:
```<code>lines = [line.split() for line in open('yourtextfile.txt')]  # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers.
</code>```

Alternatively, the following will also convert your values to int:

```<code>lines = [[int(v) for v in line.split()] for line in open('yourtextfile.txt')] # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers that are converted to int()
</code>```

Body:
lines = [line.split() for line in open('yourtextfile.txt')]  # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers.

Alternatively, the following will also convert your values to int:

lines = [[int(v) for v in line.split()] for line in open('yourtextfile.txt')] # opens the text file and calls .split() on every line, effectively splitting on every space, creating a list of numbers that are converted to int()


问:
CGAffineTransform scale with slider
I have a UISlider which goes from 0 to 275. I want to use the slider to scale an UIImageView.

When my slider value is 0 my UIImageView should have the original size (scaleX: 1, scaleY: 1).

When my slider value is 275 my UIImageView should scale to 0.85.

Can someone suggest a good formula to calculate the scale value in relationship with slider value?

Something like this

```<code>let scale = slider.value >= 275 ? 0.85 : 1
imageView.transform = CGAffineTransform(scaleX: scale, scaleY: scale)
</code>```

But I have some trouble making the scale dynamic based on slider value.

答:
You could use a linear scale such as:</p>

```<code>let scale = 1.0 - slider.value/275.0 * 0.15
</code>```

Title: CGAffineTransform scale with slider

Body:
I have a UISlider which goes from 0 to 275. I want to use the slider to scale an UIImageView.

When my slider value is 0 my UIImageView should have the original size (scaleX: 1, scaleY: 1).

When my slider value is 275 my UIImageView should scale to 0.85.

Can someone suggest a good formula to calculate the scale value in relationship with slider value?

Something like this

let scale = slider.value >= 275 ? 0.85 : 1
imageView.transform = CGAffineTransform(scaleX: scale, scaleY: scale)

But I have some trouble making the scale dynamic based on slider value.

Body:
You could use a linear scale such as:

let scale = 1.0 - slider.value/275.0 * 0.15


问:
How to play the video from raw folder using intent?
I am getting the exception as:

Android.Content.ActivityNotFoundException: No Activity found to
  handle Intent.

```<code>var video = Android.Net.Uri.Parse(@"android.resource://" +
Forms.Context.PackageName + "/Raw/" + Resource.Raw.sampleVideo);
Intent intent = new Intent(Intent.ActionView, video);
intent.SetDataAndType(video,"video/*");
Forms.Context.StartActivity(intent);
</code>```

答:
get the uri from raw folder in xamarin.android

Here is what you what :

```<code>string rawPath = "android.resource://" + PackageName + "/" + Resource.Raw.audio;
Android.Net.Uri uri = Android.Net.Uri.Parse((rawPath));
</code>```

Body:
I am getting the exception as:

Android.Content.ActivityNotFoundException: No Activity found to
  handle Intent.

var video = Android.Net.Uri.Parse(@"android.resource://" +
Forms.Context.PackageName + "/Raw/" + Resource.Raw.sampleVideo);
Intent intent = new Intent(Intent.ActionView, video);
intent.SetDataAndType(video,"video/*");
Forms.Context.StartActivity(intent);

Body:
get the uri from raw folder in xamarin.android

Here is what you what :

string rawPath = "android.resource://" + PackageName + "/" + Resource.Raw.audio;
Android.Net.Uri uri = Android.Net.Uri.Parse((rawPath));


问:
Oracle EXECUTE IMMEDIATE into a cursor
I have a stored procedure which used the EXECUTE IMMEDIATE command to execute a very long string. How do I support a very long string and return the data into a refcursor?

答:
Assuming that your SQL is not longer than 32K (as @Tony Andrews hinted at), you should be able to use something like this:

```<code>declare
   SQL_Text varchar2(32760) := 'select * from dual'; --your query goes here
   cur sys_refcursor;
begin
   open cur for SQL_Text;
end;
</code>```

When working with Ref Cursors, open-for can be used directly, instead of execute immediate.

Title: Oracle EXECUTE IMMEDIATE into a cursor

Body:
Assuming that your SQL is not longer than 32K (as @Tony Andrews hinted at), you should be able to use something like this:

declare
   SQL_Text varchar2(32760) := 'select * from dual'; --your query goes here
   cur sys_refcursor;
begin
   open cur for SQL_Text;
end;

When working with Ref Cursors, open-for can be used directly, instead of execute immediate.