问:
Loop is only taking last line of data from the file and adding more characters?
Edit2/8 1PM: fixed format of the code, added more detail to better understand what I am asking because I wrote this in a rush.
I am making a file converter in python and for some reason it only takes the last line of the example file I made and it adds brackets "['']" I don't want in it probably because it's collected data? I don't know how to make the loop so it collects the data in each row/column and spits it back out while also keeping the csv header parts in.

```<code>info = pd.read_csv(filename)
f = open(filename)
csv_f = csv.reader(f)
header=[]
data=[]
things=[]

n = -2
m = 0
i = -1

for col in info.columns:
    header.append(col)
    print(header)

for row in csv_f:
    data.append(row)
    for things in data[1:]:
        print(things)

num = len(things)
file = open('output.xml', 'w')

while num > 0:
    n+=1
    m+=1
    i+=1
    num -= 1

    print("""<%s>""" % (header[i:m]))
    print("""%s""" % (things[i:m]))
    print("""</%s>""" % (header[i:m]))

    if num > 0:
        file.write("""<%s>%s</%s>""" %(header[i:m], things[i:m], header[i:m]))
    else:
        file.close
</code>```

答:
I tried to rewrite your code, you can add print, to see the results.
I was inspired by this answer

```<code>import csv
import pandas as pd

f = open(filename)
csv_f = csv.reader(f)
info = pd.read_csv(filename)

header= list(info.columns)
#print(header)

data = []

for row in csv_f:
   data.append(row)
#print(data)

def convert_row(row):
     str_row = """<%s>%s</%s>"""*len(header)
     var_values = [list_of_elments[k] for k in range(len(header)) for list_of_elments in [header,row,header]]
     var_values =tuple(var_values)
     return str_row % var_values

#print('\n'.join([convert_row(row) for row in data[1:]]))
with open('output.xml', 'w') as myfile:
  myfile.write('\n'.join([convert_row(row) for row in data]))
</code>```

For example for :

I have got this result

I'm not sure if it's the expected result as I'm not familiar with the xml format.

Edit 1 :

I had to add a head and tail, so I added "<data>" and "</data>" (you can call it something else). I also made a small change on the function convert_row (to convert row by row to xml).

```<code>import csv

import pandas as pd
f = open(filename)
csv_f = csv.reader(f)

info = pd.read_csv(filename)
print(info)

header= list(info.columns)

data = []

for row in csv_f:
   data.append(row)

def convert_row(row):
     str_row = """<%s>%s</%s> \n"""*(len(header)-1)
     str_row = """<%s>%s""" +"\n"+ str_row + """</%s>"""
     var_values = [list_of_elments[k] for k in range(1,len(header)) for list_of_elments in [header,row,header]]
     var_values = [header[0],row[0]]+var_values+[header[0]]
     var_values =tuple(var_values)
     return str_row % var_values

#text ="<data>"+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</data>"
#print(text)
with open('output.xml', 'w') as myfile:
  myfile.write("<data>"+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</data>")
</code>```

Now you will be able to get an output.xml file and open it.

Edit 2 :

A simpler solution is to use pandas directly with df.to_xml(), for example :

```<code>info = pd.read_csv(filename)

#print(info.to_xml())
with open('outputf.xml', 'w') as myfile:
  myfile.write(info.to_xml())
</code>```

Body:
Edit2/8 1PM: fixed format of the code, added more detail to better understand what I am asking because I wrote this in a rush.
I am making a file converter in python and for some reason it only takes the last line of the example file I made and it adds brackets "['']" I don't want in it probably because it's collected data? I don't know how to make the loop so it collects the data in each row/column and spits it back out while also keeping the csv header parts in.

info = pd.read_csv(filename)
f = open(filename)
csv_f = csv.reader(f)
header=[]
data=[]
things=[]

n = -2
m = 0
i = -1

for col in info.columns:
    header.append(col)
    print(header)

for row in csv_f:
    data.append(row)
    for things in data[1:]:
        print(things)

num = len(things)
file = open('output.xml', 'w')

while num > 0:
    n+=1
    m+=1
    i+=1
    num -= 1

    print("""<%s>""" % (header[i:m]))
    print("""%s""" % (things[i:m]))
    print("""</%s>""" % (header[i:m]))

    if num > 0:
        file.write("""<%s>%s</%s>""" %(header[i:m], things[i:m], header[i:m]))
    else:
        file.close

Body:
I tried to rewrite your code, you can add print, to see the results.
I was inspired by this answer

import csv
import pandas as pd

f = open(filename)
csv_f = csv.reader(f)
info = pd.read_csv(filename)

header= list(info.columns)
#print(header)

data = []

for row in csv_f:
   data.append(row)
#print(data)

def convert_row(row):
     str_row = """<%s>%s</%s>"""*len(header)
     var_values = [list_of_elments[k] for k in range(len(header)) for list_of_elments in [header,row,header]]
     var_values =tuple(var_values)
     return str_row % var_values

#print('\n'.join([convert_row(row) for row in data[1:]]))
with open('output.xml', 'w') as myfile:
  myfile.write('\n'.join([convert_row(row) for row in data]))

For example for :

I have got this result

I'm not sure if it's the expected result as I'm not familiar with the xml format.

Edit 1 :

I had to add a head and tail, so I added "<data>" and "</data>" (you can call it something else). I also made a small change on the function convert_row (to convert row by row to xml).

import csv

import pandas as pd
f = open(filename)
csv_f = csv.reader(f)

info = pd.read_csv(filename)
print(info)

header= list(info.columns)

data = []

for row in csv_f:
   data.append(row)

def convert_row(row):
     str_row = """<%s>%s</%s> \n"""*(len(header)-1)
     str_row = """<%s>%s""" +"\n"+ str_row + """</%s>"""
     var_values = [list_of_elments[k] for k in range(1,len(header)) for list_of_elments in [header,row,header]]
     var_values = [header[0],row[0]]+var_values+[header[0]]
     var_values =tuple(var_values)
     return str_row % var_values

#text ="<data>"+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</data>"
#print(text)
with open('output.xml', 'w') as myfile:
  myfile.write("<data>"+"\n"+'\n'.join([convert_row(row) for row in data[1:]])+"\n" +"</data>")

Now you will be able to get an output.xml file and open it.

Edit 2 :

A simpler solution is to use pandas directly with df.to_xml(), for example :

info = pd.read_csv(filename)

#print(info.to_xml())
with open('outputf.xml', 'w') as myfile:
  myfile.write(info.to_xml())


来源: stackexchange

问:
How to print a generator expression?
In the Python shell, if I enter a list comprehension such as:

```<code>>>> [x for x in string.letters if x in [y for y in "BigMan on campus"]]
</code>```

I get a nicely printed result:

```<code>['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']
</code>```

Same for a dictionary comprehension:

```<code>>>> {x:x*2 for x in range(1,10)}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}
</code>```

If I enter a generator expression, I get not such a friendly response:

```<code>>>> (x for x in string.letters if x in (y for y in "BigMan on campus"))
<generator object <genexpr> at 0x1004a0be0>
</code>```

I know I can do this:

```<code>>>> for i in _: print i,
a c g i m n o p s u B M
</code>```

Other than that (or writing a helper function) can I easily evaluate and print that generator object in the interactive shell?

答:
Generator object do not store actual data, it is basically just an expression. Program can not print what will be value of an expression without evaluating it. Generator object(generator expression) can be evaluated by typecasting into any iterable data type.

eg.

```<code>list(genexpr)
dict(genexpr)
set(genexpr)
for data in genexpr:
</code>```

Additional

generating generator expression and then typecasting is 20% slower than directly creating required datatype object. So if we require whole data it's better to use

```<code>data=[x for x in range(0,10)]
</code>```

than using

```<code>genexpr=(x for x in range(0,10))
data=list(genexpr)
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to print a generator expression?

Body:
In the Python shell, if I enter a list comprehension such as:

>>> [x for x in string.letters if x in [y for y in "BigMan on campus"]]

I get a nicely printed result:

['a', 'c', 'g', 'i', 'm', 'n', 'o', 'p', 's', 'u', 'B', 'M']

Same for a dictionary comprehension:

>>> {x:x*2 for x in range(1,10)}
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

If I enter a generator expression, I get not such a friendly response:

>>> (x for x in string.letters if x in (y for y in "BigMan on campus"))
<generator object <genexpr> at 0x1004a0be0>

I know I can do this:

>>> for i in _: print i,
a c g i m n o p s u B M

Other than that (or writing a helper function) can I easily evaluate and print that generator object in the interactive shell?

Body:
Generator object do not store actual data, it is basically just an expression. Program can not print what will be value of an expression without evaluating it. Generator object(generator expression) can be evaluated by typecasting into any iterable data type.

eg.

list(genexpr)
dict(genexpr)
set(genexpr)
for data in genexpr:

Additional

generating generator expression and then typecasting is 20% slower than directly creating required datatype object. So if we require whole data it's better to use

data=[x for x in range(0,10)]

than using

genexpr=(x for x in range(0,10))
data=list(genexpr)


问:
Count the existence number of a key in a list of dictionary
I used gspread and pandas to convert my google sheet into a list of dictionaries. The example list is shown as follows: (It's a very long list, so I only list a few lines)

```<code>mylist = [
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]
</code>```

I want to count the number of the existence of some keys, for example Mike and Jane in the Receiver field. I tried the following to count the total number of the rows, and I think I may use a similar code

```<code>counts = collections.Counter()
for d in package2019:
    counts.update(d.keys())
count_list = [{c: counts[c] for c in d} for d in mylist]
</code>```

I just don't know how should I count the number of existence for some keys. I'm new to python and I searched anywhere online with no luck

答:
you can use len() and a generator:

```<code>len(tuple(d for d in my_list if d['Receiver'] == 'Mike'))
</code>```

you can use len() and filter():

```<code>len(tuple(filter(lambda d: d['Receiver'] == 'Mike', my_list)))
</code>```

you can use sum() and map():

```<code>sum(map(lambda d: d['Receiver'] == 'Mike', my_list))
</code>```

this counts all the Mikes, if you want the Janes too, you have to add it to the condition.

Body:
I used gspread and pandas to convert my google sheet into a list of dictionaries. The example list is shown as follows: (It's a very long list, so I only list a few lines)

mylist = [
{'StartDate': '2021-10-02', 'ID': 11773, 'Receiver': Mike, 'Days':66 },
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Jane, 'Days':65},
{'StartDate': '2021-10-03', 'ID': 15673, 'Receiver': Mike, 'Days':65},
...
{'StartDate': '2021-10-5', 'ID': 34653, 'Receiver': Jack, 'Days':63}]

I want to count the number of the existence of some keys, for example Mike and Jane in the Receiver field. I tried the following to count the total number of the rows, and I think I may use a similar code

counts = collections.Counter()
for d in package2019:
    counts.update(d.keys())
count_list = [{c: counts[c] for c in d} for d in mylist]

I just don't know how should I count the number of existence for some keys. I'm new to python and I searched anywhere online with no luck

Body:
you can use len() and a generator:

len(tuple(d for d in my_list if d['Receiver'] == 'Mike'))

you can use len() and filter():

len(tuple(filter(lambda d: d['Receiver'] == 'Mike', my_list)))

you can use sum() and map():

sum(map(lambda d: d['Receiver'] == 'Mike', my_list))

this counts all the Mikes, if you want the Janes too, you have to add it to the condition.


问:
Typecasting array object
I struct at a point in my application.I have an array object called time and a global int variable as index..so when I need to use both I need to type cast array object to integer value.How can I do this?Please help..

```<code>NSArray *time=[NSArray arrayWithObjects:@"1.08",@"1.12",@"1.14",@"1.18",@"1.20",@"1.24",@"1.25",@"1.29",@"1.30",@"1.34",@"1.45",@"1.50",@"1.51",@"1.55",@"1.56",@"2.00",@"2.01",@"2.06",@"2.07",@"2.11",@"2.12",@"2.16",@"2.17",@"2.21",nil];
index = 0;
</code>```

```
[self performSelector:@selector(startAnimation) withObject:self afterDelay:[time objectAtIndex:index]];
```

This is my code,but it is giving error and telling to typecast

答: Try [[time objectAtIndex:index] floatValue]. The objects in array are strings and you can get the float value by calling [myStr floatValue]. You can also use doubleValue here.

ContentLicense: CC BY-SA 3.0

Title: Typecasting array object

Body:
I struct at a point in my application.I have an array object called time and a global int variable as index..so when I need to use both I need to type cast array object to integer value.How can I do this?Please help..

NSArray *time=[NSArray arrayWithObjects:@"1.08",@"1.12",@"1.14",@"1.18",@"1.20",@"1.24",@"1.25",@"1.29",@"1.30",@"1.34",@"1.45",@"1.50",@"1.51",@"1.55",@"1.56",@"2.00",@"2.01",@"2.06",@"2.07",@"2.11",@"2.12",@"2.16",@"2.17",@"2.21",nil];
index = 0;

[self performSelector:@selector(startAnimation) withObject:self afterDelay:[time objectAtIndex:index]];

This is my code,but it is giving error and telling to typecast


问:
How can I pass an alias value to a bazel function?
I have the following alias defined in a BUILD file:

```<code>alias(
    name = "platform",
    actual = select({
        ":macos_x86_64": "macos_x86_64",
        ":linux_x86_64": "linux_x86_64",
        ":linux_aarch64": "linux_aarch64",
    }),
    visibility = ["//visibility:public"],
)
</code>```

How can I pass the "actual" string to a function like this?

```<code>def myFunction(platform): ...
</code>```

I am trying the most naive thing and it does not understand that it's an alias, not a string:

```<code>myFunction("//bazel/config:platform")
</code>```

答:
def myFunction creates a macro, not a rule. Macros can't access the values of a select, only add other selects to it and pass it to rules. Another way to think about the difference: there are very few things a macro can do which can't be done directly in a BUILD file.

Also, alias.actual is a Label. Even when you pass it to a rule, the values need to be valid labels, and will be handled as such. You can use Label.name to get the name back though.

Body:
I have the following alias defined in a BUILD file:

alias(
    name = "platform",
    actual = select({
        ":macos_x86_64": "macos_x86_64",
        ":linux_x86_64": "linux_x86_64",
        ":linux_aarch64": "linux_aarch64",
    }),
    visibility = ["//visibility:public"],
)

How can I pass the "actual" string to a function like this?

def myFunction(platform): ...

I am trying the most naive thing and it does not understand that it's an alias, not a string:

myFunction("//bazel/config:platform")


问:
how to obtain execution plan from a PLSQL
I have a code snippet like :

```<code>declare
    cursor c is select ....
begin
    for i in c loop
        update table t1 where ti.c1 = i.column ...
    end loop;
end;
</code>```

I am wondering how to obtain an execution plan from the update statement since there is involved a condition between a column from a table and a column from cursor.

Can anyone give me a hint, please?

Thank you.

答:
The simplest way might be to capture the plan while it's executing, by noting the sql_id and sql_child_number from v$session, and running

```<code>select plan_table_output
from   table(dbms_xplan.display_cursor(sql_id, sql_child_number));
</code>```

Alternatively, you can embed the call in the PL/SQL for testing purposes and have it output the plan using dbms_output.put_line. (The plan will be the same for every loop iteration, unless you want to check the actual row counts etc, so I have added an exit; statement to make it stop after one execution.)

```<code>declare
    cursor c is select * from departments;
begin
    for r in c loop
        update employees e set e.email = e.email
        where  e.department_id = r.department_id;

        for p in (
            select p.plan_table_output
            from   table(dbms_xplan.display_cursor(null,null,'ALLSTATS LAST')) p
        )
        loop
            dbms_output.put_line(p.plan_table_output);
        end loop;

        rollback;
        exit;
    end loop;
end;
</code>```

Which in my 19c demo HR schema gives:

SQL_ID  b5xbwbu4kd3r4, child number 1
-------------------------------------
UPDATE EMPLOYEES E SET E.EMAIL = E.EMAIL WHERE E.DEPARTMENT_ID = :B1

Plan hash value: 4075606039

-------------------------------------------------------------------------------------------------
| Id  | Operation         | Name              | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
-------------------------------------------------------------------------------------------------
|   0 | UPDATE STATEMENT  |                   |      1 |        |      0 |00:00:00.01 |       4 |
|   1 |  UPDATE           | EMPLOYEES         |      1 |        |      0 |00:00:00.01 |       4 |
|*  2 |   INDEX RANGE SCAN| EMP_DEPARTMENT_IX |      1 |      1 |      1 |00:00:00.01 |       1 |
-------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("E"."DEPARTMENT_ID"=:B1)
```
<p>To get the actual row counts as displayed above you would need to</p>
```alter session set statistics_level = all;
```

or else include the /*+ gather_plan_statistics */ hint in the update.

Body:
I have a code snippet like :

declare
    cursor c is select ....
begin
    for i in c loop
        update table t1 where ti.c1 = i.column ...
    end loop;
end;

I am wondering how to obtain an execution plan from the update statement since there is involved a condition between a column from a table and a column from cursor.

Can anyone give me a hint, please?

Thank you.

Body:
The simplest way might be to capture the plan while it's executing, by noting the sql_id and sql_child_number from v$session, and running

select plan_table_output
from   table(dbms_xplan.display_cursor(sql_id, sql_child_number));

Alternatively, you can embed the call in the PL/SQL for testing purposes and have it output the plan using dbms_output.put_line. (The plan will be the same for every loop iteration, unless you want to check the actual row counts etc, so I have added an exit; statement to make it stop after one execution.)

declare
    cursor c is select * from departments;
begin
    for r in c loop
        update employees e set e.email = e.email
        where  e.department_id = r.department_id;

        for p in (
            select p.plan_table_output
            from   table(dbms_xplan.display_cursor(null,null,'ALLSTATS LAST')) p
        )
        loop
            dbms_output.put_line(p.plan_table_output);
        end loop;

        rollback;
        exit;
    end loop;
end;

Which in my 19c demo HR schema gives:

SQL_ID  b5xbwbu4kd3r4, child number 1
-------------------------------------
UPDATE EMPLOYEES E SET E.EMAIL = E.EMAIL WHERE E.DEPARTMENT_ID = :B1

Plan hash value: 4075606039

-------------------------------------------------------------------------------------------------
| Id  | Operation         | Name              | Starts | E-Rows | A-Rows |   A-Time   | Buffers |
-------------------------------------------------------------------------------------------------
|   0 | UPDATE STATEMENT  |                   |      1 |        |      0 |00:00:00.01 |       4 |
|   1 |  UPDATE           | EMPLOYEES         |      1 |        |      0 |00:00:00.01 |       4 |
|*  2 |   INDEX RANGE SCAN| EMP_DEPARTMENT_IX |      1 |      1 |      1 |00:00:00.01 |       1 |
-------------------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("E"."DEPARTMENT_ID"=:B1)

To get the actual row counts as displayed above you would need to

alter session set statistics_level = all;

or else include the /*+ gather_plan_statistics */ hint in the update.


问:
Calculate weekly hours of operation in T-SQL from overlapping date/time data?
I am trying to calculate the number of hours of operation per week for each facility in a region. The part I am struggling with is that there are multiple programs each day that overlap which contribute to the total hours.

Here is a sample of the table I am working with:

location
program
date
start_time
end_time

a
1
09-22-21
14:45:00
15:45:00

a
2
09-22-21
15:30:00
16:30:00

b
88
09-22-21
10:45:00
12:45:00

b
89
09-22-21
10:45:00
14:45:00

I am hoping to get:

location
hours of operation

a
1.75

b
4

I've tried using SUM DATEDIFF with some WHERE statements but couldn't get them to work. What I have found is how to identify the overlapping ranges(Detect overlapping date ranges from the same table), but not how to sum the difference to get the desired outcome of total non-overlapping hours of operation.

答:
Believe you are trying to identify the total hours of operation for each location. Now because some programs can overlap, you want to rule those out. To do this, I generate a tally table of each possible 15 minute increment in the date and then count the time periods that have a program operating

Identify Total Hours of Operation per Date

```<code>DROP TABLE IF EXISTS #OperationSchedule
CREATE TABLE #OperationSchedule (ID INT IDENTITY(1,1),Location CHAR(1),Program INT,OpDate DATE,OpStart TIME(0),OpEnd TIME(0))
INSERT INTO #OperationSchedule
VALUES ('a',1,'09-22-21','14:45:00','15:45:00')
,('a',2,'09-22-21','15:30:00','16:30:00')
,('b',88,'09-22-21','10:45:00','12:45:00')
,('b',89,'09-22-21','10:45:00','14:45:00');

/*1 row per 15 minute increment in a day*/
;WITH cte_TimeIncrement AS (
    SELECT StartTime = CAST('00:00' AS TIME(0))
    UNION ALL
    SELECT DATEADD(minute,15,StartTime)
    FROM cte_TimeIncrement
    WHERE StartTime < '23:45'
),
/*1 row per date in data*/
cte_DistinctDate AS (
    SELECT OpDate
    FROM #OperationSchedule
    GROUP BY OpDate
),
/*Cross join to generate 1 row for each time increment*/
cte_DatetimeIncrement AS (
SELECT *
FROM cte_DistinctDate
CROSS JOIN cte_TimeIncrement
)

/*Join and count each time interval that has a match to identify times when location is operating*/
SELECT Location
    ,A.OpDate
    ,HoursOfOperation = CAST(COUNT(DISTINCT StartTime) * 15/60.0 AS Decimal(4,2))
FROM cte_DatetimeIncrement AS A
INNER JOIN #OperationSchedule AS B
    ON A.OpDate = B.OpDate
    AND A.StartTime >= B.OpStart
    AND A.StartTime < B.OpEnd
GROUP BY Location,A.OpDate
</code>```

Body:
Believe you are trying to identify the total hours of operation for each location. Now because some programs can overlap, you want to rule those out. To do this, I generate a tally table of each possible 15 minute increment in the date and then count the time periods that have a program operating

Identify Total Hours of Operation per Date

DROP TABLE IF EXISTS #OperationSchedule
CREATE TABLE #OperationSchedule (ID INT IDENTITY(1,1),Location CHAR(1),Program INT,OpDate DATE,OpStart TIME(0),OpEnd TIME(0))
INSERT INTO #OperationSchedule
VALUES ('a',1,'09-22-21','14:45:00','15:45:00')
,('a',2,'09-22-21','15:30:00','16:30:00')
,('b',88,'09-22-21','10:45:00','12:45:00')
,('b',89,'09-22-21','10:45:00','14:45:00');

/*1 row per 15 minute increment in a day*/
;WITH cte_TimeIncrement AS (
    SELECT StartTime = CAST('00:00' AS TIME(0))
    UNION ALL
    SELECT DATEADD(minute,15,StartTime)
    FROM cte_TimeIncrement
    WHERE StartTime < '23:45'
),
/*1 row per date in data*/
cte_DistinctDate AS (
    SELECT OpDate
    FROM #OperationSchedule
    GROUP BY OpDate
),
/*Cross join to generate 1 row for each time increment*/
cte_DatetimeIncrement AS (
SELECT *
FROM cte_DistinctDate
CROSS JOIN cte_TimeIncrement
)

/*Join and count each time interval that has a match to identify times when location is operating*/
SELECT Location
    ,A.OpDate
    ,HoursOfOperation = CAST(COUNT(DISTINCT StartTime) * 15/60.0 AS Decimal(4,2))
FROM cte_DatetimeIncrement AS A
INNER JOIN #OperationSchedule AS B
    ON A.OpDate = B.OpDate
    AND A.StartTime >= B.OpStart
    AND A.StartTime < B.OpEnd
GROUP BY Location,A.OpDate


问:
Fastest way of numbering instances of a value within a vector
I am looking to number each instance of a value in a vector as it appears. For example the first instance of a value with get '1' the second instance will get '2' and so on - counting how many this value has appeared before it in the vector. I can do this with a for loop in R using the EuStockMarkets example data in datasets.

```<code>#load data
data <- as.data.frame(datasets::EuStockMarkets)
df <- data.frame(order = 1:nrow(data),value = data$DAX)
head(df)

#calculate number of instances
start_time <- Sys.time()
for (i in 1:nrow(df)) {
 df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
}
end_time <- Sys.time()
end_time - start_time
#Time difference of 0.1126978 secs
</code>```

This is fine but I would rather not use a for loop if there was a faster option for much larger datasets and was wondering if their was a preexisting function that - perhaps with tidyverse package.

答:
With data.table:

```<code>library(data.table)
setDT(df)

df[,instance2:=seq_len(.N),by=value]

identical(df$instance,df$instance2)
[1] TRUE
</code>```

Body:
I am looking to number each instance of a value in a vector as it appears. For example the first instance of a value with get '1' the second instance will get '2' and so on - counting how many this value has appeared before it in the vector. I can do this with a for loop in R using the EuStockMarkets example data in datasets.

#load data
data <- as.data.frame(datasets::EuStockMarkets)
df <- data.frame(order = 1:nrow(data),value = data$DAX)
head(df)

#calculate number of instances
start_time <- Sys.time()
for (i in 1:nrow(df)) {
 df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
}
end_time <- Sys.time()
end_time - start_time
#Time difference of 0.1126978 secs

This is fine but I would rather not use a for loop if there was a faster option for much larger datasets and was wondering if their was a preexisting function that - perhaps with tidyverse package.

Body:
With data.table:

library(data.table)
setDT(df)

df[,instance2:=seq_len(.N),by=value]

identical(df$instance,df$instance2)
[1] TRUE


问:
Naming convention for methods whether they change an object or return changed object
As it is said in the headline, is there that kind of naming convention, especially in python?

For example there are functions in python sorted (function that returns changed object, but doesn't change object) and list or numpy.ndarray method sort (returns nothing, but changes the object).

But for reversed and list.reverse functions it's not quite the case, reversed returns iterator.

In my case I have Permutation class and I want to add inverse functions for these two cases. Should I name them inverted and inverse (last one will be out of class) or like get_inv and set_inv respectively, because these methods are just like getters and setters (which is also quite true for sorted and sort)?

答:
Here is my convention which has served me well in all programming languages I have used:

A function with no side-effects which returns a truth value should be named after the property it queries and use an adjective as the last word, e.g. sorted or items_sorted.

A function with no side-effects which returns a non-truth value should be named after the result it returns and use a noun as the last word, e.g. sorted_items.

A function with side-effects should be named after what it does and use a verb as the first word, e.g. sort or sort_items.

Rule 1 and 2 is also applicable to variable names.

In your concrete example i would use the identifier invert for the method which inverts a permutation, and inverse for a method which returns the inverse of a permutation.


问:
How to add tabs at bottom
I have a tabhost which contains three tabs, connected with three activities. All three tabs are in the upper side. How can I make these three tabs at the bottom?

I found this, but there are still some problems.

This is my tabhost XML file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>
</code>```

In my TabActivity class, I have following code:

```<code>setContentView(R.layout.tabs);

TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);

mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));

mTabHost.setCurrentTab(0);
</code>```

There is one activity named TabActivity1 which I have also included in Manifest file. But it is showing the error:

Can't get the activity TabActivity1.

答:
If you want to use the LinearLayout:

```<code><?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</TabHost>
</code>```

With this solution, the tab content will take no space firstly, the TabWidget will take its own space, then the remaining space will be given to the tab content.

Title: How to add tabs at bottom

Body:
I have a tabhost which contains three tabs, connected with three activities. All three tabs are in the upper side. How can I make these three tabs at the bottom?

I found this, but there are still some problems.

This is my tabhost XML file:

<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0"/>
    </LinearLayout>
</TabHost>

In my TabActivity class, I have following code:

setContentView(R.layout.tabs);

TabHost mTabHost = (TabHost)findViewById(android.R.id.tabhost);

mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("TAB 1").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("TAB 2").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("TAB 3").setContent(new Intent(AndroisTabViewActivity.this,TabActivity1.class)));

mTabHost.setCurrentTab(0);

There is one activity named TabActivity1 which I have also included in Manifest file. But it is showing the error:

Can't get the activity TabActivity1.

Body:
If you want to use the LinearLayout:

<?xml version="1.0" encoding="UTF-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/tabhost"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1" />
        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</TabHost>

With this solution, the tab content will take no space firstly, the TabWidget will take its own space, then the remaining space will be given to the tab content.


答:
base R

This is a good use of ave:

table(df$instance) # yours
#    1    2    3    4
# 1774   66   17    3
df$instance3 <- ave(df$value, df$value, FUN = seq_along)
table(df$instance3)
#    1    2    3    4
# 1774   66   17    3
all(df$instance == df$instance3)
# [1] TRUE
```
<h2>dplyr</h2>
<pre class="lang-r prettyprint-override"><code>library(dplyr)
df %>%
  group_by(value) %>%
  mutate(instance4 = row_number()) %>%
  ungroup()
</code>```

Benchmark

No surprise, Waldi's data.table breaks out:

DT <- as.data.table(df)
useful.function = function(x) { temp.idx = x[1]; sum(x[2] == df$value[1:temp.idx]); }
bench::mark(
  OP = {
    for (i in 1:nrow(df)) {
      df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
    }
  },
  Waldi = {
    DT[,instance2:=seq_len(.N),by=value]
  },
  r2evans_base = {
    df$instance3 <- ave(df$value, df$value, FUN = seq_along)
  },
  r2evans_dplyr = {
    df %>%
      group_by(value) %>%
      mutate(instance4 = row_number()) %>%
      ungroup()
  },
  PlasticMan = {
    df$instance5 <- apply(df, MARGIN = 1, useful.function)
  },
  min_terations = 500, check = FALSE)
# # A tibble: 5 x 13
#   expression         min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory                 time    gc
#   <bch:expr>    <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list>                 <list>  <list>
# 1 OP             54.42ms  59.45ms      16.6    39.9MB    11.1    300   200     18.07s <NULL> <Rprofmem [7,360 x 3]> <bench~ <tibbl~
# 2 Waldi          997.3us   1.11ms     828.     81.6KB     1.66   499     1   602.36ms <NULL> <Rprofmem [12 x 3]>    <bench~ <tibbl~
# 3 r2evans_base    3.11ms   3.52ms     273.    389.1KB     1.65   497     3      1.82s <NULL> <Rprofmem [35 x 3]>    <bench~ <tibbl~
# 4 r2evans_dplyr  13.04ms  15.85ms      59.5     347KB     6.03   454    46      7.63s <NULL> <Rprofmem [35 x 3]>    <bench~ <tibbl~
# 5 PlasticMan      12.7ms  14.12ms      65.3    26.9MB     4.47   468    32      7.16s <NULL> <Rprofmem [5,507 x 3]> <bench~ <tibbl~
```

Title: Fastest way of numbering instances of a value within a vector

Body:
base R

This is a good use of ave:

table(df$instance) # yours
#    1    2    3    4
# 1774   66   17    3
df$instance3 <- ave(df$value, df$value, FUN = seq_along)
table(df$instance3)
#    1    2    3    4
# 1774   66   17    3
all(df$instance == df$instance3)
# [1] TRUE

dplyr

library(dplyr)
df %>%
  group_by(value) %>%
  mutate(instance4 = row_number()) %>%
  ungroup()

Benchmark

No surprise, Waldi's data.table breaks out:

DT <- as.data.table(df)
useful.function = function(x) { temp.idx = x[1]; sum(x[2] == df$value[1:temp.idx]); }
bench::mark(
  OP = {
    for (i in 1:nrow(df)) {
      df[i,"instance"]<- sum(df[1:i,"value"] == df[i,"value"])
    }
  },
  Waldi = {
    DT[,instance2:=seq_len(.N),by=value]
  },
  r2evans_base = {
    df$instance3 <- ave(df$value, df$value, FUN = seq_along)
  },
  r2evans_dplyr = {
    df %>%
      group_by(value) %>%
      mutate(instance4 = row_number()) %>%
      ungroup()
  },
  PlasticMan = {
    df$instance5 <- apply(df, MARGIN = 1, useful.function)
  },
  min_terations = 500, check = FALSE)
# # A tibble: 5 x 13
#   expression         min   median `itr/sec` mem_alloc `gc/sec` n_itr  n_gc total_time result memory                 time    gc
#   <bch:expr>    <bch:tm> <bch:tm>     <dbl> <bch:byt>    <dbl> <int> <dbl>   <bch:tm> <list> <list>                 <list>  <list>
# 1 OP             54.42ms  59.45ms      16.6    39.9MB    11.1    300   200     18.07s <NULL> <Rprofmem [7,360 x 3]> <bench~ <tibbl~
# 2 Waldi          997.3us   1.11ms     828.     81.6KB     1.66   499     1   602.36ms <NULL> <Rprofmem [12 x 3]>    <bench~ <tibbl~
# 3 r2evans_base    3.11ms   3.52ms     273.    389.1KB     1.65   497     3      1.82s <NULL> <Rprofmem [35 x 3]>    <bench~ <tibbl~
# 4 r2evans_dplyr  13.04ms  15.85ms      59.5     347KB     6.03   454    46      7.63s <NULL> <Rprofmem [35 x 3]>    <bench~ <tibbl~
# 5 PlasticMan      12.7ms  14.12ms      65.3    26.9MB     4.47   468    32      7.16s <NULL> <Rprofmem [5,507 x 3]> <bench~ <tibbl~


问:
How to Suppress "Using bos_token, but it is not set yet..." in HuggingFace T5 Tokenizer
I'd like to turn off the warning that huggingface is generating when I use unique_no_split_tokens

```<code>In[2]   tokenizer = T5Tokenizer.from_pretrained("t5-base")
In[3]   tokenizer(" ".join([f"<extra_id_{n}>" for n in range(1,101)]), return_tensors="pt").input_ids.size()
Out[3]: torch.Size([1, 100])
    Using bos_token, but it is not set yet.
    Using cls_token, but it is not set yet.
    Using mask_token, but it is not set yet.
    Using sep_token, but it is not set yet.
</code>```

Anyone know how to do this?

答:
This solution worked for me:</p>
```<code>tokenizer.add_tokens([f"_{n}" for n in range(1,100)], special_tokens=True)
model.resize_token_embeddings(len(tokenizer))
tokenizer.save_pretrained('pathToExtendedTokenizer/')
tokenizer = T5Tokenizer.from_pretrained("pathToExtendedTokenizer/")
</code>```

Body:
I'd like to turn off the warning that huggingface is generating when I use unique_no_split_tokens

In[2]   tokenizer = T5Tokenizer.from_pretrained("t5-base")
In[3]   tokenizer(" ".join([f"<extra_id_{n}>" for n in range(1,101)]), return_tensors="pt").input_ids.size()
Out[3]: torch.Size([1, 100])
    Using bos_token, but it is not set yet.
    Using cls_token, but it is not set yet.
    Using mask_token, but it is not set yet.
    Using sep_token, but it is not set yet.

Anyone know how to do this?

Body:
This solution worked for me:

tokenizer.add_tokens([f"_{n}" for n in range(1,100)], special_tokens=True)
model.resize_token_embeddings(len(tokenizer))
tokenizer.save_pretrained('pathToExtendedTokenizer/')
tokenizer = T5Tokenizer.from_pretrained("pathToExtendedTokenizer/")


问:
Beautify C++ files in VSCode
I am using VSCode 1.35.5.

I have two projects in the workspace, one .js files and another with .cpp files.

When I want to beautify a .cpp file, here is the following pop up :

From  File -> Preferences -> Extensions, here are the following enabled extensions :

Beautify from HookyQR 1.5.0

C/C++ from Microsoft 0.23.1

CMake 0.0.17

ESLint 1.9.0

How can I use the Beautify extension for C++ files ?

答:
The VSCode C/C++ extension includes clang-format automatically, so you can simply run Shift+Alt+F and your C++ will format.

Then to use it more extensively I opened the C++ settings JSON (Settings→cpp→Open JSON settings), removed editor.defaultFormatter (which was prettier for me), added format on save and format on  paste, and it worked like a charm.

Here's the docs: https://code.visualstudio.com/docs/cpp/cpp-ide#_code-formatting

Title: Beautify C++ files in VSCode


问:
EF6 - Is there a way to clear EF cache / Local items without causing any change into the database?
Basically I am mixing EF with one call to a stored procedure which does some batch deletions, otherwise EF is too slow.

Here is some pseudo-code of this scenario (I have more complex code in reality):

```<code>public void RemoveCustomer(int customerUID)
{
   // this code is running in one db transaction
   {
      // retrieve certain orders of particular customer using EF
      var orders = repoOrders.GetOrdersOfCustomer(filter, customerUID);

      // do something with above orders before deletion using EF
      repoX.DoSomethingWithOrders(orders);

      // call SP to delete all orders of customer
      repoOrders.DeleteAllOrdersOfCustomer(customerUID);  // this calls a stored procedure

      // delete customer using EF
      repoCustomers.DeleteCustomer(customerUID);  // throws exception due to relationship!
   }
}
</code>```

of course, customers-orders is one-to-many (1:m) relation.

I want to avoid in the above scenario the exception which is thrown when there will be some orders loaded by the context belonging to the customer that gets deleted. Exception is:

"The relationship could not be changed because one or more of the
  foreign-key properties is non-nullable. When a change is made to a
  relationship, the related foreign-key property is set to a null value.
  If the foreign-key does not support null values, a new relationship
  must be defined, the foreign-key property must be assigned another
  non-null value, or the unrelated object must be deleted."

So, I want to know if is possible to clear some/all orders from <DbSet>.Local without causing any change into the database after calling the stored procedure and before user gets deleted.

I guess Detach could be used, but this means I should loop through.

What would you recommend?

Edit: I am new to EF and I am integrating EF now after the repositories were done using ADO.NET, and yes, the BL has been kept the same... so I try this integration with minimal efforts at this point.

Note: I can't make changes on the database structure.

答:
This feature is available starting with Entity Framework Core 5!

To make the DbContext stop tracking all currently tracked entities:

```<code>myDbContext.ChangeTracker.Clear();
</code>```

Body:
Basically I am mixing EF with one call to a stored procedure which does some batch deletions, otherwise EF is too slow.

Here is some pseudo-code of this scenario (I have more complex code in reality):

public void RemoveCustomer(int customerUID)
{
   // this code is running in one db transaction
   {
      // retrieve certain orders of particular customer using EF
      var orders = repoOrders.GetOrdersOfCustomer(filter, customerUID);

      // do something with above orders before deletion using EF
      repoX.DoSomethingWithOrders(orders);

      // call SP to delete all orders of customer
      repoOrders.DeleteAllOrdersOfCustomer(customerUID);  // this calls a stored procedure

      // delete customer using EF
      repoCustomers.DeleteCustomer(customerUID);  // throws exception due to relationship!
   }
}

of course, customers-orders is one-to-many (1:m) relation.

I want to avoid in the above scenario the exception which is thrown when there will be some orders loaded by the context belonging to the customer that gets deleted. Exception is:

"The relationship could not be changed because one or more of the
  foreign-key properties is non-nullable. When a change is made to a
  relationship, the related foreign-key property is set to a null value.
  If the foreign-key does not support null values, a new relationship
  must be defined, the foreign-key property must be assigned another
  non-null value, or the unrelated object must be deleted."

So, I want to know if is possible to clear some/all orders from <DbSet>.Local without causing any change into the database after calling the stored procedure and before user gets deleted.

I guess Detach could be used, but this means I should loop through.

What would you recommend?

Edit: I am new to EF and I am integrating EF now after the repositories were done using ADO.NET, and yes, the BL has been kept the same... so I try this integration with minimal efforts at this point.

Note: I can't make changes on the database structure.

Body:
This feature is available starting with Entity Framework Core 5!

To make the DbContext stop tracking all currently tracked entities:

myDbContext.ChangeTracker.Clear();


问:
Is it possible to prevent the removal of the comma with empty __VA_ARGS__ in Visual C++?
On Visual Studio 2005 I have a macro that looks like this (examplified!!):

```<code>#define MY_CALL(FUN, ...) \
  if(prepare(x, y)) {     \
    FUN(__VA_ARGS__);     \
  }
/**/
</code>```

As long as the function takes at least one argument, I'm fine.

When the function takes zero arguments, the preprocessor "helpfully" removes the "trailing comma", expanding something like this:

```<code>if(prepare(x y)) { funct(); }
</code>```

Great, isn't it?

How can I fix this macro, so that it'll work with zero __VA_ARGS__ on Visual C++ (VS 2005)?

Apparently this is a bug in VS2005.

答:
Unfortunately, I do not use Visual C++ anymore (and as so cannot verify this works), but can you try this?

```<code>#define MY_CALL(FUN, ...) \
  if(prepare(x, y)) {     \
    int fail[] = {0,}     \
    FUN(__VA_ARGS__);     \
  }
</code>```

Using gcc 4.2, both {0,} and {0} are allowed in that context, so if the comma gets deleted or not it would not matter. However, I am not certain whether that is generally accepted in the spec, a commonly implemented extension, or something specific to gcc.

If the {0,} syntax is allowed by Visual C++, then this would hopefully solve your problem (assuming I understand correctly that the most recent comma before __VA_ARGS__ is what is being incorrectly deleted, regardless of where it is appearing in the syntax).

Body:
On Visual Studio 2005 I have a macro that looks like this (examplified!!):

#define MY_CALL(FUN, ...) \
  if(prepare(x, y)) {     \
    FUN(__VA_ARGS__);     \
  }
/**/

As long as the function takes at least one argument, I'm fine.

When the function takes zero arguments, the preprocessor "helpfully" removes the "trailing comma", expanding something like this:

if(prepare(x y)) { funct(); }

Great, isn't it?

How can I fix this macro, so that it'll work with zero __VA_ARGS__ on Visual C++ (VS 2005)?

Apparently this is a bug in VS2005.

Body:
Unfortunately, I do not use Visual C++ anymore (and as so cannot verify this works), but can you try this?

#define MY_CALL(FUN, ...) \
  if(prepare(x, y)) {     \
    int fail[] = {0,}     \
    FUN(__VA_ARGS__);     \
  }

Using gcc 4.2, both {0,} and {0} are allowed in that context, so if the comma gets deleted or not it would not matter. However, I am not certain whether that is generally accepted in the spec, a commonly implemented extension, or something specific to gcc.

If the {0,} syntax is allowed by Visual C++, then this would hopefully solve your problem (assuming I understand correctly that the most recent comma before __VA_ARGS__ is what is being incorrectly deleted, regardless of where it is appearing in the syntax).


问:
How to use regular expressions in kdiff3 when merging two git files
I was wondering if someone could help me with explanation how to merge two files using regular expressions. I am trying to bring back comments that were removed in one of the branches. The problem is that there are over 600 of them. I tried to set the following expressions in Settings/Merge/Automerge:
(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|(//.*)
When I click on Test your regular expressions and put an example, it confirms that it works fine. However when I try to run Merge/Run Regular Expressions AutoMerge nothing happens. Any ideas what am I doing wrong?

答:
As per the documentation

For simple lines that match the "Auto merge regular expression"-option in all input-files KDiff3 will choose the line from B or - if available - from C. (Additionally it is necessary that the lines in question line up in the comparison and the previous line contains no conflict.) This auto merge can either be run immediately after a merge starts (activate the option "Run regular expression auto merge on merge start") or later via the merge menu "Run Regular Expression Auto Merge".

So Kdiff doesn't choose A, B, or C based on that regex, it just identifies the line/block as one that should be automerged. And it chooses B or, if available, C.


问:
Using Material-UI components in Storybook producing weird code snippets
I'm using Storybook together with Material-UI components. When importing and implementing them there and I look into the produced code snippets in the 'show code' tab I get weird withStyles(forwardRef(COMPONENT)) outputs.

This is my code:

```<code>import React from 'react'
import { Story, Meta } from '@storybook/react/types-6-0'
import { MenuItem, Select } from '@material-ui/core'
import {
  ArgsTable,
  Description,
  Primary,
  PRIMARY_STORY,
  Stories,
  Subtitle,
  Title,
} from '@storybook/addon-docs/blocks'

export default {
  title: 'Reusable/Themed Components/SelectComponent',
  component: Select,
  argTypes: {
    variant: {
      control: {
        type: 'select',
        options: ['filled', 'outlined', 'standard'],
        defaultValue: ['standard'],
      },
    },
  },
  parameters: {
    docs: {
      page: () => (
        <>
          <Title>Select</Title>
          <Subtitle>
            This is the docs for the generic Select component.
          </Subtitle>
          <Description>Lirum Larum Description.</Description>
          <Primary />
          <ArgsTable story={PRIMARY_STORY} />
          <Stories includePrimary />
        </>
      ),
    },
  },
} as Meta

const Template: Story = ({ ...args }) => (
  <Select variant={args.variant} style={{ width: '120px' }}>
    <MenuItem value="german" selected>
      Deutsch
    </MenuItem>
    <MenuItem value="english">Englisch</MenuItem>
    <MenuItem value="arabic">Arabisch</MenuItem>
  </Select>
)

export const SelectComponentStory = Template.bind({})
SelectComponentStory.storyName = 'SelectComponent'

</code>```

Output from the 'show code' tab in the Storybook 'playground':

```<code>
<WithStyles(ForwardRef(Select))
  style={{
    width: '120px'
  }}
>
  <WithStyles(ForwardRef(MenuItem))
    selected
    value="german"
  >
    Deutsch
  </WithStyles(ForwardRef(MenuItem))>
  <WithStyles(ForwardRef(MenuItem)) value="english">
    Englisch
  </WithStyles(ForwardRef(MenuItem))>
  <WithStyles(ForwardRef(MenuItem)) value="arabic">
    Arabisch
  </WithStyles(ForwardRef(MenuItem))>
</WithStyles(ForwardRef(Select))>
</code>```

Expected output that I'd like to see generated in the show code tab, so that developers and reuse it:

```<code><Select variant='standard' style={{ width: '120px' }}>
    <MenuItem value="german" selected>
      Deutsch
    </MenuItem>
    <MenuItem value="english">Englisch</MenuItem>
    <MenuItem value="arabic">Arabisch</MenuItem>
  </Select>
</code>```

Anyone know how to get there?

Edit: here's the image of the output for visual reference:

答:
Perhaps more of a workaround than a fix, but I was able to fix this by using Storybook's transformSource within parameters.docs, like so:

const meta = {
  title: "Core Components (Atoms)/Buttons",
  component: Button,
  parameters: {
    docs: {
      transformSource: source => source.replace(/WithStyles\(ForwardRef\(/g, "").replace(/\)\)/g, ""),
    },
  },
```

I would also add that wrapping your component and giving it a displayName might help resolve this as well.

Body:
I'm using Storybook together with Material-UI components. When importing and implementing them there and I look into the produced code snippets in the 'show code' tab I get weird withStyles(forwardRef(COMPONENT)) outputs.

This is my code:

import React from 'react'
import { Story, Meta } from '@storybook/react/types-6-0'
import { MenuItem, Select } from '@material-ui/core'
import {
  ArgsTable,
  Description,
  Primary,
  PRIMARY_STORY,
  Stories,
  Subtitle,
  Title,
} from '@storybook/addon-docs/blocks'

export default {
  title: 'Reusable/Themed Components/SelectComponent',
  component: Select,
  argTypes: {
    variant: {
      control: {
        type: 'select',
        options: ['filled', 'outlined', 'standard'],
        defaultValue: ['standard'],
      },
    },
  },
  parameters: {
    docs: {
      page: () => (
        <>
          <Title>Select</Title>
          <Subtitle>
            This is the docs for the generic Select component.
          </Subtitle>
          <Description>Lirum Larum Description.</Description>
          <Primary />
          <ArgsTable story={PRIMARY_STORY} />
          <Stories includePrimary />
        </>
      ),
    },
  },
} as Meta

const Template: Story = ({ ...args }) => (
  <Select variant={args.variant} style={{ width: '120px' }}>
    <MenuItem value="german" selected>
      Deutsch
    </MenuItem>
    <MenuItem value="english">Englisch</MenuItem>
    <MenuItem value="arabic">Arabisch</MenuItem>
  </Select>
)

export const SelectComponentStory = Template.bind({})
SelectComponentStory.storyName = 'SelectComponent'

Output from the 'show code' tab in the Storybook 'playground':

<WithStyles(ForwardRef(Select))
  style={{
    width: '120px'
  }}
>
  <WithStyles(ForwardRef(MenuItem))
    selected
    value="german"
  >
    Deutsch
  </WithStyles(ForwardRef(MenuItem))>
  <WithStyles(ForwardRef(MenuItem)) value="english">
    Englisch
  </WithStyles(ForwardRef(MenuItem))>
  <WithStyles(ForwardRef(MenuItem)) value="arabic">
    Arabisch
  </WithStyles(ForwardRef(MenuItem))>
</WithStyles(ForwardRef(Select))>

Expected output that I'd like to see generated in the show code tab, so that developers and reuse it:

<Select variant='standard' style={{ width: '120px' }}>
    <MenuItem value="german" selected>
      Deutsch
    </MenuItem>
    <MenuItem value="english">Englisch</MenuItem>
    <MenuItem value="arabic">Arabisch</MenuItem>
  </Select>

Anyone know how to get there?

Edit: here's the image of the output for visual reference:

Body:
Perhaps more of a workaround than a fix, but I was able to fix this by using Storybook's transformSource within parameters.docs, like so:

const meta = {
  title: "Core Components (Atoms)/Buttons",
  component: Button,
  parameters: {
    docs: {
      transformSource: source => source.replace(/WithStyles\(ForwardRef\(/g, "").replace(/\)\)/g, ""),
    },
  },

I would also add that wrapping your component and giving it a displayName might help resolve this as well.


问:
Is there a way to set the content of each page on ngx-typed-js?
I'm using the TypedJS version for Angular ngx-typed-js to print the content of a container, but I'm having a huge problem when the content gets more than one page, cutting off the content in the middle of those.

Is there a way to control the content of each page ? Or some kind of preview?

Here is a screenshot of the problem and the package page on the NPM website.

https://www.npmjs.com/package/ngx-typed-js

答:
I've found a solution in a property name page-break-before.

"The page-break-before property adds a page-break before the element to which it is applied."

```<code>page-break-before: always;
</code>```

page-break

Body:
I've found a solution in a property name page-break-before.

"The page-break-before property adds a page-break before the element to which it is applied."

page-break-before: always;

page-break


问:
How to use two version of flutter on same device for different projects?
I have a stable flutter channel SDK located at c:\flutter. which is set at the system environment variables to be the default path for Flutter.

And I'm using this path c:\flutter when creating new Flutter project in IntelliJ for our customers.

I also downloaded Flutter master channel at c:\flutter_master and I need to use this flutter SDK (master) for another project.

How I can correctly have two working flutter version on the same device for different projects without playing with the system environment variables each time?

答:
Now you can use “FVM”, and it's Flutter Version Management, A simple CLI to manage Flutter SDK versions per project.

1 you can use it by this command

```<code>pub global activate fvm
</code>```

2 after that you can install any versions you want like

```<code>fvm install stable

fvm install 'flutter version'
</code>```

it will be installed at

```<code> /Users/'username'/fvm/versions/
</code>```

3 to switch versions:

```<code>fvm use 'flutter version'
</code>```

for more info, visit FVM.app

Body:
Now you can use “FVM”, and it's Flutter Version Management, A simple CLI to manage Flutter SDK versions per project.

1 you can use it by this command

pub global activate fvm

2 after that you can install any versions you want like

fvm install stable

fvm install 'flutter version'

it will be installed at

 /Users/'username'/fvm/versions/

3 to switch versions:

fvm use 'flutter version'

for more info, visit FVM.app


问:
Identifying and deleting S3 Objects that are not being accessed?
I have recently joined a company that uses S3 Buckets for various different projects within AWS. I want to identify and potentially delete S3 Objects that are not being accessed (read and write), in an effort to reduce the cost of S3 in my AWS account.

I read this, which helped me to some extent.

Is there a way to find out which objects are being accessed and which are not?

答:
There is recent AWS blog post which I found very interesting and cost optimized approach to solve this problem.

Here is the description from AWS blog:

The S3 server access logs capture S3 object requests. These are generated and stored in the target S3 bucket.

An S3 inventory report is generated for the source bucket daily. It is written to the S3 inventory target bucket.

An Amazon EventBridge rule is configured that will initiate an AWS Lambda function once a day, or as desired.

The Lambda function initiates an S3 Batch Operation job to tag objects in the source bucket. These must be expired using the following logic:

Capture the number of days (x) configuration from the S3 Lifecycle configuration.

Run an Amazon Athena query that will get the list of objects from the S3 inventory report and server access logs. Create a delta list with objects that were created earlier than 'x' days, but not accessed during that time.

Write a manifest file with the list of these objects to an S3 bucket.

Create an S3 Batch operation job that will tag all objects in the manifest file with a tag of "delete=True".

The Lifecycle rule on the source S3 bucket will expire all objects that were created prior to 'x' days. They will have the tag given via the S3 batch operation of "delete=True".

Expiring Amazon S3 Objects Based on Last Accessed Date to Decrease Costs


问:
How to manipulate this type of timestamps with pandas?
I have a dataset that looks like this and I've been having a really hard time trying to figure out how to manipulate those types of timestamps, I don't even know if they have a name/type etc and I could use all the help I could get or insights.

答:
This is the unix timestamp. Update: and as I have seen just yet, it's the Unixtime in milliseconds. I've updated my code.

You can convert it into a more readable format with pd.to_datetime(dta["timestamp"], unit="s"). But besides that there are advantages to have it in this format (easier to parse, less size and so on).

```<code>import pandas as pd
import time
from datetime import datetime

now = int(time.time()) * 1000

dta = pd.DataFrame({"timestamp":now}, index=[0])

dta["datetime"] = pd.to_datetime(dta["timestamp"], unit="ms")
</code>```

Output:

```<code>+----+-----------------+---------------------+
|    |   timestamp     | datetime            |
|----+-----------------+---------------------|
|  0 |  16443491050000 | 2022-02-08 19:38:25 |
+----+-----------------+---------------------+
</code>```

Body:
This is the unix timestamp. Update: and as I have seen just yet, it's the Unixtime in milliseconds. I've updated my code.

You can convert it into a more readable format with pd.to_datetime(dta["timestamp"], unit="s"). But besides that there are advantages to have it in this format (easier to parse, less size and so on).

import pandas as pd
import time
from datetime import datetime

now = int(time.time()) * 1000

dta = pd.DataFrame({"timestamp":now}, index=[0])

dta["datetime"] = pd.to_datetime(dta["timestamp"], unit="ms")

Output:

+----+-----------------+---------------------+
|    |   timestamp     | datetime            |
|----+-----------------+---------------------|
|  0 |  16443491050000 | 2022-02-08 19:38:25 |
+----+-----------------+---------------------+


问:
Submitting a form in ColdFusion that has special characters
I have a form that contains textboxes and textareas with user entered data. I am using a simple ColdFusion actionpage with a cfquery tag to submit the data to my database.

```<code><cfquery name="add_ticket" datasource="#datasource#">
INSERT INTO service_ticket(end_user, customer_id, ticket_id, company_name, service_description, service_date, status, customer_signature, technician_signature, materials, ticket_type, equipment, discount, percent_discount, material_subtotal, material_tax, material_shipping, material_total, billable_service_total, tax_rate, grand_total, equipment_id, equipment_name)
VALUES("", '#get_customer.customer_id#', "#ticketnum#", "#url.customer_name#", "#url.description# - #get_equipment.equipment_name#", #CreateODBCDateTime(Now())#, "In-progress", "0", "0", "0", "#url.TT#", "0",  '0.00', '0', '0.00', '6.625', '0.00', '0.00', '0.00', '#subscriber.tax_rate#', '0.00', "#get_equipment.id#", "#get_equipment.equipment_name#")
</cfquery>
</code>```

I sporadically run into errors submitting this query because the values for certain columns contain special characters.

For instance, the value for company_name might be: Smith & Johnson, LLC.

The ColdFusion code breaks once it hits the ampersand. I've tried enclosing the value in single quotes and double quotes as well as

```<code><cfqueryparam value="#url.company_name#" cfsqltype="cf_sql_longvarchar" />
</code>```

but nothing seems to help.

Is there a better way to handle this situation?

I'm currently running a Lucee server.

答:
You have options.

You can change your form to something like this:

```<code><form action = actionpages/add_ticket_maintenance.cfm
target = "_blank"
method = "post">
</code>```

This will submit the form to a separate window or tab.  On your action page you will have to use the form scope instead of the url scope.

Or, you can encode your url variables with the EncodeForUrl function.  Your choice.

Body:
I have a form that contains textboxes and textareas with user entered data. I am using a simple ColdFusion actionpage with a cfquery tag to submit the data to my database.

<cfquery name="add_ticket" datasource="#datasource#">
INSERT INTO service_ticket(end_user, customer_id, ticket_id, company_name, service_description, service_date, status, customer_signature, technician_signature, materials, ticket_type, equipment, discount, percent_discount, material_subtotal, material_tax, material_shipping, material_total, billable_service_total, tax_rate, grand_total, equipment_id, equipment_name)
VALUES("", '#get_customer.customer_id#', "#ticketnum#", "#url.customer_name#", "#url.description# - #get_equipment.equipment_name#", #CreateODBCDateTime(Now())#, "In-progress", "0", "0", "0", "#url.TT#", "0",  '0.00', '0', '0.00', '6.625', '0.00', '0.00', '0.00', '#subscriber.tax_rate#', '0.00', "#get_equipment.id#", "#get_equipment.equipment_name#")
</cfquery>

I sporadically run into errors submitting this query because the values for certain columns contain special characters.

For instance, the value for company_name might be: Smith & Johnson, LLC.

The ColdFusion code breaks once it hits the ampersand. I've tried enclosing the value in single quotes and double quotes as well as

<cfqueryparam value="#url.company_name#" cfsqltype="cf_sql_longvarchar" />

but nothing seems to help.

Is there a better way to handle this situation?

I'm currently running a Lucee server.

Body:
You have options.

You can change your form to something like this:

<form action = actionpages/add_ticket_maintenance.cfm
target = "_blank"
method = "post">

This will submit the form to a separate window or tab.  On your action page you will have to use the form scope instead of the url scope.

Or, you can encode your url variables with the EncodeForUrl function.  Your choice.


问:
gzip an image file through cloud function on storage trigger
I am trying to automate gzipping on image uploaded to cloud storage bucket.
Everytime i upload an image, i want cloud function to run python code to convert it into gzip and move it to another bucket present in storage.

My code is not running. It's giving me File not found error. Also what's the right way to give full location.

My code is  ..

```<code>from google.cloud import storage
import gzip
import shutil
client = storage.Client()

def hello_gcs(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for
the event.
    """
    with open("/"+event['name'],'rb') as f_input :
        with gzip.open("'/tmp/'+event['name']+'.gz'","wb") as f_output:
            shutil.copyfileobj(f_input,f_output)

    source_bucket= client.bucket(event['bucket'])
    source_blob = source_bucket.blob("/tmp/" + event['name'])
    destination_bucket = client.bucket('baalti2')

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, event['name']
    )

    print(
        "Blob {} in bucket {} moved to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
       )
    )
</code>```

答: You are using Linux file system APIs (open, shutil.copy) to access Cloud Storge which will not work. Copy the file from the bucket to local storage. Gzip the file. Copy the gzip file to the destination bucket. Use the Cloud Storage APIs to interact with Cloud Storage.</p>

Body:
I am trying to automate gzipping on image uploaded to cloud storage bucket.
Everytime i upload an image, i want cloud function to run python code to convert it into gzip and move it to another bucket present in storage.

My code is not running. It's giving me File not found error. Also what's the right way to give full location.

My code is  ..

from google.cloud import storage
import gzip
import shutil
client = storage.Client()

def hello_gcs(event, context):
    """Triggered by a change to a Cloud Storage bucket.
    Args:
         event (dict): Event payload.
         context (google.cloud.functions.Context): Metadata for
the event.
    """
    with open("/"+event['name'],'rb') as f_input :
        with gzip.open("'/tmp/'+event['name']+'.gz'","wb") as f_output:
            shutil.copyfileobj(f_input,f_output)

    source_bucket= client.bucket(event['bucket'])
    source_blob = source_bucket.blob("/tmp/" + event['name'])
    destination_bucket = client.bucket('baalti2')

    blob_copy = source_bucket.copy_blob(
        source_blob, destination_bucket, event['name']
    )

    print(
        "Blob {} in bucket {} moved to blob {} in bucket {}.".format(
            source_blob.name,
            source_bucket.name,
            blob_copy.name,
            destination_bucket.name,
       )
    )


问:
How to define C API to get current time count in nanosecond?
I need to define C API ex. GetTimerCountInNS(void) to get current TimerCount in Nanosecond, so using this API call I can calculate total execution time of some work done in nanosecond. Can someone suggest me what is wrong with my GetTimerCountInNS function as when I am calculating total execution time it shows incorrect execution time however for MilliSecond it shows correct one.

I already checked other query related to same one but I could not found exact answer.As I dont want to write all equation into main code when calculating time in nanosecond.

I need to use custom API to get count in Nanosecond and by getting different of start and stop time count I need to get total execution time.

How to get current timestamp in nanoseconds in linux using c

Calculating Function time in nanoseconds in C code

```<code>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#define BILLION  1000000000L;

// This API provides incorrect time in NS duration
uint64_t GetTimerCountInNS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);

   //I am not sure here how to calculate count in NS
   return currenttime.tv_nsec;
}

// This API provides correct time in MS duration
uint64_t GetTimerCountInMS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);
   return (1000 * currenttime.tv_sec) + ((double)currenttime.tv_nsec / 1e6);
}

int main( int argc, char** argv )
  {
    struct timespec start, stop;
    uint64_t start_ns,end_ns;
    uint64_t start_ms,end_ms;

    clock_gettime( CLOCK_REALTIME, &start);
    start_ms = GetTimerCountInMS();
    start_ns  = GetTimerCountInNS();

    int  f = 0;
    sleep(3);
    clock_gettime( CLOCK_REALTIME, &stop);

    end_ms = GetTimerCountInMS();
    end_ns  = GetTimerCountInNS();

    double total_time_sec = ( stop.tv_sec - start.tv_sec ) + (double)( stop.tv_nsec - start.tv_nsec ) / (double)BILLION;
    printf( "time in sec \t: %lf\n", total_time_sec );
    printf( "time in ms \t: %ld\n", (end_ms - start_ms) );
    printf( "time in ns \t: %ld\n", (end_ns - start_ns) );

    return EXIT_SUCCESS;
  }
</code>```
```<code>Output:
time in sec     : 3.000078
time in ms      : 3000
time in ns      : 76463   // This shows wrong time
</code>```

答:
A fix:

```<code>uint64_t GetTimerCountInNS(void) {
   struct timespec currenttime;
   clock_gettime(CLOCK_REALTIME, &currenttime);
   return UINT64_C(1000000000) * currenttime.tv_sec + currenttime.tv_nsec;
}
</code>```

In the return, a uint64_t constant is used to promote all other operands of the binary arithmetic operators to uint64_t, in addition to converting seconds to nanoseconds.

Body:
I need to define C API ex. GetTimerCountInNS(void) to get current TimerCount in Nanosecond, so using this API call I can calculate total execution time of some work done in nanosecond. Can someone suggest me what is wrong with my GetTimerCountInNS function as when I am calculating total execution time it shows incorrect execution time however for MilliSecond it shows correct one.

I already checked other query related to same one but I could not found exact answer.As I dont want to write all equation into main code when calculating time in nanosecond.

I need to use custom API to get count in Nanosecond and by getting different of start and stop time count I need to get total execution time.

How to get current timestamp in nanoseconds in linux using c

Calculating Function time in nanoseconds in C code

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <time.h>

#define BILLION  1000000000L;

// This API provides incorrect time in NS duration
uint64_t GetTimerCountInNS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);

   //I am not sure here how to calculate count in NS
   return currenttime.tv_nsec;
}

// This API provides correct time in MS duration
uint64_t GetTimerCountInMS(void)
{
   struct timespec currenttime;
   clock_gettime( CLOCK_REALTIME, &currenttime);
   return (1000 * currenttime.tv_sec) + ((double)currenttime.tv_nsec / 1e6);
}

int main( int argc, char** argv )
  {
    struct timespec start, stop;
    uint64_t start_ns,end_ns;
    uint64_t start_ms,end_ms;

    clock_gettime( CLOCK_REALTIME, &start);
    start_ms = GetTimerCountInMS();
    start_ns  = GetTimerCountInNS();

    int  f = 0;
    sleep(3);
    clock_gettime( CLOCK_REALTIME, &stop);

    end_ms = GetTimerCountInMS();
    end_ns  = GetTimerCountInNS();

    double total_time_sec = ( stop.tv_sec - start.tv_sec ) + (double)( stop.tv_nsec - start.tv_nsec ) / (double)BILLION;
    printf( "time in sec \t: %lf\n", total_time_sec );
    printf( "time in ms \t: %ld\n", (end_ms - start_ms) );
    printf( "time in ns \t: %ld\n", (end_ns - start_ns) );

    return EXIT_SUCCESS;
  }

Output:
time in sec     : 3.000078
time in ms      : 3000
time in ns      : 76463   // This shows wrong time

Body:
A fix:

uint64_t GetTimerCountInNS(void) {
   struct timespec currenttime;
   clock_gettime(CLOCK_REALTIME, &currenttime);
   return UINT64_C(1000000000) * currenttime.tv_sec + currenttime.tv_nsec;
}

In the return, a uint64_t constant is used to promote all other operands of the binary arithmetic operators to uint64_t, in addition to converting seconds to nanoseconds.


问:
Understanding conflicting Interfaces
I am trying to understand the interface concept.
The following is my test code:

```<code>package main

import "fmt"

//interface
type InterfaceA interface {
    A() string
}

//interface
type InterfaceB interface {
    A() string
}

//user defined type structure
type structure struct {
    a string
}

//implementing A(), but which A() ?
func (strt structure) A() string {
    return strt.a
}

func main() {
    fmt.Println("Start")
    variable := structure{"hello"}
    fmt.Println(variable.A())
}

</code>```

As per the documentation, I understand that there is no explicit mention of "Implements" like in other languages. But when I call variable.A() which interface is my type structure using? InterfaceA or InterfaceB ? Plus, am I actually implementing the interface properly?

答:
Your interfaces do not conflict with each other; interfaces do not conflict. They can be redundant with each other as they describe the same thing, but that doesn't create a conflict nor any other tangible problem.

As for which interface is structure using: neither. Concrete types such as structs don't use interfaces, they implement them. Implementing of an interface is implicit and automatic. It's just a statement of fact, not a mechanism (until you explicitly use it as such). Further, neither interface is used to any extent in your program. Your variable is a structure and is being used as a structure. It could be used as either InterfaceA or InterfaceB, or both of them at different times, but you are doing no such thing in this example.

See Burak's answer for how you could use the structure value through the interfaces.

Title: Understanding conflicting Interfaces

Body:
I am trying to understand the interface concept.
The following is my test code:

package main

import "fmt"

//interface
type InterfaceA interface {
    A() string
}

//interface
type InterfaceB interface {
    A() string
}

//user defined type structure
type structure struct {
    a string
}

//implementing A(), but which A() ?
func (strt structure) A() string {
    return strt.a
}

func main() {
    fmt.Println("Start")
    variable := structure{"hello"}
    fmt.Println(variable.A())
}

As per the documentation, I understand that there is no explicit mention of "Implements" like in other languages. But when I call variable.A() which interface is my type structure using? InterfaceA or InterfaceB ? Plus, am I actually implementing the interface properly?


问:
tinyMCE, change content depending on the link that opens it
I've got two links that opens a tinyMCE embedded inside a fancybox.

Now i'd like to change the content inside depending on what link the user clicks on, the content that i want to show inside tinyMCE is the link that im clicking on.

I've tried to set $('.editor').html($(this).html()) and it works the first time, the right content gets shown.

BUT here's my problem, the content gets 'stuck', when i close my fancybox and clicks the other link then the first content is still there.

Is there anyway i can reset the tinyMCE? I've tried setting $('editor').text('') and that removes the content but it wont get back when i click the button.

it probably has something to do with the iframe that tinyMCE produces, but i can't get it to work...

Here is my current code...

HTML

       " />

```<code><!--File2-->
<div class="title">
   <a href="#mce" class="edit"><h2>Titel</h2></a>
</div>

<div class="content">
   <a href="#mce" class="edit">
      <p>
         Lorem ipsum dolor sit amet, consectetur adipiscing elit.
         Ut aliquam diam eget elit tristique sit amet fringilla velit sagittis.
         Nam aliquet, nisl eget elementum consectetur, felis arcu feugiat felis, vel fermentum mi ipsum vitae neque.
         Suspendisse placerat leo dolor, ut mollis elit. Nullam bibendum posuere risus tempus viverra.
         Aliquam in erat dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
         Aenean auctor lacinia erat, ut facilisis lorem scelerisque eu.
         Duis vitae ullamcorper felis. Pellentesque blandit tortor quis magna placerat eget iaculis velit commodo.
         Nam imperdiet auctor scelerisque. Proin fermentum sem in nulla ornare euismod.
         Maecenas faucibus facilisis cursus. Proin tincidunt luctus egestas.
         Curabitur vestibulum aliquet viverra.
      </p>
   </a>
</div>

javascript

$('.editor').html('');
  var content = $(this).html();
    $('.editor').html(content);
  $(this).fancybox(
     {
        'size' : 'auto',
        'onComplete': function()
        {
           $('.editor').tinymce(
           {
              script_url : '/media/tiny_mce/tiny_mce.js',
              theme : 'advanced',
              height: 450,
              plugins : 'ecmsimage,pagebreak,style,layer,table,save,advhr,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist',
                  theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
                  theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,|,insertdate,inserttime,|,forecolor,backcolor",
                  theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,|,sub,sup,|,charmap,iespell,advhr,|,code,preview,fullscreen",
                   theme_advanced_toolbar_location : "top",
                  theme_advanced_toolbar_align : "left",
                  theme_advanced_statusbar_location : "bottom",
                  theme_advanced_resizing : true,
                  theme_advanced_resize_horizontal: false
               });

               $('#fancybox-inner').width(550).height(500);
               $('#fancybox-wrap').width(550).height(500);
               $.fancybox.center();
            }
         });
</code>```

答:
You need to shut down tinymce correctly before closing the fancybox in order to be able to open the tinymce editor a second time. Use this to shut it down correctly

```<code>tinymce.EditorManager.execCommand('mceRemoveControl',true, editor_id);
</code>```

The editorid equals the id of your html element for which you initialize your tinymce.

Body:
I've got two links that opens a tinyMCE embedded inside a fancybox.

Now i'd like to change the content inside depending on what link the user clicks on, the content that i want to show inside tinyMCE is the link that im clicking on.

I've tried to set $('.editor').html($(this).html()) and it works the first time, the right content gets shown.

BUT here's my problem, the content gets 'stuck', when i close my fancybox and clicks the other link then the first content is still there.

Is there anyway i can reset the tinyMCE? I've tried setting $('editor').text('') and that removes the content but it wont get back when i click the button.

it probably has something to do with the iframe that tinyMCE produces, but i can't get it to work...

Here is my current code...

HTML

       " />

Titel

         Lorem ipsum dolor sit amet, consectetur adipiscing elit.
         Ut aliquam diam eget elit tristique sit amet fringilla velit sagittis.
         Nam aliquet, nisl eget elementum consectetur, felis arcu feugiat felis, vel fermentum mi ipsum vitae neque.
         Suspendisse placerat leo dolor, ut mollis elit. Nullam bibendum posuere risus tempus viverra.
         Aliquam in erat dui. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
         Aenean auctor lacinia erat, ut facilisis lorem scelerisque eu.
         Duis vitae ullamcorper felis. Pellentesque blandit tortor quis magna placerat eget iaculis velit commodo.
         Nam imperdiet auctor scelerisque. Proin fermentum sem in nulla ornare euismod.
         Maecenas faucibus facilisis cursus. Proin tincidunt luctus egestas.
         Curabitur vestibulum aliquet viverra.

javascript

$('.editor').html('');
  var content = $(this).html();
    $('.editor').html(content);
  $(this).fancybox(
     {
        'size' : 'auto',
        'onComplete': function()
        {
           $('.editor').tinymce(
           {
              script_url : '/media/tiny_mce/tiny_mce.js',
              theme : 'advanced',
              height: 450,
              plugins : 'ecmsimage,pagebreak,style,layer,table,save,advhr,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist',
                  theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect,fontselect,fontsizeselect",
                  theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,cleanup,help,|,insertdate,inserttime,|,forecolor,backcolor",
                  theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,|,sub,sup,|,charmap,iespell,advhr,|,code,preview,fullscreen",
                   theme_advanced_toolbar_location : "top",
                  theme_advanced_toolbar_align : "left",
                  theme_advanced_statusbar_location : "bottom",
                  theme_advanced_resizing : true,
                  theme_advanced_resize_horizontal: false
               });

               $('#fancybox-inner').width(550).height(500);
               $('#fancybox-wrap').width(550).height(500);
               $.fancybox.center();
            }
         });

Body:
You need to shut down tinymce correctly before closing the fancybox in order to be able to open the tinymce editor a second time. Use this to shut it down correctly

tinymce.EditorManager.execCommand('mceRemoveControl',true, editor_id);

The editorid equals the id of your html element for which you initialize your tinymce.


问:
How to use `allow_redirects` in Python 2.7 in order to solve "302 Found" status
Problem Description

I am using the following the following python code in order to retrieve data from a give website through an API. The problem is that I am not receiving anything. When I print(str(response.status)+"  "+response.reason), I get the following: 302 FOUND and nothing is being printed. From what I saw The HTTP response status code 302 Found is a common way of performing URL redirection.

Question

I saw that there is a way to set allow_redirects to False in order to solve that problem. I am forced to use python 2.7. I can't use python 3.0. Is there a way to add allow_redirects to the request in python 2.7? I also can't use the requests library. I can use import requests.

```<code>#!/usr/bin/env python
import sys
import json
import httplib

# Retrieve list of errors from Error Viewer
def retrieve_errors_from_error_viewer(errors):
    headers = {"Content-Type": "application/json","Accept": "text/html"}
    data = {"dba": "XXX", "phase": "PROD"}
    conn = httplib.HTTPConnection('errorviewer.toys.net')
    conn.request('POST', '/api/errors', json.dumps(data), headers)
    response = conn.getresponse()
    print(str(response.status)+"  "+response.reason)
    print(response.read())

if __name__ == "__main__":
    # Retrieve Errors From ErrorViewer
    errors = []
    retrieve_errors_from_error_viewer(errors)
</code>```

答: If you use httplib2 instead of httplib, you have the follow_all_redirects option that should solve your problem.

Body:
Problem Description

I am using the following the following python code in order to retrieve data from a give website through an API. The problem is that I am not receiving anything. When I print(str(response.status)+"  "+response.reason), I get the following: 302 FOUND and nothing is being printed. From what I saw The HTTP response status code 302 Found is a common way of performing URL redirection.

Question

I saw that there is a way to set allow_redirects to False in order to solve that problem. I am forced to use python 2.7. I can't use python 3.0. Is there a way to add allow_redirects to the request in python 2.7? I also can't use the requests library. I can use import requests.

#!/usr/bin/env python
import sys
import json
import httplib

# Retrieve list of errors from Error Viewer
def retrieve_errors_from_error_viewer(errors):
    headers = {"Content-Type": "application/json","Accept": "text/html"}
    data = {"dba": "XXX", "phase": "PROD"}
    conn = httplib.HTTPConnection('errorviewer.toys.net')
    conn.request('POST', '/api/errors', json.dumps(data), headers)
    response = conn.getresponse()
    print(str(response.status)+"  "+response.reason)
    print(response.read())

if __name__ == "__main__":
    # Retrieve Errors From ErrorViewer
    errors = []
    retrieve_errors_from_error_viewer(errors)


问:
How to test Functions with TcUnit in TwinCAT3?
I want to write tests for my functions. I came across a framework for testing in TwinCAT 3, but I didn't find any examples of how to properly test functions there.</p>

答:
There is a convenient example of the implementation of testing of a function on the user introduction page where a Function Block 'FB_Sum' is run through some basic tests (As usual Jakob has it under control ).

In order to apply this example to a Function rather than a Function Block all that is needed is to generate this object as a Function. The FB version applies no additional functionality beyond that which is available as a Function (i.e. there are no methods/properties/internal memory spaces).

Updating METHOD TwoPlusTwoEqualsFour with the following changes allows you to run a test on f_Sum:

```<code>METHOD TwoPlusTwoEqualsFour
VAR
    Result : UINT;
    ExpectedSum : UINT := 4;
END_VAR

TEST('TwoPlusTwoEqualsFour');

Result := f_Sum( one := 2, two := 2);

AssertEquals(Expected := ExpectedSum,
             Actual := Result,
             Message := 'The calculation is not correct');

TEST_FINISHED();
</code>```

```<code>FUNCTION f_Sum
VAR_INPUT
    one : UINT;
    two : UINT;
END_VAR

f_Sum := one + two;
</code>```

Body:
There is a convenient example of the implementation of testing of a function on the user introduction page where a Function Block 'FB_Sum' is run through some basic tests (As usual Jakob has it under control ).

In order to apply this example to a Function rather than a Function Block all that is needed is to generate this object as a Function. The FB version applies no additional functionality beyond that which is available as a Function (i.e. there are no methods/properties/internal memory spaces).

Updating METHOD TwoPlusTwoEqualsFour with the following changes allows you to run a test on f_Sum:

METHOD TwoPlusTwoEqualsFour
VAR
    Result : UINT;
    ExpectedSum : UINT := 4;
END_VAR

TEST('TwoPlusTwoEqualsFour');

Result := f_Sum( one := 2, two := 2);

AssertEquals(Expected := ExpectedSum,
             Actual := Result,
             Message := 'The calculation is not correct');

TEST_FINISHED();

FUNCTION f_Sum
VAR_INPUT
    one : UINT;
    two : UINT;
END_VAR

f_Sum := one + two;


问:
Using a UITableViewDropCoordinator to animate drops via the dropDelegate with a diffable data source
In iOS 11 Apple introduced native drag and drop to TableViews which provided specifc animations for common drag and drop interactions.  Assuming you had returned the correct UIDropProposal it would easily animate a reordering drop in a table view

```<code>func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
  // usual code to handle drop, get dragItem, etc
  // ....

  // update the dataModel to reflect the change
  self?.model.updateDataSourceForDrag(from: sourceIndexPath, to: destinationIndexPath)

 // perform the drop animation with the drop coordinator
 coordinator.drop(dragItem, toRowAt: destinationIndexPath)
}
</code>```

and this would nicely animate the insertion of the dropped item into the tableView into the gap it was hovering over.

Fast forward to iOS 13+ and the use of diffable data source and I can find no reference to using the dropCoordinator with snapshots in the Apple documentation, and there has been no update to the guides, tutorials, or WWDC videos to show how to combine the two sets of APIs.

The drop controller will correctly "manage" the tableView during the drag operation and move the cells around to show the gap where dragged cell would drop, but it won't animate the actual drop with coordinator.drop(dragItem, toRowAt: destinationIndexPath).

The workaround I have currently is to manually update and then apply the snapshot:

```<code>DispatchQueue.main.async {
  var snapshot = self?.dataSource.snapshot()
  if destinationIndexPath.row > sourceIndexPath.row {
     snapshot?.moveItem((self?.dataSource.itemIdentifier(for: sourceIndexPath))!, afterItem: (self?.dataSource.itemIdentifier(for: destinationIndexPath))!)
  } else {
     snapshot?.moveItem((self?.dataSource.itemIdentifier(for: sourceIndexPath))!, beforeItem: (self?.dataSource.itemIdentifier(for: destinationIndexPath))!)
  }
  self?.dataSource.apply(snapshot!, animatingDifferences: false)
}
</code>```

This works to a degree, but it doesn't integrate with the drop controller animation.  So I can get the animation providing drop gaps in the tableView while I drag, but as soon as I drop it animates the cell move from its original indexPath rather than from the animated dropped items (as I'd expect for this workaround) which is all rather clunky.

That the dropCoordinator can adapt the tableView to animate the drag suggests it should be able to do animate the drop too, but I can find no way to achieve this.

Any experience with this would be gratefully received (before I give up and revert the code back to the older UITableViewDataSource methods).

答:
The drop animation is now working as expected on code that hasn't been modified for months.

There must have been a bug in iOS14 and early versions of iOS15 that was fixed in one of the recent updates.

All that wasted time and effort.  At times we really should have more faith in our own code.

Body:
In iOS 11 Apple introduced native drag and drop to TableViews which provided specifc animations for common drag and drop interactions.  Assuming you had returned the correct UIDropProposal it would easily animate a reordering drop in a table view

func tableView(_ tableView: UITableView, performDropWith coordinator: UITableViewDropCoordinator) {
  // usual code to handle drop, get dragItem, etc
  // ....

  // update the dataModel to reflect the change
  self?.model.updateDataSourceForDrag(from: sourceIndexPath, to: destinationIndexPath)

 // perform the drop animation with the drop coordinator
 coordinator.drop(dragItem, toRowAt: destinationIndexPath)
}

and this would nicely animate the insertion of the dropped item into the tableView into the gap it was hovering over.

Fast forward to iOS 13+ and the use of diffable data source and I can find no reference to using the dropCoordinator with snapshots in the Apple documentation, and there has been no update to the guides, tutorials, or WWDC videos to show how to combine the two sets of APIs.

The drop controller will correctly "manage" the tableView during the drag operation and move the cells around to show the gap where dragged cell would drop, but it won't animate the actual drop with coordinator.drop(dragItem, toRowAt: destinationIndexPath).

The workaround I have currently is to manually update and then apply the snapshot:

DispatchQueue.main.async {
  var snapshot = self?.dataSource.snapshot()
  if destinationIndexPath.row > sourceIndexPath.row {
     snapshot?.moveItem((self?.dataSource.itemIdentifier(for: sourceIndexPath))!, afterItem: (self?.dataSource.itemIdentifier(for: destinationIndexPath))!)
  } else {
     snapshot?.moveItem((self?.dataSource.itemIdentifier(for: sourceIndexPath))!, beforeItem: (self?.dataSource.itemIdentifier(for: destinationIndexPath))!)
  }
  self?.dataSource.apply(snapshot!, animatingDifferences: false)
}

This works to a degree, but it doesn't integrate with the drop controller animation.  So I can get the animation providing drop gaps in the tableView while I drag, but as soon as I drop it animates the cell move from its original indexPath rather than from the animated dropped items (as I'd expect for this workaround) which is all rather clunky.

That the dropCoordinator can adapt the tableView to animate the drag suggests it should be able to do animate the drop too, but I can find no way to achieve this.

Any experience with this would be gratefully received (before I give up and revert the code back to the older UITableViewDataSource methods).