问:
Get type definition for props.dispatch() for using TypeScript with React-Redux
I have this functional/stateless component:

```<code>import React from 'react';
import {useFormik} from 'formik';
import {connect} from "react-redux";

function mapStateToProps(){
  return {
     foo: "bar"
  }
}

interface OwnProps {
  propFromParent: number
}

type StateProps = ReturnType<typeof mapStateToProps>
type Props = StateProps & OwnProps

const SignupForm = (props: Props) => {

  const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: ''
    },
    onSubmit(values) {
      props.dispatch()   // props.dispatch is not defined!
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      <label htmlFor="name">Full Name</label>
      <input
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default connect<StateProps, null, Props>(mapStateToProps)(SignupForm);
</code>```

so I am getting this compile error:

So how can I include the type definition so that props.dispatch is defined?
Just looking for help with the proper TS definitions.

答:
Please see the React-Redux docs on "Static Typing", which show how to handle defining the correct types for what connect will pass into your component.

Specifically, we recommend using the ConnectedProps<T> helper, like this:

```<code>import { connect, ConnectedProps } from 'react-redux'

interface RootState {
  isOn: boolean
}

const mapState = (state: RootState) => ({
  isOn: state.isOn
})

const mapDispatch = {
  toggleOn: () => ({ type: 'TOGGLE_IS_ON' })
}

const connector = connect(
  mapState,
  mapDispatch
)

// The inferred type will look like:
// {isOn: boolean, toggleOn: () => void}
type PropsFromRedux = ConnectedProps<typeof connector>

interface Props extends PropsFromRedux {
  backgroundColor: string
}

const MyComponent = (props: Props) => (
  <div style={{ backgroundColor: props.backgroundColor }}>
    <button onClick={props.toggleOn}>
      Toggle is {props.isOn ? 'ON' : 'OFF'}
    </button>
  </div>
)

export default connector(MyComponent)
</code>```

Body:
I have this functional/stateless component:

import React from 'react';
import {useFormik} from 'formik';
import {connect} from "react-redux";

function mapStateToProps(){
  return {
     foo: "bar"
  }
}

interface OwnProps {
  propFromParent: number
}

type StateProps = ReturnType<typeof mapStateToProps>
type Props = StateProps & OwnProps

const SignupForm = (props: Props) => {

  const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: ''
    },
    onSubmit(values) {
      props.dispatch()   // props.dispatch is not defined!
    }
  });

  return (
    <form onSubmit={formik.handleSubmit}>
      Full Name
      <input
        id="name"
        name="name"
        type="name"
        onChange={formik.handleChange}
        value={formik.values.name}
      />
      <button type="submit">Submit</button>
    </form>
  );
};

export default connect<StateProps, null, Props>(mapStateToProps)(SignupForm);

so I am getting this compile error:

So how can I include the type definition so that props.dispatch is defined?
Just looking for help with the proper TS definitions.

Body:
Please see the React-Redux docs on "Static Typing", which show how to handle defining the correct types for what connect will pass into your component.

Specifically, we recommend using the ConnectedProps<T> helper, like this:

import { connect, ConnectedProps } from 'react-redux'

interface RootState {
  isOn: boolean
}

const mapState = (state: RootState) => ({
  isOn: state.isOn
})

const mapDispatch = {
  toggleOn: () => ({ type: 'TOGGLE_IS_ON' })
}

const connector = connect(
  mapState,
  mapDispatch
)

// The inferred type will look like:
// {isOn: boolean, toggleOn: () => void}
type PropsFromRedux = ConnectedProps<typeof connector>

interface Props extends PropsFromRedux {
  backgroundColor: string
}

const MyComponent = (props: Props) => (
  <div style={{ backgroundColor: props.backgroundColor }}>
    <button onClick={props.toggleOn}>
      Toggle is {props.isOn ? 'ON' : 'OFF'}
    </button>
  </div>
)

export default connector(MyComponent)


来源: stackexchange

问:
Regular expression to match characters inside a word
I am doing the Pig Latin text conversion:

One of the requirements is putting qu together.

What I did  re.findall(r'^qu', token)

but it only accepts qu together if the word/token starts with qu

If the word/token starts with aqu then it does not recognize qu together.

What I want is to recognize qu no matter the placement, including if it starts with Qu.

How do I fix this?

答: Remove the ^ from it, that cause this. The caret mean basically "start the matching from the beginning of the line (token in your case)".

ContentLicense: CC BY-SA 4.0


问:
Navbar dropdown menu href links not a working properly (Django+Bootstrap)
I am creating a small web application with using Django and Bootstrap4. In my Project Folder in Django, I have the templates and one of them is the base template. The other templates extend the base template. I have added the Bootstrap CDN to the base template and is working fine. I have created Bootstrap Navbar which get a dropdown when adjusted to screen size.

The issue is when I click a nav-link it adds the path in its href to the current path displayed in my browser i.e the location of the previous nav-link and searches for that. Hence it gives me an error. Upon clicking it should only take the path of only the clicked nav-link. My code is below. The href links are coming from my urls.py file. Please advise how to resolve this. Thanks.

base.html code

答: Thank you all for your responses. It works now. I used the href="{% url 'login' %} and ensured that the name-tag matched my urls.py file entry. </p>


问:
Using an I-frame on mechanical turk HIT?
I'd like to host an external website on AMT using an iframe and allow users to answer to respond on the website. However, I get the following error:

The resource from “https://requestersandbox.mturk.com/create/projects/worker-html.js” was blocked due to MIME type (“text/html”) mismatch (X-Content-Type-Options: nosniff).

Could this be caused by the use of a rest API (application/json)? If so, is there a way of fixing it or some work around?

答:
Are you using Express to host the external website? This answer seems to have the same error message and recommends a fix: https://stackoverflow.com/a/45119502/2601671

Also, the URL https://requestersandbox.mturk.com/create/projects/worker-html.js doesn't exist on the MTurk site. Is this a file you expect to have on your server?


问:
Changing the C# version in Visual Studio 2019
I'm using visual studio 2019 and I'm trying to change my C# version. The reason I am doing this is that the build servers I use use an older version of VS / MSBuild to build and deploy code (this is outside my control). Therefore I need to use C# 5.

On previous versions of visual studio, you could do this from the menu in [Project] -> Properties -> Build -> Advanced.
For VS2019 Microsoft, in their infinite wisdom, has decided to make this harder. Apparently you need to edit the project file manually and add:

```<code><PropertyGroup>
   <LangVersion>[some version here]</LangVersion>
</PropertyGroup>
</code>```

To your project file manually. That's all well and good, but I can't seem to get that working. It just ignores it, even after I unload and reload it. Here is a snapshot of my project file:

```<code><Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
   <LangVersion>5</LangVersion>
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{58FE5465-851B-471F-B6A9-9C861FA5C022}</ProjectGuid>
    <OutputType>Library</OutputType>
...
</code>```

Any idea how I can make this work? It's probably something really silly I'm missing.
Note: I did see this previous question but it was lacking detail.

答:
Turns out @lennart was right: There were some other <LangVersion>'s in the file. VS had snuck them into some of the build configurations.

```<code>    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x86\Debug\</OutputPath>
    <DefineConstants>TRACE;DEBUG;PLATFORM_X86</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x86</PlatformTarget>
    <LangVersion>7.3</LangVersion> <-- HERE!!
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
    <OutputPath>bin\x86\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>
</code>```

SOLUTION:
I deleted all these configuration special cases and it defaulted back to the language I had listed at the top of the file.

I can tell it worked in my case because it now rejects interpolated strings (e.g. $"{value}words") saying it's not available in C#5.

As for what language names work, both "5" and "5.0" worked for me. The rest of the options can be found here

I feel kind of dumb now, I hope this question will still be useful to some future people.

Body:
I'm using visual studio 2019 and I'm trying to change my C# version. The reason I am doing this is that the build servers I use use an older version of VS / MSBuild to build and deploy code (this is outside my control). Therefore I need to use C# 5.

On previous versions of visual studio, you could do this from the menu in [Project] -> Properties -> Build -> Advanced.
For VS2019 Microsoft, in their infinite wisdom, has decided to make this harder. Apparently you need to edit the project file manually and add:

<PropertyGroup>
   <LangVersion>[some version here]</LangVersion>
</PropertyGroup>

To your project file manually. That's all well and good, but I can't seem to get that working. It just ignores it, even after I unload and reload it. Here is a snapshot of my project file:

<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
   <LangVersion>5</LangVersion>
  </PropertyGroup>
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
    <ProjectGuid>{58FE5465-851B-471F-B6A9-9C861FA5C022}</ProjectGuid>
    <OutputType>Library</OutputType>
...

Any idea how I can make this work? It's probably something really silly I'm missing.
Note: I did see this previous question but it was lacking detail.

Body:
Turns out @lennart was right: There were some other <LangVersion>'s in the file. VS had snuck them into some of the build configurations.

    <WarningLevel>4</WarningLevel>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
    <DebugSymbols>true</DebugSymbols>
    <OutputPath>bin\x86\Debug\</OutputPath>
    <DefineConstants>TRACE;DEBUG;PLATFORM_X86</DefineConstants>
    <DebugType>full</DebugType>
    <PlatformTarget>x86</PlatformTarget>
    <LangVersion>7.3</LangVersion> <-- HERE!!
    <ErrorReport>prompt</ErrorReport>
    <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
    <OutputPath>bin\x86\Release\</OutputPath>
    <DefineConstants>TRACE</DefineConstants>

SOLUTION:
I deleted all these configuration special cases and it defaulted back to the language I had listed at the top of the file.

I can tell it worked in my case because it now rejects interpolated strings (e.g. $"{value}words") saying it's not available in C#5.

As for what language names work, both "5" and "5.0" worked for me. The rest of the options can be found here

I feel kind of dumb now, I hope this question will still be useful to some future people.


问:
why assigning instance variable inside method of implemented interface does not work while calling it from another local methods of the same class?
I have a class called "A" implements interface "I" like below

```<code>public interface I<T>{
   void setList(List<T> list)
}

public class A implements I<M>{
   private List<M> mList;

   public void load(){
      //Working on mList....
   }

   public void method(){
      someList;
      I<M> i = this;
      i.setList(someList);
   }

   public void setList(List<M> list){
      this.mList = list;
   }

}

public class M{
   private String str;
}

</code>```

I want to assign value of list to mList and use it wherever inside the class however the value will be assigned inside the overriden method but when I use mList in any other methods like load it does not give me the value.

答:
Finally I could find the solution I was supposed to do like below</p>

```<code>public interface I<T>{
   void setList(List<T> list)
}

public class A implements I<M>{
   private List<M> mList;
   I<M> i;

   public A(){
      this.i = this;
   }

   public void load(){
      //Working on mList....
   }

   public void method(){
      someList;
      i.setList(someList);
   }

   public void setList(List<M> list){
      this.mList = list;
   }

}

public class M{
   private String str;
}
</code>```

Body:
I have a class called "A" implements interface "I" like below

public interface I<T>{
   void setList(List<T> list)
}

public class A implements I<M>{
   private List<M> mList;

   public void load(){
      //Working on mList....
   }

   public void method(){
      someList;
      I<M> i = this;
      i.setList(someList);
   }

   public void setList(List<M> list){
      this.mList = list;
   }

}

public class M{
   private String str;
}

I want to assign value of list to mList and use it wherever inside the class however the value will be assigned inside the overriden method but when I use mList in any other methods like load it does not give me the value.

Body:
Finally I could find the solution I was supposed to do like below

public interface I<T>{
   void setList(List<T> list)
}

public class A implements I<M>{
   private List<M> mList;
   I<M> i;

   public A(){
      this.i = this;
   }

   public void load(){
      //Working on mList....
   }

   public void method(){
      someList;
      i.setList(someList);
   }

   public void setList(List<M> list){
      this.mList = list;
   }

}

public class M{
   private String str;
}


问:
How to use Order By in a stored procedure without using dynamic SQL
I've the following MS SQL stored procedure. I need to sort the results without using dynamic SQL and sp_executesql method

@Order by can have the possible values ProductName ASC, ProductName DESC, ProductCode ASC, VendorName DESC, VendorCode or ClientName

I was trying to use ORDER BY CASE, is there any issue if the  ProductName, ProductCode are of different type?

```<code>ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)

AS
BEGIN

IF (@OrderBy IS NULL) BEGIN
    SET @OrderBy = 'ProductName';
END

SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)
</code>```

Update:

Is the below part correct? ref from here

```<code>ORDER BY
    CASE @OrderBy WHEN 'ProductCode ASC' THEN ProductCode WHEN 'ProductCode DESC' THEN ProductCode END DESC,
    CASE @OrderBy WHEN 'ProductName ASC' THEN ProductName WHEN 'ProductName DESC' THEN ProductName END DESC,
</code>```

答:
I understand, the ordering uses just one column. In that case I might try something like this:

Split @OrderBy into @OrderByCol and @OrderByDir.

Use this template:

```<code>...
ORDER BY
  CASE @OrderByDir WHEN 'ASC' THEN
    CASE @OrderByCol
      WHEN 'Column1' THEN Column1
      WHEN 'Column2' THEN Column2
      ...
    END
  END ASC,

  CASE @OrderByDir WHEN 'DESC' THEN
    CASE @OrderByCol
      WHEN 'Column1' THEN Column1
      WHEN 'Column2' THEN Column2
      ...
    END
  END DESC
</code>```

Or, if you are on SQL Server 2005+, maybe this one, as an alternative:

```<code>WITH sorted AS (
  SELECT
     ... /* columns, omitted */
     Column1Order = ROW_NUMBER() OVER (ORDER BY Column1),
     Column2Order = ROW_NUMBER() OVER (ORDER BY Column2),
     ...
  FROM ...
)
SELECT ...
FROM sorted
ORDER BY
  CASE @OrderByCol
    WHEN 'Column1' THEN Column1Order
    WHEN 'Column2' THEN Column2Order
    ...
  END * CASE @OrderByDir WHEN 'DESC' THEN -1 ELSE 1 END
</code>```

As @Greg Ogle has correctly pointed out in the comment, the first template can only work when the various sorting criteria are of compatible types, otherwise the statement will break.

ContentLicense: CC BY-SA 3.0

Body:
I've the following MS SQL stored procedure. I need to sort the results without using dynamic SQL and sp_executesql method

@Order by can have the possible values ProductName ASC, ProductName DESC, ProductCode ASC, VendorName DESC, VendorCode or ClientName

I was trying to use ORDER BY CASE, is there any issue if the  ProductName, ProductCode are of different type?

ALTER PROCEDURE [dbo].[SortedReport]
(
    @ClientID INT,
    @RecordLimit,
    @FromDate DATETIME,
    @ToDate DATETIME,
    @OrderBy NVARCHAR(MAX)
)

AS
BEGIN

IF (@OrderBy IS NULL) BEGIN
    SET @OrderBy = 'ProductName';
END

SELECT TOP (@RecordLimit)
        sv.ClientID,
        sv.VendorID,
        sv.ProductID,
        sv.TransactionTime,
        sv.ClientName,
        sv.VendorName,
        sv.ProductName,
        sv.ProductCode,
        sv.VendorCode,
FROM SortedReportiew AS sv
WHERE (sv.ClientID = @ClientID)
    AND (sv.TransactionTime >= @FromDate)
    AND (sv.TransactionTime < @Date)

Update:

Is the below part correct? ref from here

ORDER BY
    CASE @OrderBy WHEN 'ProductCode ASC' THEN ProductCode WHEN 'ProductCode DESC' THEN ProductCode END DESC,
    CASE @OrderBy WHEN 'ProductName ASC' THEN ProductName WHEN 'ProductName DESC' THEN ProductName END DESC,

Body:
I understand, the ordering uses just one column. In that case I might try something like this:

Split @OrderBy into @OrderByCol and @OrderByDir.

Use this template:

...
ORDER BY
  CASE @OrderByDir WHEN 'ASC' THEN
    CASE @OrderByCol
      WHEN 'Column1' THEN Column1
      WHEN 'Column2' THEN Column2
      ...
    END
  END ASC,

  CASE @OrderByDir WHEN 'DESC' THEN
    CASE @OrderByCol
      WHEN 'Column1' THEN Column1
      WHEN 'Column2' THEN Column2
      ...
    END
  END DESC

Or, if you are on SQL Server 2005+, maybe this one, as an alternative:

WITH sorted AS (
  SELECT
     ... /* columns, omitted */
     Column1Order = ROW_NUMBER() OVER (ORDER BY Column1),
     Column2Order = ROW_NUMBER() OVER (ORDER BY Column2),
     ...
  FROM ...
)
SELECT ...
FROM sorted
ORDER BY
  CASE @OrderByCol
    WHEN 'Column1' THEN Column1Order
    WHEN 'Column2' THEN Column2Order
    ...
  END * CASE @OrderByDir WHEN 'DESC' THEN -1 ELSE 1 END

As @Greg Ogle has correctly pointed out in the comment, the first template can only work when the various sorting criteria are of compatible types, otherwise the statement will break.


问:
Character recognition model possibly overfitting?
I'm trying to train a model to recognize gestures drawn using a wand which is picked up by an IR camera and fed into a model.
I trained the model using an A-Z handwritten character dataset, as well as two additional custom symbols that I have trained.
Currently it detects all the symbols correctly when drawing them directly, but if any random symbols/drawings are put into the model it will also identify them as being one of the two custom symbols I've added.
This is my confusion matrix:

Any ideas?
Thanks!

答:
Well, since your model has to classify any given input into any one class, your model seems to be trying to classify the random inputs to your custom classes. It would be useful if you could provide more information about your custom classes.

I guess you could try introducing a component of confidence in your class predictions, i.e. assuming you're using softmax, for any input, you can only truly accept a classification if the probability given for a class is above a certain threshold, else classify as random.

Additionally, you could try adding another custom class and train your model with all the random symbols but I don't think it is ideal.


答:
Because there was only your data with one level, I use an example below to show how to use broom to get the statistic you need:

```<code>library(broom)
library(dplyr)

df = data.frame(
Machine = sample(c("LEG PRESS","Y PRESS"),100,replace=TRUE),
Contraction_Mode_Levels = sample(c("Con01","Con02","Con03"),100,replace=TRUE),
Rater_Mean = runif(100),
Participant_Age_Levels = sample(c("young","old"),100,replace=TRUE))

df %>% group_by(Machine,Contraction_Mode_Levels) %>% do(tidy(wilcox.test(Rater_Mean ~  Participant_Age_Levels,data=. )))

# A tibble: 6 x 6
# Groups:   Machine, Contraction_Mode_Levels [6]
  Machine   Contraction_Mode_Lev… statistic p.value method           alternative
  <fct>     <fct>                     <dbl>   <dbl> <chr>            <chr>
1 LEG PRESS Con01                        22   0.607 Wilcoxon rank s… two.sided
2 LEG PRESS Con02                        45   0.730 Wilcoxon rank s… two.sided
3 LEG PRESS Con03                        22   0.607 Wilcoxon rank s… two.sided
4 Y PRESS   Con01                        38   0.604 Wilcoxon rank s… two.sided
5 Y PRESS   Con02                        33   0.613 Wilcoxon rank s… two.sided
6 Y PRESS   Con03                        45   0.696 Wilcoxon rank s… two.sided
</code>```

From your code, I guess you are only interested in the difference in Rater_Mean between "young" and "old" groups in Participant_Age_Levels, hence you can write wilcox.test(Rater_Mean ~ Participant_Age_Levels) .

Title: Error: Column `` is of unsupported type NULL

Body:
structure(list(Date = c("2019.01.26", "2019.01.26", "2019.01.26",
"2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26",
"2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26",
"2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26", "2019.01.26",
"2019.01.26", "2019.01.26"), Participant = c("CV", "CV", "CV",
"CV", "CV", "CV", "CV", "CV", "CV", "CV", "CV", "CV", "CV", "CV",
"CV", "CV", "CV", "CV", "CV", "CV"), Machine_ASVZ = c("A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1", "A1",
"A1", "A1", "A1", "A1", "A1", "A1", "A1"), Machine = c("LEG PRESS",
"LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS",
"LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS",
"LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS",
"LEG PRESS", "LEG PRESS", "LEG PRESS", "LEG PRESS"), Set = c(1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2), Contraction_Mode = c("Con01",
"Con02", "Con03", "Con04", "Con05", "Con06", "Con07", "Con08",
"Con09", "Con10", "Con01", "Con02", "Con03", "Con04", "Con05",
"Con06", "Con07", "Con08", "Con09", "Con10"), Time_Video_CV = c(1340,
1160, 1220, 1260, 1560, 1020, 1060, 1100, 1060, 1040, 1080, 980,
1020, 1000, 940, 1000, 960, 1000, 900, 980), Time_Video_GRFD = c(1360,
1180, 1240, 1280, 1180, 1060, 1080, 1100, 1060, 1060, 1100, 980,
1020, 1020, 980, 1020, 960, 980, 920, 1040), Time_Smartphone_1 = c(1650,
1350, 1400, 1400, 1350, 1250, 1550, 1500, 1600, 1650, 2500, 1100,
1100, 1150, 1100, 1200, 1350, 1450, 1200, 1600), Time_Smartphone_3 = c(1700,
1350, 1350, 1350, 1300, 1250, 1600, 1500, 1650, 1650, 1300, 1100,
1150, 1150, 1100, 1150, 1200, 1400, 1400, 1700), Rater_Mean = c(1350,
1170, 1230, 1270, 1370, 1040, 1070, 1100, 1060, 1050, 1090, 980,
1020, 1010, 960, 1010, 960, 990, 910, 1010), Smartphone_Mean = c(1675,
1350, 1375, 1375, 1325, 1250, 1575, 1500, 1625, 1650, 1900, 1100,
1125, 1150, 1100, 1175, 1275, 1425, 1300, 1650), Relative_Diff = c(0.241,
0.154, 0.118, 0.083, 0.033, 0.202, 0.472, 0.364, 0.533, 0.571,
0.743, 0.122, 0.103, 0.139, 0.146, 0.163, 0.328, 0.439, 0.429,
0.634), RaterSmartphone_Diff = c(-325, -180, -145, -105, 45,
-210, -505, -400, -565, -600, -810, -120, -105, -140, -140, -165,
-315, -435, -390, -640), RaterSmartphone_Mean = c(1512.5, 1260,
1302.5, 1322.5, 1347.5, 1145, 1322.5, 1300, 1342.5, 1350, 1495,
1040, 1072.5, 1080, 1030, 1092.5, 1117.5, 1207.5, 1105, 1330),
    Contraction_Mode_Levels = c("Con", "Con", "Con", "Con", "Con",
    "Con", "Con", "Con", "Con", "Con", "Con", "Con", "Con", "Con",
    "Con", "Con", "Con", "Con", "Con", "Con"), Rater_Diff = c(-20,
    -20, -20, -20, 380, -40, -20, 0, 0, -20, -20, 0, 0, -20,
    -40, -20, 0, 20, -20, -60), Smartphone_Diff = c(-50, 0, 50,
    50, 50, 0, -50, 0, -50, 0, 1200, 0, -50, 0, 0, 50, 150, 50,
    -200, -100), RaterSmartphone_Diff_Potential_Outlier = c(FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE, TRUE, TRUE,
    TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, TRUE,
    TRUE), Rater_Diff_Potential_Outlier = c(FALSE, FALSE, FALSE,
    FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE),
    Smartphone_Diff_Potential_Outlier = c(FALSE, FALSE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE,
    FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE), Normalized_Error_Smartphone = c(19.4,
    13.33, 10.55, 7.64, 3.4, 16.8, 32.06, 26.67, 34.77, 36.36,
    42.63, 10.91, 9.33, 12.17, 12.73, 14.04, 24.71, 30.53, 30,
    38.79), Participant_Age_Levels = structure(c(1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L), .Label = c("old", "young"), class = "factor"), Participant_Age = c(42,
    42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42,
    42, 42, 42, 42)), row.names = c(NA, 20L), class = "data.frame")

Above you can find an exert of my data.frame. I try to group the data by Machine and Contraction_Mode_Levels and then to summarise a Mann-Withney-U test for both of the two factors "young" ang "old".

I am trying to run a Mann-Withney-U test as the follwing:

wilcox<-all_data_wide_outlier_levels %>%
  group_by(Machine,Contraction_Mode_Levels) %>%
  summarise_each(funs(wilcox.test(.[Participant_Age_Levels == "young"],
                                  .[Participant_Age_Levels == "old"],
                                  paired=FALSE, alternative = c("two.sided"))$parameter,
                      wilcox.test(.[Participant_Age_Levels == "young"],
                                  .[Participant_Age_Levels == "old"],
                                  paired=FALSE, alternative = c("two.sided"))$statistic,
                      wilcox.test(.[Participant_Age_Levels == "young"],
                                  .[Participant_Age_Levels == "old"],
                                  paired=FALSE, alternative = c("two.sided"))$p.value),
                 vars = Rater_Mean)

Which throws back a error:

Error: Column vars_$..1 is of unsupported type NULL

Body:
Because there was only your data with one level, I use an example below to show how to use broom to get the statistic you need:

library(broom)
library(dplyr)

df = data.frame(
Machine = sample(c("LEG PRESS","Y PRESS"),100,replace=TRUE),
Contraction_Mode_Levels = sample(c("Con01","Con02","Con03"),100,replace=TRUE),
Rater_Mean = runif(100),
Participant_Age_Levels = sample(c("young","old"),100,replace=TRUE))

df %>% group_by(Machine,Contraction_Mode_Levels) %>% do(tidy(wilcox.test(Rater_Mean ~  Participant_Age_Levels,data=. )))

# A tibble: 6 x 6
# Groups:   Machine, Contraction_Mode_Levels [6]
  Machine   Contraction_Mode_Lev… statistic p.value method           alternative
  <fct>     <fct>                     <dbl>   <dbl> <chr>            <chr>
1 LEG PRESS Con01                        22   0.607 Wilcoxon rank s… two.sided
2 LEG PRESS Con02                        45   0.730 Wilcoxon rank s… two.sided
3 LEG PRESS Con03                        22   0.607 Wilcoxon rank s… two.sided
4 Y PRESS   Con01                        38   0.604 Wilcoxon rank s… two.sided
5 Y PRESS   Con02                        33   0.613 Wilcoxon rank s… two.sided
6 Y PRESS   Con03                        45   0.696 Wilcoxon rank s… two.sided

From your code, I guess you are only interested in the difference in Rater_Mean between "young" and "old" groups in Participant_Age_Levels, hence you can write wilcox.test(Rater_Mean ~ Participant_Age_Levels) .


问:
How to change the BackColor of a ComboBox when DropdownStyle is DropDownList?
I'm trying to change the dispaly color of a ComboBox when the DropdownStyle property is DropdownList. When the property is changed to Dropdown from DropdownList the color changes.

How can I control the view color of the dropdown boxes ?

Thanks

答:
Just like mentioned above; You can set FlatStyle property to Popup/Flat. This way the back color will use in both DropDown and DropDownList mode.

But then you wont have the look you expected.
There's a trick i do where i create a panel and change its border property to FixedSingle. Change the color of the panel to as desired and then change its size property to match the size of your ComboBox. Eg to 80, 22.
On the position where you had your ComboBox, place your panel.
Place your combobox on the Panel.
If you can fine tune its position, When you debug, you will find that your ComboBox looks like it has a border.


问:
Most efficent way to calculate CRC64 with reflected input
I need to calculate a CRC-64 using this setup into this wonderful website: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html

As you can see I require "input reflected" and that means that I need to reverse the bit order of any byte (a bit annoying).
For the moment, I implemented this with a lookup table (for example 0x55 -> 0xAA), but I was wondering if there is any property of CRC which can be used to be more efficient.

This is my code (in C):

```<code>static const unsigned long long CRC64_TABLE[256] = {
    0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, 0x493366450E42ECDF, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A,
    0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x1C4488F3E8F96ED4,
    0x663D78FF90E185EF, 0x24CD9914390BB37C, 0xE3DCBB28C335E8C9, 0xA12C5AC36ADFDE5A, 0x2F0E1EBA9EA36930, 0x6DFEFF5137495FA3, 0xAAEFDD6DCD770416, 0xE81F3C86649D3285,
    0xF45BB4758C645C51, 0xB6AB559E258E6AC2, 0x71BA77A2DFB03177, 0x334A9649765A07E4, 0xBD68D2308226B08E, 0xFF9833DB2BCC861D, 0x388911E7D1F2DDA8, 0x7A79F00C7818EB3B,
    0xCC7AF1FF21C30BDE, 0x8E8A101488293D4D, 0x499B3228721766F8, 0x0B6BD3C3DBFD506B, 0x854997BA2F81E701, 0xC7B97651866BD192, 0x00A8546D7C558A27, 0x4258B586D5BFBCB4,
    0x5E1C3D753D46D260, 0x1CECDC9E94ACE4F3, 0xDBFDFEA26E92BF46, 0x990D1F49C77889D5, 0x172F5B3033043EBF, 0x55DFBADB9AEE082C, 0x92CE98E760D05399, 0xD03E790CC93A650A,
    0xAA478900B1228E31, 0xE8B768EB18C8B8A2, 0x2FA64AD7E2F6E317, 0x6D56AB3C4B1CD584, 0xE374EF45BF6062EE, 0xA1840EAE168A547D, 0x66952C92ECB40FC8, 0x2465CD79455E395B,
    0x3821458AADA7578F, 0x7AD1A461044D611C, 0xBDC0865DFE733AA9, 0xFF3067B657990C3A, 0x711223CFA3E5BB50, 0x33E2C2240A0F8DC3, 0xF4F3E018F031D676, 0xB60301F359DBE0E5,
    0xDA050215EA6C212F, 0x98F5E3FE438617BC, 0x5FE4C1C2B9B84C09, 0x1D14202910527A9A, 0x93366450E42ECDF0, 0xD1C685BB4DC4FB63, 0x16D7A787B7FAA0D6, 0x5427466C1E109645,
    0x4863CE9FF6E9F891, 0x0A932F745F03CE02, 0xCD820D48A53D95B7, 0x8F72ECA30CD7A324, 0x0150A8DAF8AB144E, 0x43A04931514122DD, 0x84B16B0DAB7F7968, 0xC6418AE602954FFB,
    0xBC387AEA7A8DA4C0, 0xFEC89B01D3679253, 0x39D9B93D2959C9E6, 0x7B2958D680B3FF75, 0xF50B1CAF74CF481F, 0xB7FBFD44DD257E8C, 0x70EADF78271B2539, 0x321A3E938EF113AA,
    0x2E5EB66066087D7E, 0x6CAE578BCFE24BED, 0xABBF75B735DC1058, 0xE94F945C9C3626CB, 0x676DD025684A91A1, 0x259D31CEC1A0A732, 0xE28C13F23B9EFC87, 0xA07CF2199274CA14,
    0x167FF3EACBAF2AF1, 0x548F120162451C62, 0x939E303D987B47D7, 0xD16ED1D631917144, 0x5F4C95AFC5EDC62E, 0x1DBC74446C07F0BD, 0xDAAD56789639AB08, 0x985DB7933FD39D9B,
    0x84193F60D72AF34F, 0xC6E9DE8B7EC0C5DC, 0x01F8FCB784FE9E69, 0x43081D5C2D14A8FA, 0xCD2A5925D9681F90, 0x8FDAB8CE70822903, 0x48CB9AF28ABC72B6, 0x0A3B7B1923564425,
    0x70428B155B4EAF1E, 0x32B26AFEF2A4998D, 0xF5A348C2089AC238, 0xB753A929A170F4AB, 0x3971ED50550C43C1, 0x7B810CBBFCE67552, 0xBC902E8706D82EE7, 0xFE60CF6CAF321874,
    0xE224479F47CB76A0, 0xA0D4A674EE214033, 0x67C58448141F1B86, 0x253565A3BDF52D15, 0xAB1721DA49899A7F, 0xE9E7C031E063ACEC, 0x2EF6E20D1A5DF759, 0x6C0603E6B3B7C1CA,
    0xF6FAE5C07D3274CD, 0xB40A042BD4D8425E, 0x731B26172EE619EB, 0x31EBC7FC870C2F78, 0xBFC9838573709812, 0xFD39626EDA9AAE81, 0x3A28405220A4F534, 0x78D8A1B9894EC3A7,
    0x649C294A61B7AD73, 0x266CC8A1C85D9BE0, 0xE17DEA9D3263C055, 0xA38D0B769B89F6C6, 0x2DAF4F0F6FF541AC, 0x6F5FAEE4C61F773F, 0xA84E8CD83C212C8A, 0xEABE6D3395CB1A19,
    0x90C79D3FEDD3F122, 0xD2377CD44439C7B1, 0x15265EE8BE079C04, 0x57D6BF0317EDAA97, 0xD9F4FB7AE3911DFD, 0x9B041A914A7B2B6E, 0x5C1538ADB04570DB, 0x1EE5D94619AF4648,
    0x02A151B5F156289C, 0x4051B05E58BC1E0F, 0x87409262A28245BA, 0xC5B073890B687329, 0x4B9237F0FF14C443, 0x0962D61B56FEF2D0, 0xCE73F427ACC0A965, 0x8C8315CC052A9FF6,
    0x3A80143F5CF17F13, 0x7870F5D4F51B4980, 0xBF61D7E80F251235, 0xFD913603A6CF24A6, 0x73B3727A52B393CC, 0x31439391FB59A55F, 0xF652B1AD0167FEEA, 0xB4A25046A88DC879,
    0xA8E6D8B54074A6AD, 0xEA16395EE99E903E, 0x2D071B6213A0CB8B, 0x6FF7FA89BA4AFD18, 0xE1D5BEF04E364A72, 0xA3255F1BE7DC7CE1, 0x64347D271DE22754, 0x26C49CCCB40811C7,
    0x5CBD6CC0CC10FAFC, 0x1E4D8D2B65FACC6F, 0xD95CAF179FC497DA, 0x9BAC4EFC362EA149, 0x158E0A85C2521623, 0x577EEB6E6BB820B0, 0x906FC95291867B05, 0xD29F28B9386C4D96,
    0xCEDBA04AD0952342, 0x8C2B41A1797F15D1, 0x4B3A639D83414E64, 0x09CA82762AAB78F7, 0x87E8C60FDED7CF9D, 0xC51827E4773DF90E, 0x020905D88D03A2BB, 0x40F9E43324E99428,
    0x2CFFE7D5975E55E2, 0x6E0F063E3EB46371, 0xA91E2402C48A38C4, 0xEBEEC5E96D600E57, 0x65CC8190991CB93D, 0x273C607B30F68FAE, 0xE02D4247CAC8D41B, 0xA2DDA3AC6322E288,
    0xBE992B5F8BDB8C5C, 0xFC69CAB42231BACF, 0x3B78E888D80FE17A, 0x7988096371E5D7E9, 0xF7AA4D1A85996083, 0xB55AACF12C735610, 0x724B8ECDD64D0DA5, 0x30BB6F267FA73B36,
    0x4AC29F2A07BFD00D, 0x08327EC1AE55E69E, 0xCF235CFD546BBD2B, 0x8DD3BD16FD818BB8, 0x03F1F96F09FD3CD2, 0x41011884A0170A41, 0x86103AB85A2951F4, 0xC4E0DB53F3C36767,
    0xD8A453A01B3A09B3, 0x9A54B24BB2D03F20, 0x5D45907748EE6495, 0x1FB5719CE1045206, 0x919735E51578E56C, 0xD367D40EBC92D3FF, 0x1476F63246AC884A, 0x568617D9EF46BED9,
    0xE085162AB69D5E3C, 0xA275F7C11F7768AF, 0x6564D5FDE549331A, 0x279434164CA30589, 0xA9B6706FB8DFB2E3, 0xEB46918411358470, 0x2C57B3B8EB0BDFC5, 0x6EA7525342E1E956,
    0x72E3DAA0AA188782, 0x30133B4B03F2B111, 0xF7021977F9CCEAA4, 0xB5F2F89C5026DC37, 0x3BD0BCE5A45A6B5D, 0x79205D0E0DB05DCE, 0xBE317F32F78E067B, 0xFCC19ED95E6430E8,
    0x86B86ED5267CDBD3, 0xC4488F3E8F96ED40, 0x0359AD0275A8B6F5, 0x41A94CE9DC428066, 0xCF8B0890283E370C, 0x8D7BE97B81D4019F, 0x4A6ACB477BEA5A2A, 0x089A2AACD2006CB9,
    0x14DEA25F3AF9026D, 0x562E43B4931334FE, 0x913F6188692D6F4B, 0xD3CF8063C0C759D8, 0x5DEDC41A34BBEEB2, 0x1F1D25F19D51D821, 0xD80C07CD676F8394, 0x9AFCE626CE85B507
};

static const unsigned char REVERSE_BITS_TABLE[256] = {
    // 0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F
    0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
    0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
    0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
    0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
    0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
    0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
    0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
    0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
    0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
    0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
    0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
    0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
    0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
    0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
    0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
    0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
};

unsigned long long calculateCRC64(unsigned char* data, unsigned long size)
{
    unsigned long long myCRC64 = 0;

    for(unsigned long i = 0; i < size; i++)
        myCRC64 = CRC64_TABLE[((myCRC64 >> 56) ^ REVERSE_BITS_TABLE[data[i]]) & 0xFF] ^ (myCRC64 << 8);

    return myCRC64;
}
</code>```

Thanks in advance for any help!

Update: actually I'm wondering if some properties of CRC allow me to get the same result using reflected table, opposite shifting, reciprocal / reverse polynomial... etc. That would let skip the step of reversing bits.

Solution: using reflected table, changing shift direction and reversing bits just of the very last result:

```<code>static const unsigned long long CRC64_TABLE_REF[256] = {
    0x0000000000000000, 0xB32E4CBE03A75F6F, 0xF4843657A840A05B, 0x47AA7AE9ABE7FF34, 0x7BD0C384FF8F5E33, 0xC8FE8F3AFC28015C, 0x8F54F5D357CFFE68, 0x3C7AB96D5468A107,
    0xF7A18709FF1EBC66, 0x448FCBB7FCB9E309, 0x0325B15E575E1C3D, 0xB00BFDE054F94352, 0x8C71448D0091E255, 0x3F5F08330336BD3A, 0x78F572DAA8D1420E, 0xCBDB3E64AB761D61,
    0x7D9BA13851336649, 0xCEB5ED8652943926, 0x891F976FF973C612, 0x3A31DBD1FAD4997D, 0x064B62BCAEBC387A, 0xB5652E02AD1B6715, 0xF2CF54EB06FC9821, 0x41E11855055BC74E,
    0x8A3A2631AE2DDA2F, 0x39146A8FAD8A8540, 0x7EBE1066066D7A74, 0xCD905CD805CA251B, 0xF1EAE5B551A2841C, 0x42C4A90B5205DB73, 0x056ED3E2F9E22447, 0xB6409F5CFA457B28,
    0xFB374270A266CC92, 0x48190ECEA1C193FD, 0x0FB374270A266CC9, 0xBC9D3899098133A6, 0x80E781F45DE992A1, 0x33C9CD4A5E4ECDCE, 0x7463B7A3F5A932FA, 0xC74DFB1DF60E6D95,
    0x0C96C5795D7870F4, 0xBFB889C75EDF2F9B, 0xF812F32EF538D0AF, 0x4B3CBF90F69F8FC0, 0x774606FDA2F72EC7, 0xC4684A43A15071A8, 0x83C230AA0AB78E9C, 0x30EC7C140910D1F3,
    0x86ACE348F355AADB, 0x3582AFF6F0F2F5B4, 0x7228D51F5B150A80, 0xC10699A158B255EF, 0xFD7C20CC0CDAF4E8, 0x4E526C720F7DAB87, 0x09F8169BA49A54B3, 0xBAD65A25A73D0BDC,
    0x710D64410C4B16BD, 0xC22328FF0FEC49D2, 0x85895216A40BB6E6, 0x36A71EA8A7ACE989, 0x0ADDA7C5F3C4488E, 0xB9F3EB7BF06317E1, 0xFE5991925B84E8D5, 0x4D77DD2C5823B7BA,
    0x64B62BCAEBC387A1, 0xD7986774E864D8CE, 0x90321D9D438327FA, 0x231C512340247895, 0x1F66E84E144CD992, 0xAC48A4F017EB86FD, 0xEBE2DE19BC0C79C9, 0x58CC92A7BFAB26A6,
    0x9317ACC314DD3BC7, 0x2039E07D177A64A8, 0x67939A94BC9D9B9C, 0xD4BDD62ABF3AC4F3, 0xE8C76F47EB5265F4, 0x5BE923F9E8F53A9B, 0x1C4359104312C5AF, 0xAF6D15AE40B59AC0,
    0x192D8AF2BAF0E1E8, 0xAA03C64CB957BE87, 0xEDA9BCA512B041B3, 0x5E87F01B11171EDC, 0x62FD4976457FBFDB, 0xD1D305C846D8E0B4, 0x96797F21ED3F1F80, 0x2557339FEE9840EF,
    0xEE8C0DFB45EE5D8E, 0x5DA24145464902E1, 0x1A083BACEDAEFDD5, 0xA9267712EE09A2BA, 0x955CCE7FBA6103BD, 0x267282C1B9C65CD2, 0x61D8F8281221A3E6, 0xD2F6B4961186FC89,
    0x9F8169BA49A54B33, 0x2CAF25044A02145C, 0x6B055FEDE1E5EB68, 0xD82B1353E242B407, 0xE451AA3EB62A1500, 0x577FE680B58D4A6F, 0x10D59C691E6AB55B, 0xA3FBD0D71DCDEA34,
    0x6820EEB3B6BBF755, 0xDB0EA20DB51CA83A, 0x9CA4D8E41EFB570E, 0x2F8A945A1D5C0861, 0x13F02D374934A966, 0xA0DE61894A93F609, 0xE7741B60E174093D, 0x545A57DEE2D35652,
    0xE21AC88218962D7A, 0x5134843C1B317215, 0x169EFED5B0D68D21, 0xA5B0B26BB371D24E, 0x99CA0B06E7197349, 0x2AE447B8E4BE2C26, 0x6D4E3D514F59D312, 0xDE6071EF4CFE8C7D,
    0x15BB4F8BE788911C, 0xA6950335E42FCE73, 0xE13F79DC4FC83147, 0x521135624C6F6E28, 0x6E6B8C0F1807CF2F, 0xDD45C0B11BA09040, 0x9AEFBA58B0476F74, 0x29C1F6E6B3E0301B,
    0xC96C5795D7870F42, 0x7A421B2BD420502D, 0x3DE861C27FC7AF19, 0x8EC62D7C7C60F076, 0xB2BC941128085171, 0x0192D8AF2BAF0E1E, 0x4638A2468048F12A, 0xF516EEF883EFAE45,
    0x3ECDD09C2899B324, 0x8DE39C222B3EEC4B, 0xCA49E6CB80D9137F, 0x7967AA75837E4C10, 0x451D1318D716ED17, 0xF6335FA6D4B1B278, 0xB199254F7F564D4C, 0x02B769F17CF11223,
    0xB4F7F6AD86B4690B, 0x07D9BA1385133664, 0x4073C0FA2EF4C950, 0xF35D8C442D53963F, 0xCF273529793B3738, 0x7C0979977A9C6857, 0x3BA3037ED17B9763, 0x888D4FC0D2DCC80C,
    0x435671A479AAD56D, 0xF0783D1A7A0D8A02, 0xB7D247F3D1EA7536, 0x04FC0B4DD24D2A59, 0x3886B22086258B5E, 0x8BA8FE9E8582D431, 0xCC0284772E652B05, 0x7F2CC8C92DC2746A,
    0x325B15E575E1C3D0, 0x8175595B76469CBF, 0xC6DF23B2DDA1638B, 0x75F16F0CDE063CE4, 0x498BD6618A6E9DE3, 0xFAA59ADF89C9C28C, 0xBD0FE036222E3DB8, 0x0E21AC88218962D7,
    0xC5FA92EC8AFF7FB6, 0x76D4DE52895820D9, 0x317EA4BB22BFDFED, 0x8250E80521188082, 0xBE2A516875702185, 0x0D041DD676D77EEA, 0x4AAE673FDD3081DE, 0xF9802B81DE97DEB1,
    0x4FC0B4DD24D2A599, 0xFCEEF8632775FAF6, 0xBB44828A8C9205C2, 0x086ACE348F355AAD, 0x34107759DB5DFBAA, 0x873E3BE7D8FAA4C5, 0xC094410E731D5BF1, 0x73BA0DB070BA049E,
    0xB86133D4DBCC19FF, 0x0B4F7F6AD86B4690, 0x4CE50583738CB9A4, 0xFFCB493D702BE6CB, 0xC3B1F050244347CC, 0x709FBCEE27E418A3, 0x3735C6078C03E797, 0x841B8AB98FA4B8F8,
    0xADDA7C5F3C4488E3, 0x1EF430E13FE3D78C, 0x595E4A08940428B8, 0xEA7006B697A377D7, 0xD60ABFDBC3CBD6D0, 0x6524F365C06C89BF, 0x228E898C6B8B768B, 0x91A0C532682C29E4,
    0x5A7BFB56C35A3485, 0xE955B7E8C0FD6BEA, 0xAEFFCD016B1A94DE, 0x1DD181BF68BDCBB1, 0x21AB38D23CD56AB6, 0x9285746C3F7235D9, 0xD52F0E859495CAED, 0x6601423B97329582,
    0xD041DD676D77EEAA, 0x636F91D96ED0B1C5, 0x24C5EB30C5374EF1, 0x97EBA78EC690119E, 0xAB911EE392F8B099, 0x18BF525D915FEFF6, 0x5F1528B43AB810C2, 0xEC3B640A391F4FAD,
    0x27E05A6E926952CC, 0x94CE16D091CE0DA3, 0xD3646C393A29F297, 0x604A2087398EADF8, 0x5C3099EA6DE60CFF, 0xEF1ED5546E415390, 0xA8B4AFBDC5A6ACA4, 0x1B9AE303C601F3CB,
    0x56ED3E2F9E224471, 0xE5C372919D851B1E, 0xA26908783662E42A, 0x114744C635C5BB45, 0x2D3DFDAB61AD1A42, 0x9E13B115620A452D, 0xD9B9CBFCC9EDBA19, 0x6A978742CA4AE576,
    0xA14CB926613CF817, 0x1262F598629BA778, 0x55C88F71C97C584C, 0xE6E6C3CFCADB0723, 0xDA9C7AA29EB3A624, 0x69B2361C9D14F94B, 0x2E184CF536F3067F, 0x9D36004B35545910,
    0x2B769F17CF112238, 0x9858D3A9CCB67D57, 0xDFF2A94067518263, 0x6CDCE5FE64F6DD0C, 0x50A65C93309E7C0B, 0xE388102D33392364, 0xA4226AC498DEDC50, 0x170C267A9B79833F,
    0xDCD7181E300F9E5E, 0x6FF954A033A8C131, 0x28532E49984F3E05, 0x9B7D62F79BE8616A, 0xA707DB9ACF80C06D, 0x14299724CC279F02, 0x5383EDCD67C06036, 0xE0ADA17364673F59
};

unsigned long long calculateCRC64(unsigned char* data, unsigned long size)
{
    unsigned long long myCRC64 = 0;

    for(unsigned long i = 0; i < size; i++)
        myCRC64 = CRC64_TABLE_REF[(myCRC64 ^ data[i]) & 0xFF] ^ (myCRC64 >> 8);

    unsigned long long tmp = myCRC64;
    myCRC64 = 0;
    for (int i = 0; i < 64; i++) {
        myCRC64 = (myCRC64 << 1) | (tmp & 1);
        tmp >>= 1;
    }

    return myCRC64;
}
</code>```

Thanks to everybody for the help!

答:
actually I'm wondering if some properties of CRC allow me to get the same result using reflected table, opposite shifting, reciprocal / reverse polynomial... etc. That would let skip the step of reversing bits.

There is such a property, and you only need one reverse, in the end. The whole logic of the CRC can be bit-reversed*, so that the bits stream the opposite way and don't need to be reversed during the calculation itself:

```<code>unsigned long long CRC64(unsigned char* data, unsigned long size)
{
    unsigned long long crc = 0;

    for(unsigned long i = 0; i < size; i++)
        crc = CRC64_TABLE_R[(crc & 0xff) ^ data[i]] ^ (crc >> 8);

    return rbit(crc);
}
</code>```

CRC64_TABLE_R is like CRC64_TABLE, but with the entries and indexes both bit-reversed. So they relate to each other like this: (naturally you would hard-code this table)

```<code>for (int i = 0; i < 256; i++) {
    CRC64_TABLE_R[REVERSE_BITS_TABLE[i]] = rbit(CRC64_TABLE[i]);
}
</code>```

rbit is just some function that reverses bits, I used this really dumb one, use a better one if you want but it's only used once:

```<code>unsigned long long rbit(unsigned long long n)
{
    unsigned long long x = 0;
    for (int i = 0; i < 64; i++) {
        x = (x << 1) | (n & 1);
        n >>= 1;
    }
    return x;
}
</code>```

*: really what this means is that the integer holding the bits during the calculation is viewed in reverse, with what would normally be its least significant bit instead held in its most significant bit etc. So depending on how you look at it, the calculation is not even different. The same bits are created, but we hold them in a variable differently.

Body:
I need to calculate a CRC-64 using this setup into this wonderful website: http://www.sunshine2k.de/coding/javascript/crc/crc_js.html

As you can see I require "input reflected" and that means that I need to reverse the bit order of any byte (a bit annoying).
For the moment, I implemented this with a lookup table (for example 0x55 -> 0xAA), but I was wondering if there is any property of CRC which can be used to be more efficient.

This is my code (in C):

static const unsigned long long CRC64_TABLE[256] = {
    0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, 0x493366450E42ECDF, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A,
    0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x1C4488F3E8F96ED4,
    0x663D78FF90E185EF, 0x24CD9914390BB37C, 0xE3DCBB28C335E8C9, 0xA12C5AC36ADFDE5A, 0x2F0E1EBA9EA36930, 0x6DFEFF5137495FA3, 0xAAEFDD6DCD770416, 0xE81F3C86649D3285,
    0xF45BB4758C645C51, 0xB6AB559E258E6AC2, 0x71BA77A2DFB03177, 0x334A9649765A07E4, 0xBD68D2308226B08E, 0xFF9833DB2BCC861D, 0x388911E7D1F2DDA8, 0x7A79F00C7818EB3B,
    0xCC7AF1FF21C30BDE, 0x8E8A101488293D4D, 0x499B3228721766F8, 0x0B6BD3C3DBFD506B, 0x854997BA2F81E701, 0xC7B97651866BD192, 0x00A8546D7C558A27, 0x4258B586D5BFBCB4,
    0x5E1C3D753D46D260, 0x1CECDC9E94ACE4F3, 0xDBFDFEA26E92BF46, 0x990D1F49C77889D5, 0x172F5B3033043EBF, 0x55DFBADB9AEE082C, 0x92CE98E760D05399, 0xD03E790CC93A650A,
    0xAA478900B1228E31, 0xE8B768EB18C8B8A2, 0x2FA64AD7E2F6E317, 0x6D56AB3C4B1CD584, 0xE374EF45BF6062EE, 0xA1840EAE168A547D, 0x66952C92ECB40FC8, 0x2465CD79455E395B,
    0x3821458AADA7578F, 0x7AD1A461044D611C, 0xBDC0865DFE733AA9, 0xFF3067B657990C3A, 0x711223CFA3E5BB50, 0x33E2C2240A0F8DC3, 0xF4F3E018F031D676, 0xB60301F359DBE0E5,
    0xDA050215EA6C212F, 0x98F5E3FE438617BC, 0x5FE4C1C2B9B84C09, 0x1D14202910527A9A, 0x93366450E42ECDF0, 0xD1C685BB4DC4FB63, 0x16D7A787B7FAA0D6, 0x5427466C1E109645,
    0x4863CE9FF6E9F891, 0x0A932F745F03CE02, 0xCD820D48A53D95B7, 0x8F72ECA30CD7A324, 0x0150A8DAF8AB144E, 0x43A04931514122DD, 0x84B16B0DAB7F7968, 0xC6418AE602954FFB,
    0xBC387AEA7A8DA4C0, 0xFEC89B01D3679253, 0x39D9B93D2959C9E6, 0x7B2958D680B3FF75, 0xF50B1CAF74CF481F, 0xB7FBFD44DD257E8C, 0x70EADF78271B2539, 0x321A3E938EF113AA,
    0x2E5EB66066087D7E, 0x6CAE578BCFE24BED, 0xABBF75B735DC1058, 0xE94F945C9C3626CB, 0x676DD025684A91A1, 0x259D31CEC1A0A732, 0xE28C13F23B9EFC87, 0xA07CF2199274CA14,
    0x167FF3EACBAF2AF1, 0x548F120162451C62, 0x939E303D987B47D7, 0xD16ED1D631917144, 0x5F4C95AFC5EDC62E, 0x1DBC74446C07F0BD, 0xDAAD56789639AB08, 0x985DB7933FD39D9B,
    0x84193F60D72AF34F, 0xC6E9DE8B7EC0C5DC, 0x01F8FCB784FE9E69, 0x43081D5C2D14A8FA, 0xCD2A5925D9681F90, 0x8FDAB8CE70822903, 0x48CB9AF28ABC72B6, 0x0A3B7B1923564425,
    0x70428B155B4EAF1E, 0x32B26AFEF2A4998D, 0xF5A348C2089AC238, 0xB753A929A170F4AB, 0x3971ED50550C43C1, 0x7B810CBBFCE67552, 0xBC902E8706D82EE7, 0xFE60CF6CAF321874,
    0xE224479F47CB76A0, 0xA0D4A674EE214033, 0x67C58448141F1B86, 0x253565A3BDF52D15, 0xAB1721DA49899A7F, 0xE9E7C031E063ACEC, 0x2EF6E20D1A5DF759, 0x6C0603E6B3B7C1CA,
    0xF6FAE5C07D3274CD, 0xB40A042BD4D8425E, 0x731B26172EE619EB, 0x31EBC7FC870C2F78, 0xBFC9838573709812, 0xFD39626EDA9AAE81, 0x3A28405220A4F534, 0x78D8A1B9894EC3A7,
    0x649C294A61B7AD73, 0x266CC8A1C85D9BE0, 0xE17DEA9D3263C055, 0xA38D0B769B89F6C6, 0x2DAF4F0F6FF541AC, 0x6F5FAEE4C61F773F, 0xA84E8CD83C212C8A, 0xEABE6D3395CB1A19,
    0x90C79D3FEDD3F122, 0xD2377CD44439C7B1, 0x15265EE8BE079C04, 0x57D6BF0317EDAA97, 0xD9F4FB7AE3911DFD, 0x9B041A914A7B2B6E, 0x5C1538ADB04570DB, 0x1EE5D94619AF4648,
    0x02A151B5F156289C, 0x4051B05E58BC1E0F, 0x87409262A28245BA, 0xC5B073890B687329, 0x4B9237F0FF14C443, 0x0962D61B56FEF2D0, 0xCE73F427ACC0A965, 0x8C8315CC052A9FF6,
    0x3A80143F5CF17F13, 0x7870F5D4F51B4980, 0xBF61D7E80F251235, 0xFD913603A6CF24A6, 0x73B3727A52B393CC, 0x31439391FB59A55F, 0xF652B1AD0167FEEA, 0xB4A25046A88DC879,
    0xA8E6D8B54074A6AD, 0xEA16395EE99E903E, 0x2D071B6213A0CB8B, 0x6FF7FA89BA4AFD18, 0xE1D5BEF04E364A72, 0xA3255F1BE7DC7CE1, 0x64347D271DE22754, 0x26C49CCCB40811C7,
    0x5CBD6CC0CC10FAFC, 0x1E4D8D2B65FACC6F, 0xD95CAF179FC497DA, 0x9BAC4EFC362EA149, 0x158E0A85C2521623, 0x577EEB6E6BB820B0, 0x906FC95291867B05, 0xD29F28B9386C4D96,
    0xCEDBA04AD0952342, 0x8C2B41A1797F15D1, 0x4B3A639D83414E64, 0x09CA82762AAB78F7, 0x87E8C60FDED7CF9D, 0xC51827E4773DF90E, 0x020905D88D03A2BB, 0x40F9E43324E99428,
    0x2CFFE7D5975E55E2, 0x6E0F063E3EB46371, 0xA91E2402C48A38C4, 0xEBEEC5E96D600E57, 0x65CC8190991CB93D, 0x273C607B30F68FAE, 0xE02D4247CAC8D41B, 0xA2DDA3AC6322E288,
    0xBE992B5F8BDB8C5C, 0xFC69CAB42231BACF, 0x3B78E888D80FE17A, 0x7988096371E5D7E9, 0xF7AA4D1A85996083, 0xB55AACF12C735610, 0x724B8ECDD64D0DA5, 0x30BB6F267FA73B36,
    0x4AC29F2A07BFD00D, 0x08327EC1AE55E69E, 0xCF235CFD546BBD2B, 0x8DD3BD16FD818BB8, 0x03F1F96F09FD3CD2, 0x41011884A0170A41, 0x86103AB85A2951F4, 0xC4E0DB53F3C36767,
    0xD8A453A01B3A09B3, 0x9A54B24BB2D03F20, 0x5D45907748EE6495, 0x1FB5719CE1045206, 0x919735E51578E56C, 0xD367D40EBC92D3FF, 0x1476F63246AC884A, 0x568617D9EF46BED9,
    0xE085162AB69D5E3C, 0xA275F7C11F7768AF, 0x6564D5FDE549331A, 0x279434164CA30589, 0xA9B6706FB8DFB2E3, 0xEB46918411358470, 0x2C57B3B8EB0BDFC5, 0x6EA7525342E1E956,
    0x72E3DAA0AA188782, 0x30133B4B03F2B111, 0xF7021977F9CCEAA4, 0xB5F2F89C5026DC37, 0x3BD0BCE5A45A6B5D, 0x79205D0E0DB05DCE, 0xBE317F32F78E067B, 0xFCC19ED95E6430E8,
    0x86B86ED5267CDBD3, 0xC4488F3E8F96ED40, 0x0359AD0275A8B6F5, 0x41A94CE9DC428066, 0xCF8B0890283E370C, 0x8D7BE97B81D4019F, 0x4A6ACB477BEA5A2A, 0x089A2AACD2006CB9,
    0x14DEA25F3AF9026D, 0x562E43B4931334FE, 0x913F6188692D6F4B, 0xD3CF8063C0C759D8, 0x5DEDC41A34BBEEB2, 0x1F1D25F19D51D821, 0xD80C07CD676F8394, 0x9AFCE626CE85B507
};

static const unsigned char REVERSE_BITS_TABLE[256] = {
    // 0     1     2     3     4     5     6     7     8     9     A     B     C     D     E     F
    0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0, 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
    0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8, 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
    0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4, 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
    0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC, 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
    0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2, 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
    0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA, 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
    0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6, 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
    0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE, 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
    0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1, 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
    0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9, 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
    0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5, 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
    0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED, 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
    0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3, 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
    0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB, 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
    0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7, 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
    0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF, 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
};

unsigned long long calculateCRC64(unsigned char* data, unsigned long size)
{
    unsigned long long myCRC64 = 0;

    for(unsigned long i = 0; i < size; i++)
        myCRC64 = CRC64_TABLE[((myCRC64 >> 56) ^ REVERSE_BITS_TABLE[data[i]]) & 0xFF] ^ (myCRC64 << 8);

    return myCRC64;
}

Thanks in advance for any help!

Update: actually I'm wondering if some properties of CRC allow me to get the same result using reflected table, opposite shifting, reciprocal / reverse polynomial... etc. That would let skip the step of reversing bits.

Solution: using reflected table, changing shift direction and reversing bits just of the very last result:

static const unsigned long long CRC64_TABLE_REF[256] = {
    0x0000000000000000, 0xB32E4CBE03A75F6F, 0xF4843657A840A05B, 0x47AA7AE9ABE7FF34, 0x7BD0C384FF8F5E33, 0xC8FE8F3AFC28015C, 0x8F54F5D357CFFE68, 0x3C7AB96D5468A107,
    0xF7A18709FF1EBC66, 0x448FCBB7FCB9E309, 0x0325B15E575E1C3D, 0xB00BFDE054F94352, 0x8C71448D0091E255, 0x3F5F08330336BD3A, 0x78F572DAA8D1420E, 0xCBDB3E64AB761D61,
    0x7D9BA13851336649, 0xCEB5ED8652943926, 0x891F976FF973C612, 0x3A31DBD1FAD4997D, 0x064B62BCAEBC387A, 0xB5652E02AD1B6715, 0xF2CF54EB06FC9821, 0x41E11855055BC74E,
    0x8A3A2631AE2DDA2F, 0x39146A8FAD8A8540, 0x7EBE1066066D7A74, 0xCD905CD805CA251B, 0xF1EAE5B551A2841C, 0x42C4A90B5205DB73, 0x056ED3E2F9E22447, 0xB6409F5CFA457B28,
    0xFB374270A266CC92, 0x48190ECEA1C193FD, 0x0FB374270A266CC9, 0xBC9D3899098133A6, 0x80E781F45DE992A1, 0x33C9CD4A5E4ECDCE, 0x7463B7A3F5A932FA, 0xC74DFB1DF60E6D95,
    0x0C96C5795D7870F4, 0xBFB889C75EDF2F9B, 0xF812F32EF538D0AF, 0x4B3CBF90F69F8FC0, 0x774606FDA2F72EC7, 0xC4684A43A15071A8, 0x83C230AA0AB78E9C, 0x30EC7C140910D1F3,
    0x86ACE348F355AADB, 0x3582AFF6F0F2F5B4, 0x7228D51F5B150A80, 0xC10699A158B255EF, 0xFD7C20CC0CDAF4E8, 0x4E526C720F7DAB87, 0x09F8169BA49A54B3, 0xBAD65A25A73D0BDC,
    0x710D64410C4B16BD, 0xC22328FF0FEC49D2, 0x85895216A40BB6E6, 0x36A71EA8A7ACE989, 0x0ADDA7C5F3C4488E, 0xB9F3EB7BF06317E1, 0xFE5991925B84E8D5, 0x4D77DD2C5823B7BA,
    0x64B62BCAEBC387A1, 0xD7986774E864D8CE, 0x90321D9D438327FA, 0x231C512340247895, 0x1F66E84E144CD992, 0xAC48A4F017EB86FD, 0xEBE2DE19BC0C79C9, 0x58CC92A7BFAB26A6,
    0x9317ACC314DD3BC7, 0x2039E07D177A64A8, 0x67939A94BC9D9B9C, 0xD4BDD62ABF3AC4F3, 0xE8C76F47EB5265F4, 0x5BE923F9E8F53A9B, 0x1C4359104312C5AF, 0xAF6D15AE40B59AC0,
    0x192D8AF2BAF0E1E8, 0xAA03C64CB957BE87, 0xEDA9BCA512B041B3, 0x5E87F01B11171EDC, 0x62FD4976457FBFDB, 0xD1D305C846D8E0B4, 0x96797F21ED3F1F80, 0x2557339FEE9840EF,
    0xEE8C0DFB45EE5D8E, 0x5DA24145464902E1, 0x1A083BACEDAEFDD5, 0xA9267712EE09A2BA, 0x955CCE7FBA6103BD, 0x267282C1B9C65CD2, 0x61D8F8281221A3E6, 0xD2F6B4961186FC89,
    0x9F8169BA49A54B33, 0x2CAF25044A02145C, 0x6B055FEDE1E5EB68, 0xD82B1353E242B407, 0xE451AA3EB62A1500, 0x577FE680B58D4A6F, 0x10D59C691E6AB55B, 0xA3FBD0D71DCDEA34,
    0x6820EEB3B6BBF755, 0xDB0EA20DB51CA83A, 0x9CA4D8E41EFB570E, 0x2F8A945A1D5C0861, 0x13F02D374934A966, 0xA0DE61894A93F609, 0xE7741B60E174093D, 0x545A57DEE2D35652,
    0xE21AC88218962D7A, 0x5134843C1B317215, 0x169EFED5B0D68D21, 0xA5B0B26BB371D24E, 0x99CA0B06E7197349, 0x2AE447B8E4BE2C26, 0x6D4E3D514F59D312, 0xDE6071EF4CFE8C7D,
    0x15BB4F8BE788911C, 0xA6950335E42FCE73, 0xE13F79DC4FC83147, 0x521135624C6F6E28, 0x6E6B8C0F1807CF2F, 0xDD45C0B11BA09040, 0x9AEFBA58B0476F74, 0x29C1F6E6B3E0301B,
    0xC96C5795D7870F42, 0x7A421B2BD420502D, 0x3DE861C27FC7AF19, 0x8EC62D7C7C60F076, 0xB2BC941128085171, 0x0192D8AF2BAF0E1E, 0x4638A2468048F12A, 0xF516EEF883EFAE45,
    0x3ECDD09C2899B324, 0x8DE39C222B3EEC4B, 0xCA49E6CB80D9137F, 0x7967AA75837E4C10, 0x451D1318D716ED17, 0xF6335FA6D4B1B278, 0xB199254F7F564D4C, 0x02B769F17CF11223,
    0xB4F7F6AD86B4690B, 0x07D9BA1385133664, 0x4073C0FA2EF4C950, 0xF35D8C442D53963F, 0xCF273529793B3738, 0x7C0979977A9C6857, 0x3BA3037ED17B9763, 0x888D4FC0D2DCC80C,
    0x435671A479AAD56D, 0xF0783D1A7A0D8A02, 0xB7D247F3D1EA7536, 0x04FC0B4DD24D2A59, 0x3886B22086258B5E, 0x8BA8FE9E8582D431, 0xCC0284772E652B05, 0x7F2CC8C92DC2746A,
    0x325B15E575E1C3D0, 0x8175595B76469CBF, 0xC6DF23B2DDA1638B, 0x75F16F0CDE063CE4, 0x498BD6618A6E9DE3, 0xFAA59ADF89C9C28C, 0xBD0FE036222E3DB8, 0x0E21AC88218962D7,
    0xC5FA92EC8AFF7FB6, 0x76D4DE52895820D9, 0x317EA4BB22BFDFED, 0x8250E80521188082, 0xBE2A516875702185, 0x0D041DD676D77EEA, 0x4AAE673FDD3081DE, 0xF9802B81DE97DEB1,
    0x4FC0B4DD24D2A599, 0xFCEEF8632775FAF6, 0xBB44828A8C9205C2, 0x086ACE348F355AAD, 0x34107759DB5DFBAA, 0x873E3BE7D8FAA4C5, 0xC094410E731D5BF1, 0x73BA0DB070BA049E,
    0xB86133D4DBCC19FF, 0x0B4F7F6AD86B4690, 0x4CE50583738CB9A4, 0xFFCB493D702BE6CB, 0xC3B1F050244347CC, 0x709FBCEE27E418A3, 0x3735C6078C03E797, 0x841B8AB98FA4B8F8,
    0xADDA7C5F3C4488E3, 0x1EF430E13FE3D78C, 0x595E4A08940428B8, 0xEA7006B697A377D7, 0xD60ABFDBC3CBD6D0, 0x6524F365C06C89BF, 0x228E898C6B8B768B, 0x91A0C532682C29E4,
    0x5A7BFB56C35A3485, 0xE955B7E8C0FD6BEA, 0xAEFFCD016B1A94DE, 0x1DD181BF68BDCBB1, 0x21AB38D23CD56AB6, 0x9285746C3F7235D9, 0xD52F0E859495CAED, 0x6601423B97329582,
    0xD041DD676D77EEAA, 0x636F91D96ED0B1C5, 0x24C5EB30C5374EF1, 0x97EBA78EC690119E, 0xAB911EE392F8B099, 0x18BF525D915FEFF6, 0x5F1528B43AB810C2, 0xEC3B640A391F4FAD,
    0x27E05A6E926952CC, 0x94CE16D091CE0DA3, 0xD3646C393A29F297, 0x604A2087398EADF8, 0x5C3099EA6DE60CFF, 0xEF1ED5546E415390, 0xA8B4AFBDC5A6ACA4, 0x1B9AE303C601F3CB,
    0x56ED3E2F9E224471, 0xE5C372919D851B1E, 0xA26908783662E42A, 0x114744C635C5BB45, 0x2D3DFDAB61AD1A42, 0x9E13B115620A452D, 0xD9B9CBFCC9EDBA19, 0x6A978742CA4AE576,
    0xA14CB926613CF817, 0x1262F598629BA778, 0x55C88F71C97C584C, 0xE6E6C3CFCADB0723, 0xDA9C7AA29EB3A624, 0x69B2361C9D14F94B, 0x2E184CF536F3067F, 0x9D36004B35545910,
    0x2B769F17CF112238, 0x9858D3A9CCB67D57, 0xDFF2A94067518263, 0x6CDCE5FE64F6DD0C, 0x50A65C93309E7C0B, 0xE388102D33392364, 0xA4226AC498DEDC50, 0x170C267A9B79833F,
    0xDCD7181E300F9E5E, 0x6FF954A033A8C131, 0x28532E49984F3E05, 0x9B7D62F79BE8616A, 0xA707DB9ACF80C06D, 0x14299724CC279F02, 0x5383EDCD67C06036, 0xE0ADA17364673F59
};

unsigned long long calculateCRC64(unsigned char* data, unsigned long size)
{
    unsigned long long myCRC64 = 0;

    for(unsigned long i = 0; i < size; i++)
        myCRC64 = CRC64_TABLE_REF[(myCRC64 ^ data[i]) & 0xFF] ^ (myCRC64 >> 8);

    unsigned long long tmp = myCRC64;
    myCRC64 = 0;
    for (int i = 0; i < 64; i++) {
        myCRC64 = (myCRC64 << 1) | (tmp & 1);
        tmp >>= 1;
    }

    return myCRC64;
}

Thanks to everybody for the help!

Body:
actually I'm wondering if some properties of CRC allow me to get the same result using reflected table, opposite shifting, reciprocal / reverse polynomial... etc. That would let skip the step of reversing bits.

There is such a property, and you only need one reverse, in the end. The whole logic of the CRC can be bit-reversed*, so that the bits stream the opposite way and don't need to be reversed during the calculation itself:

unsigned long long CRC64(unsigned char* data, unsigned long size)
{
    unsigned long long crc = 0;

    for(unsigned long i = 0; i < size; i++)
        crc = CRC64_TABLE_R[(crc & 0xff) ^ data[i]] ^ (crc >> 8);

    return rbit(crc);
}

CRC64_TABLE_R is like CRC64_TABLE, but with the entries and indexes both bit-reversed. So they relate to each other like this: (naturally you would hard-code this table)

for (int i = 0; i < 256; i++) {
    CRC64_TABLE_R[REVERSE_BITS_TABLE[i]] = rbit(CRC64_TABLE[i]);
}

rbit is just some function that reverses bits, I used this really dumb one, use a better one if you want but it's only used once:

unsigned long long rbit(unsigned long long n)
{
    unsigned long long x = 0;
    for (int i = 0; i < 64; i++) {
        x = (x << 1) | (n & 1);
        n >>= 1;
    }
    return x;
}

*: really what this means is that the integer holding the bits during the calculation is viewed in reverse, with what would normally be its least significant bit instead held in its most significant bit etc. So depending on how you look at it, the calculation is not even different. The same bits are created, but we hold them in a variable differently.


问:
Ragged Arrays and For Loop errors
I get a bad access error in the middle of the for loop, always when i=4. Does anybody know the reason for this? It works until i=4, but I don't see why I wouldn't get the bad access error in any other part of the for loop.</p>

```<code>    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>

    #define MAXF 51
    #define MAXFILE 200

int recommend(int fid, char *funcs[]){
int i;

for(i=0; i<fid; i++)
    *funcs++;
printf("\nRecommended Function: %s\n", *funcs);

return 0;
}

int overlap(char *list[], char name[], int n){
int over=0, fid=202, i, j, k, m;

for(i=0; i<n; i++){
    m=strlen(*list);
    int lap=0;
    for(j=0; j<(strlen(name)-1); j++){
        for(k=0; k<m; k++)
            if(list[i][k]==name[j]){
                lap+=1;
                break;
            }
    }

    if(over<lap){
        over=lap;
        fid=i;
    }

    *list++;
}

return fid;
}

int readfile(char *flist[], FILE *fptr){
char a[MAXF];
int size=0;

while(fscanf(fptr, "%s\n", a) != EOF){
    flist[size]=malloc(sizeof(char)*(1+strlen(a)));
    strcpy(flist[size++],a);
}

return size;
}

int main () {
int n, id;
char fnname[MAXF], filename[MAXF], *flist[MAXFILE];
FILE *fp;

printf("Name of network file: ");
gets(filename);
printf("\nFunction Name: ");
gets(fnname);

fp=fopen(filename, "r");

if(fp==NULL)
    printf("\nCould not open file.\n");
else {
    n=readfile(flist, fp);
    id=overlap(flist, fnname, n);
    recommend(id, flist);
}

return 0;
}
</code>```

答:
It looks to me as if this:

```<code> m=strlen(*list);
</code>```

should be:

```<code> m=strlen(list[i]);
</code>```

And this:

```<code>*list++;
</code>```

should not be there at all.

Title: Ragged Arrays and For Loop errors

Body:
I get a bad access error in the middle of the for loop, always when i=4. Does anybody know the reason for this? It works until i=4, but I don't see why I wouldn't get the bad access error in any other part of the for loop.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>

    #define MAXF 51
    #define MAXFILE 200

int recommend(int fid, char *funcs[]){
int i;

for(i=0; i<fid; i++)
    *funcs++;
printf("\nRecommended Function: %s\n", *funcs);

return 0;
}

int overlap(char *list[], char name[], int n){
int over=0, fid=202, i, j, k, m;

for(i=0; i<n; i++){
    m=strlen(*list);
    int lap=0;
    for(j=0; j<(strlen(name)-1); j++){
        for(k=0; k<m; k++)
            if(list[i][k]==name[j]){
                lap+=1;
                break;
            }
    }

    if(over<lap){
        over=lap;
        fid=i;
    }

    *list++;
}

return fid;
}

int readfile(char *flist[], FILE *fptr){
char a[MAXF];
int size=0;

while(fscanf(fptr, "%s\n", a) != EOF){
    flist[size]=malloc(sizeof(char)*(1+strlen(a)));
    strcpy(flist[size++],a);
}

return size;
}

int main () {
int n, id;
char fnname[MAXF], filename[MAXF], *flist[MAXFILE];
FILE *fp;

printf("Name of network file: ");
gets(filename);
printf("\nFunction Name: ");
gets(fnname);

fp=fopen(filename, "r");

if(fp==NULL)
    printf("\nCould not open file.\n");
else {
    n=readfile(flist, fp);
    id=overlap(flist, fnname, n);
    recommend(id, flist);
}

return 0;
}

Body:
It looks to me as if this:

 m=strlen(*list);

should be:

 m=strlen(list[i]);

And this:

*list++;

should not be there at all.


问:
Django - how to handle time duration
I am trying to display the elapsed time during a race.

```<code>class results(models.Model):
    race_id = models.ForeignKey(Race, on_delete=models.CASCADE)
    runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE)
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    obs = models.TextField(blank=True)
    def __str__(self):
        return self.race_id.race_cod+" - "+self.runner_id.name
    class Meta:
        verbose_name_plural = "Results"
</code>```

Looking here I have found the following guides:

Django model elapsed time between two DateTimeFields

Django: What's the best field type to represent time elapsed?

Unfortunately, the solution presented there seems a little bit complex.

I also have found this workaround in the .html view page

```<code><div class="info-box-content">
  <span class="info-box-number">Time - {{ results.race_finish|timesince:results.race_start }}</span>
</div>
</code>```

the issue with this one is that everything over 24 hours came as x days, yy hours - while my need is to display the duration as HH:mm

Any hints here?

答:
For this I would suggest adding a custom template filter or a new model property. For example, if you want to add this into your model:

```<code>class results(models.Model):
    ...
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    @property
    def duration(self):
        if not (self.race_start and self.race_finish): return None
        a,b=self.race_start, self.race_finish
        return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60)
</code>```

Here's an example converting it to a class (outside django) to show how it would work with two race times separated by 1 day, 2 hours, 17 minutes:

```<code>import datetime
class results:
    def __init__(self):
        self.race_start = datetime.datetime.now()
        self.race_finish = datetime.datetime.now() + datetime.timedelta(days=1, hours=2, minutes=17)
    @property
    def duration(self):
        if not (self.race_start and self.race_finish): return None
        a,b=self.race_start, self.race_finish
        return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60)

>>> r=results()
>>> r.duration
'26:17'
</code>```

In other words, in your template, you can just have Time - {{ results.duration }} and it should show: "Time - 26:17".

Title: Django - how to handle time duration

Body:
I am trying to display the elapsed time during a race.

class results(models.Model):
    race_id = models.ForeignKey(Race, on_delete=models.CASCADE)
    runner_id = models.ForeignKey(Runner, on_delete=models.CASCADE)
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    obs = models.TextField(blank=True)
    def __str__(self):
        return self.race_id.race_cod+" - "+self.runner_id.name
    class Meta:
        verbose_name_plural = "Results"

Looking here I have found the following guides:

Django model elapsed time between two DateTimeFields

Django: What's the best field type to represent time elapsed?

Unfortunately, the solution presented there seems a little bit complex.

I also have found this workaround in the .html view page

  Time - {{ results.race_finish|timesince:results.race_start }}

the issue with this one is that everything over 24 hours came as x days, yy hours - while my need is to display the duration as HH:mm

Any hints here?

Body:
For this I would suggest adding a custom template filter or a new model property. For example, if you want to add this into your model:

class results(models.Model):
    ...
    race_start = models.DateTimeField()
    race_finish = models.DateTimeField(blank=True, null=True)
    @property
    def duration(self):
        if not (self.race_start and self.race_finish): return None
        a,b=self.race_start, self.race_finish
        return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60)

Here's an example converting it to a class (outside django) to show how it would work with two race times separated by 1 day, 2 hours, 17 minutes:

import datetime
class results:
    def __init__(self):
        self.race_start = datetime.datetime.now()
        self.race_finish = datetime.datetime.now() + datetime.timedelta(days=1, hours=2, minutes=17)
    @property
    def duration(self):
        if not (self.race_start and self.race_finish): return None
        a,b=self.race_start, self.race_finish
        return '%s:%s' % ((b-a).days*24 + (b-a).seconds//3600, (b-a).seconds%3600//60)

>>> r=results()
>>> r.duration
'26:17'

In other words, in your template, you can just have Time - {{ results.duration }} and it should show: "Time - 26:17".


问:
How to get m4a file from recorded audio for API in Swift?
Goal: I want to record audio for 10 seconds, get the audio recording file and send it in a post request.

What I have done: I am able to record audio for 10 seconds using this code:

```<code>var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!

func setupAV() {
    recordingSession = AVAudioSession.sharedInstance()

    do {
        try recordingSession.setCategory(.playAndRecord, mode: .default)
        try recordingSession.setActive(true)
        recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.recordTapped)))
                } else {
                    // failed to record!
                }
            }
        }
    } catch {
        // failed to record!
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

@objc func recordTapped() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record(forDuration: 10)
        print("RECORDING")
    } catch {
        print("audio failed to record")
    }

}

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("DONE")
}
</code>```

What I need to do: I need to get this audio recording as an m4a file and send it in a post request. How can I do this? Please let me know if you need any other information! Thank you!

答:
You need to export the recording using AVAssetExportSession. Here is a nice method that will do it for you:

```<code>func export(fileType: AVFileType = .m4a, completion: @escaping (() -> Void)) {
    let asset = AVAsset(url: recordingFileURL))
    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { return }
    exportSession.outputFileType = fileType
    exportSession.metadata = asset.metadata
    exportSession.shouldOptimizeForNetworkUse = true
    exportSession.outputURL = exportOutputURL
    exportSession.exportAsynchronously {
        print("Export finished.")
        completion()
    }
}
</code>```

Where exportOutputURL can be any URL that you create in the documents directory. For example, we can define it as a computed property:

```<code>var exportOutputURL: URL? {
    let pathURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    return pathURL?.appendingPathComponent("my_exported_recording")
}
</code>```

You will now have the exported m4a file in your exportOutputURL.

Depending on what your API expects the parameter to be, you can convert into data like so:

```<code>do {
    let data = try Data(contentsOf: exportOutputURL)
} catch { ... }
</code>```

And to a base64 string:

```<code>let base64String = data.base64EncodedString()
</code>```

Body:
Goal: I want to record audio for 10 seconds, get the audio recording file and send it in a post request.

What I have done: I am able to record audio for 10 seconds using this code:

var recordingSession: AVAudioSession!
var audioRecorder: AVAudioRecorder!

func setupAV() {
    recordingSession = AVAudioSession.sharedInstance()

    do {
        try recordingSession.setCategory(.playAndRecord, mode: .default)
        try recordingSession.setActive(true)
        recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    self.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.recordTapped)))
                } else {
                    // failed to record!
                }
            }
        }
    } catch {
        // failed to record!
    }
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

@objc func recordTapped() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.m4a")

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000,
        AVNumberOfChannelsKey: 1,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]

    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
        audioRecorder.record(forDuration: 10)
        print("RECORDING")
    } catch {
        print("audio failed to record")
    }

}

func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
    print("DONE")
}

What I need to do: I need to get this audio recording as an m4a file and send it in a post request. How can I do this? Please let me know if you need any other information! Thank you!

Body:
You need to export the recording using AVAssetExportSession. Here is a nice method that will do it for you:

func export(fileType: AVFileType = .m4a, completion: @escaping (() -> Void)) {
    let asset = AVAsset(url: recordingFileURL))
    guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetAppleM4A) else { return }
    exportSession.outputFileType = fileType
    exportSession.metadata = asset.metadata
    exportSession.shouldOptimizeForNetworkUse = true
    exportSession.outputURL = exportOutputURL
    exportSession.exportAsynchronously {
        print("Export finished.")
        completion()
    }
}

Where exportOutputURL can be any URL that you create in the documents directory. For example, we can define it as a computed property:

var exportOutputURL: URL? {
    let pathURL = try? FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
    return pathURL?.appendingPathComponent("my_exported_recording")
}

You will now have the exported m4a file in your exportOutputURL.

Depending on what your API expects the parameter to be, you can convert into data like so:

do {
    let data = try Data(contentsOf: exportOutputURL)
} catch { ... }

And to a base64 string:

let base64String = data.base64EncodedString()


问:
Unique value in the list
now I'm creating a minesweeper-alike game in pygame. I'm trying to make bomb numering creator, but unfortunately i'm having list index out of range error. My idea is to generate all 1 numbers, and then when coordinates are the same for i place in the list, change picture to 2 etc.

import sys, os
import pygame
import random
import time

from pygame import mixer

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

W, H = 400, 400

pygame.init()
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("mine")

emp_place_img = pygame.image.load('emp.png').convert_alpha()
emp_place_mask = pygame.mask.from_surface(emp_place_img)
bomb_img = pygame.image.load('bomb.png').convert_alpha()
bomb_mask = pygame.mask.from_surface(bomb_img)
mark1_img = pygame.image.load('mark1.png').convert_alpha()
mark2_img = pygame.image.load('mark2.png').convert_alpha()
mark3_img = pygame.image.load('mark3.png').convert_alpha()

kursor = pygame.image.load('coursor.png').convert_alpha()

kursor_mask = pygame.mask.from_surface(kursor)

emp_place_x = []
emp_place_y = []
emp_place_image = []
emp_place_masking = []

placex = 0
placey=0

bomb_image = []
bomb_masking = []
bomb_x = []
bomb_y = []

mark_image = []
mark_masking = []
mark_x = []
mark_y = []
mark_x_pos = [-25,-25,-25,0,0,0,25,25,25]
mark_y_pos = [-25,0,25,-25,0,25,-25,0,25]
mark_blit_number =0

boom = False
CLOCK = pygame.time.Clock()
def emp_place_blit(x, y, i):
    screen.blit(emp_place_image[i], (x, y))
def bomb_blit(x,y,i):
    screen.blit(bomb_image[i],(x,y))
def mark_blit(x,y,i):
    screen.blit(mark_image[i],(x,y))
def main():
    global boom, emp_place_image, emp_place_img, emp_place_x, emp_place_y, placex, placey,mark_blit_number
    running = True
    while running:
        pygame.mouse.set_visible(True)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        playerx1, playery1 = pygame.mouse.get_pos()

        for i in range(256):
            emp_place_image.append(emp_place_img)
            emp_place_masking.append(pygame.mask.from_surface(emp_place_image[i]))
            emp_place_x.append(placex*25)
            emp_place_y.append(placey)

            placex+=1
            if placex==16:
                placex=0
                placey+=25

        for i in range(256):
            distance = (playerx1 - int(emp_place_x[i])), ((playery1 - int(emp_place_y[i])))
            result = emp_place_masking[i].overlap(kursor_mask, distance)
            if result and pygame.mouse.get_pressed()[0]:
                emp_place_image[i] = pygame.image.load("fill.png")
                if boom == True:
                    sys.exit()
        for i in range(20):
            bomb_image.append(bomb_img)
            randomposx = (random.choice(emp_place_x))
            bomb_x.append(randomposx)
            randomposy = (random.choice(emp_place_y))
            bomb_y.append(randomposy)
            for x in range(9):
                mark_x.append(randomposx+mark_x_pos[x])
                mark_y.append(randomposy+mark_y_pos[x])
                mark_x_add = mark_x
                mark_y_add = mark_y
                mark_x_add_value = mark_x[i]
                mark_y_add_value = mark_y[i]
                mark_x_add.remove(mark_x[i])
                mark_y_add.remove(mark_y[i])
                if mark_x_add_value in mark_x_add and mark_y_add_value in mark_y_add:
                    mark_image.append(mark2_img)
                else:
                    mark_image.append(mark1_img)

        for i in range(20):
            distancebomb1, distancebomb2 = (playerx1 - int(bomb_x[i])), ((playery1 - int(bomb_y[i])))
            if 0<distancebomb1<25 and 0<distancebomb2<25 and pygame.mouse.get_pressed()[0]:
                boom = ""
        for i in range(256):
            emp_place_blit(emp_place_x[i], emp_place_y[i], i)
        for i in range(180):
            mark_blit(mark_x[i], mark_y[i], i)

        for i in range(20):
            bomb_blit(bomb_x[i], bomb_y[i], i)

        screen.blit(kursor,(playerx1, playery1))
        pygame.display.flip()
        pygame.display.update()
        CLOCK.tick(60)

main()
```

I'm aware this is probably not the best way to do this minigame, but I want to know what is going wrong and how to repair it
Basicly this is how the game work(in the final game there just will be a layer above it)

答:
mark_x_add = mark_x does not create a copy of the list mark. To create a shallow copy of a list you can use do mark_x_add = mark_x[:]. See Shallow and deep copy operations.

Further more, the control variable in the inner loop is x rather than i:

mark_x_add = mark_x[:]
mark_y_add = mark_y[:]
mark_x_add_value = mark_x[x]
mark_y_add_value = mark_y[x]
mark_x_add.remove(mark_x[x])
mark_y_add.remove(mark_y[x])
```

<hr>

<p>Anyway, you overcomplicate things. The random positions for the bombs have to be computed before the main application loop. So the positions for the marks can be computed before the loop, too. Use a dictionary to store the positions of the bombs and marks. e.g:</p>

<pre class="lang-py prettyprint-override"><code>grid_size = (16, 16)
field_size = (25, 25)
number_of_bombs = 20
bombs = {}
markpos = [(x, y) for x in range(-1, 2) for y in range(-1, 2) if x != 0 or y !=0]
marks = {}

def main():
    global bombs, marks

    # create random bombs
    while len(bombs) < number_of_bombs:
        bx, by = random.randint(0, grid_size[0]-1), random.randint(0, grid_size[1]-1)
        if (bx, by) not in bombs:
            bombs[(bx, by)] = bomb_img

    # find marks
    for pos in bombs:
        mposlist = [(p[0]+pos[0], p[1]+pos[1]) for p in markpos
                    if 0 <= p[0]+pos[0] < grid_size[0] and
                       0 <= p[1]+pos[1] < grid_size[1] and
                       (p[0]+pos[0], p[1]+pos[1]) not in bombs]
        for mpos in mposlist:
            marks[mpos] = marks[mpos]+1 if mpos in marks else 1

    running = True
    while running:
        pygame.mouse.set_visible(True)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        playerx1, playery1 = pygame.mouse.get_pos()

        for x in range(grid_size[0]):
            for y in range(grid_size[1]):
                screen.blit(emp_place_img, (x*field_size[0], y*field_size[1]))

        for pos, img in bombs.items():
            screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))

        for pos, count in marks.items():
            img = [mark1_img, mark2_img, mark3_img][min(count-1, 2)]
            screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))

        screen.blit(kursor,(playerx1, playery1))
        pygame.display.flip()
        pygame.display.update()
        CLOCK.tick(60)
</code>```

how can i add more marks for 4, 5 etc bombs?

You have to change the line:

img = [mark1_img, mark2_img, mark3_img][min(count-1, 2)]
```

<p>Create a list of mark images somewhere at the initialization part. e.g:</p>

<pre class="lang-py prettyprint-override"><code>mark_list = [mark1_img, mark2_img, mark3_img, mark4_img, mar5_img]
</code>```

and select the proper image. e.g:

for pos, count in marks.items():
    img = mark_list[min(count-1, len(mark_list)-1)]
    screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))
```

Title: Unique value in the list

Body:
now I'm creating a minesweeper-alike game in pygame. I'm trying to make bomb numering creator, but unfortunately i'm having list index out of range error. My idea is to generate all 1 numbers, and then when coordinates are the same for i place in the list, change picture to 2 etc.

import sys, os
import pygame
import random
import time

from pygame import mixer

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

W, H = 400, 400

pygame.init()
screen = pygame.display.set_mode((W, H))
pygame.display.set_caption("mine")

emp_place_img = pygame.image.load('emp.png').convert_alpha()
emp_place_mask = pygame.mask.from_surface(emp_place_img)
bomb_img = pygame.image.load('bomb.png').convert_alpha()
bomb_mask = pygame.mask.from_surface(bomb_img)
mark1_img = pygame.image.load('mark1.png').convert_alpha()
mark2_img = pygame.image.load('mark2.png').convert_alpha()
mark3_img = pygame.image.load('mark3.png').convert_alpha()

kursor = pygame.image.load('coursor.png').convert_alpha()

kursor_mask = pygame.mask.from_surface(kursor)

emp_place_x = []
emp_place_y = []
emp_place_image = []
emp_place_masking = []

placex = 0
placey=0

bomb_image = []
bomb_masking = []
bomb_x = []
bomb_y = []

mark_image = []
mark_masking = []
mark_x = []
mark_y = []
mark_x_pos = [-25,-25,-25,0,0,0,25,25,25]
mark_y_pos = [-25,0,25,-25,0,25,-25,0,25]
mark_blit_number =0

boom = False
CLOCK = pygame.time.Clock()
def emp_place_blit(x, y, i):
    screen.blit(emp_place_image[i], (x, y))
def bomb_blit(x,y,i):
    screen.blit(bomb_image[i],(x,y))
def mark_blit(x,y,i):
    screen.blit(mark_image[i],(x,y))
def main():
    global boom, emp_place_image, emp_place_img, emp_place_x, emp_place_y, placex, placey,mark_blit_number
    running = True
    while running:
        pygame.mouse.set_visible(True)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        playerx1, playery1 = pygame.mouse.get_pos()

        for i in range(256):
            emp_place_image.append(emp_place_img)
            emp_place_masking.append(pygame.mask.from_surface(emp_place_image[i]))
            emp_place_x.append(placex*25)
            emp_place_y.append(placey)

            placex+=1
            if placex==16:
                placex=0
                placey+=25

        for i in range(256):
            distance = (playerx1 - int(emp_place_x[i])), ((playery1 - int(emp_place_y[i])))
            result = emp_place_masking[i].overlap(kursor_mask, distance)
            if result and pygame.mouse.get_pressed()[0]:
                emp_place_image[i] = pygame.image.load("fill.png")
                if boom == True:
                    sys.exit()
        for i in range(20):
            bomb_image.append(bomb_img)
            randomposx = (random.choice(emp_place_x))
            bomb_x.append(randomposx)
            randomposy = (random.choice(emp_place_y))
            bomb_y.append(randomposy)
            for x in range(9):
                mark_x.append(randomposx+mark_x_pos[x])
                mark_y.append(randomposy+mark_y_pos[x])
                mark_x_add = mark_x
                mark_y_add = mark_y
                mark_x_add_value = mark_x[i]
                mark_y_add_value = mark_y[i]
                mark_x_add.remove(mark_x[i])
                mark_y_add.remove(mark_y[i])
                if mark_x_add_value in mark_x_add and mark_y_add_value in mark_y_add:
                    mark_image.append(mark2_img)
                else:
                    mark_image.append(mark1_img)

        for i in range(20):
            distancebomb1, distancebomb2 = (playerx1 - int(bomb_x[i])), ((playery1 - int(bomb_y[i])))
            if 0<distancebomb1<25 and 0<distancebomb2<25 and pygame.mouse.get_pressed()[0]:
                boom = ""
        for i in range(256):
            emp_place_blit(emp_place_x[i], emp_place_y[i], i)
        for i in range(180):
            mark_blit(mark_x[i], mark_y[i], i)

        for i in range(20):
            bomb_blit(bomb_x[i], bomb_y[i], i)

        screen.blit(kursor,(playerx1, playery1))
        pygame.display.flip()
        pygame.display.update()
        CLOCK.tick(60)

main()

I'm aware this is probably not the best way to do this minigame, but I want to know what is going wrong and how to repair it
Basicly this is how the game work(in the final game there just will be a layer above it)

Body:
mark_x_add = mark_x does not create a copy of the list mark. To create a shallow copy of a list you can use do mark_x_add = mark_x[:]. See Shallow and deep copy operations.

Further more, the control variable in the inner loop is x rather than i:

mark_x_add = mark_x[:]
mark_y_add = mark_y[:]
mark_x_add_value = mark_x[x]
mark_y_add_value = mark_y[x]
mark_x_add.remove(mark_x[x])
mark_y_add.remove(mark_y[x])

Anyway, you overcomplicate things. The random positions for the bombs have to be computed before the main application loop. So the positions for the marks can be computed before the loop, too. Use a dictionary to store the positions of the bombs and marks. e.g:

grid_size = (16, 16)
field_size = (25, 25)
number_of_bombs = 20
bombs = {}
markpos = [(x, y) for x in range(-1, 2) for y in range(-1, 2) if x != 0 or y !=0]
marks = {}

def main():
    global bombs, marks

    # create random bombs
    while len(bombs) < number_of_bombs:
        bx, by = random.randint(0, grid_size[0]-1), random.randint(0, grid_size[1]-1)
        if (bx, by) not in bombs:
            bombs[(bx, by)] = bomb_img

    # find marks
    for pos in bombs:
        mposlist = [(p[0]+pos[0], p[1]+pos[1]) for p in markpos
                    if 0 <= p[0]+pos[0] < grid_size[0] and
                       0 <= p[1]+pos[1] < grid_size[1] and
                       (p[0]+pos[0], p[1]+pos[1]) not in bombs]
        for mpos in mposlist:
            marks[mpos] = marks[mpos]+1 if mpos in marks else 1

    running = True
    while running:
        pygame.mouse.set_visible(True)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
        playerx1, playery1 = pygame.mouse.get_pos()

        for x in range(grid_size[0]):
            for y in range(grid_size[1]):
                screen.blit(emp_place_img, (x*field_size[0], y*field_size[1]))

        for pos, img in bombs.items():
            screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))

        for pos, count in marks.items():
            img = [mark1_img, mark2_img, mark3_img][min(count-1, 2)]
            screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))

        screen.blit(kursor,(playerx1, playery1))
        pygame.display.flip()
        pygame.display.update()
        CLOCK.tick(60)

how can i add more marks for 4, 5 etc bombs?

You have to change the line:

img = [mark1_img, mark2_img, mark3_img][min(count-1, 2)]

Create a list of mark images somewhere at the initialization part. e.g:

mark_list = [mark1_img, mark2_img, mark3_img, mark4_img, mar5_img]

and select the proper image. e.g:

for pos, count in marks.items():
    img = mark_list[min(count-1, len(mark_list)-1)]
    screen.blit(img, (pos[0]*field_size[0], pos[1]*field_size[1]))


问:
Ambiguity between Haskell Num class and my show-like class
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

```<code>data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3
</code>```

But GHC (7.0.3) becomes angry and says:

```<code>Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)
</code>```

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.

答:
problem: the type of 3 is Num a => a, but ghc needs a concrete type in order to search for an instance of Some
(possibly, there could exist more than one instance of Some which is in Num -- so which one to choose?)

Body:
I'm trying to declare my own data with appropriate conversion as class. My code looks like this:

data SomeData =  SInteger Integer | SElse deriving Show

class Some a where
    toSome :: a -> SomeData

instance Some Int where toSome = SInteger . toInteger

main :: IO ()
main = print $ toSome 3

But GHC (7.0.3) becomes angry and says:

Ambiguous type variable `a0' in the constraints:
      (Some a0) arising from a use of `toSome'
                at minimal_broken.hs:11:16-21
      (Num a0) arising from the literal `3' at minimal_broken.hs:11:23
    Probable fix: add a type signature that fixes these type variable(s)

Explicit type signature (like 3::Int) fixes the issue, but it's very inconvenient.

Standard "Show" works just fine, and according to the manual it's declared exactly the same way.

Why standard Show works, but my class doesn't? Did I miss something?

P.S.: Explicit "default (Int)" does not resolve this.


问:
What online tool do you use to automate translation of .arb files?
Do you know any good tools to support the translation of .arb files?

It's a standard for Flutter and since Google Translator Toolkit will be sunset soon (https://support.google.com/translatortoolkit/answer/9462068) we're searching for a good solution to translate/gather our translations

答:
Edit (June 2020): There's great new open source project called Arbify. This is a self-hosted tool to manage multiple translation projects focused on Flutter. You can edit arb files and fetch them via Dart package tool.

Aside from that some services like POEditor have announced basic support for ARB too.

At the moment the best support for arb files is on Localizely. However, this is a paid service and has strict limits on a free version. It allows to export arb translation files with plurals and placeholder support. It doesn't support genders, though.

There is also one simple web editor and one desktop editor (Babel) that support arb files.


问:
How can I increase the failure timeout of an apple Pay operation?
In the current implementation, my payment takes a long time in some cases. Often users have an error like "Apple pay not completed". The question says that in iOS 11 this happens after 15-20 seconds, can I increase this time, if so, how ? If the payment has time to process during this time, the payment in apple pay is successful.

答:
While changing the failure timeout is impossible, there is still a workaround to avoid the "Apple pay not completed" message for cases when, for example, your API call processing the payment has extended timeout. (At the moment of writing this answer, on iOS 13, the ApplePay dialog would timeout itself in around 30 secs).

The trick is to set a one-time timer, which would dismiss the ApplePay dialog just before it decides to give up. Of course your app must always give user proper feedback when the purchase process ends (was it success or failure), 'cause ApplePay dialog won't be able to show anything after you dismiss it.

Example timer:

```<code>_ = Timer.scheduledTimer(withTimeInterval: 25, repeats: false) { _ in
    guard self.applePayBeingProcessed == true else { return }
    if let applePayVC = AppUtil.shared.topMostController() as? PKPaymentAuthorizationViewController {
        self.applePayHasTimeouted = true
        applePayVC.dismiss(animated: true)
    }
}
</code>```

*applePayBeingProcessed is set to true in paymentAuthorizationViewController(_:didAuthorizePayment:handler:) and set back to false right after calling handler(PKPaymentAuthorizationResult(status: paymentStatus, errors: [error])) - so that the routine called by timer would be skipped when ApplePay dismissed in a normal way via paymentAuthorizationViewControllerDidFinish(_:)

** applePayHasTimeouted is later checked inside a completion of your payment processing API call, if true it means we need to perform actions, that are normally supposed to be performed inside paymentAuthorizationViewControllerDidFinish(_:) (because the latter will never be called after manually closing ApplePay dialog)

*** topMostController() method finds the controller from the top of hierarchy. How to do this is out of scope of current question, there lots of ways to do this, my favorite one is in this answer.

Body:
While changing the failure timeout is impossible, there is still a workaround to avoid the "Apple pay not completed" message for cases when, for example, your API call processing the payment has extended timeout. (At the moment of writing this answer, on iOS 13, the ApplePay dialog would timeout itself in around 30 secs).

The trick is to set a one-time timer, which would dismiss the ApplePay dialog just before it decides to give up. Of course your app must always give user proper feedback when the purchase process ends (was it success or failure), 'cause ApplePay dialog won't be able to show anything after you dismiss it.

Example timer:

_ = Timer.scheduledTimer(withTimeInterval: 25, repeats: false) { _ in
    guard self.applePayBeingProcessed == true else { return }
    if let applePayVC = AppUtil.shared.topMostController() as? PKPaymentAuthorizationViewController {
        self.applePayHasTimeouted = true
        applePayVC.dismiss(animated: true)
    }
}

*applePayBeingProcessed is set to true in paymentAuthorizationViewController(_:didAuthorizePayment:handler:) and set back to false right after calling handler(PKPaymentAuthorizationResult(status: paymentStatus, errors: [error])) - so that the routine called by timer would be skipped when ApplePay dismissed in a normal way via paymentAuthorizationViewControllerDidFinish(_:)

** applePayHasTimeouted is later checked inside a completion of your payment processing API call, if true it means we need to perform actions, that are normally supposed to be performed inside paymentAuthorizationViewControllerDidFinish(_:) (because the latter will never be called after manually closing ApplePay dialog)

*** topMostController() method finds the controller from the top of hierarchy. How to do this is out of scope of current question, there lots of ways to do this, my favorite one is in this answer.