问:
Mistakes in my mips code to return multiples of X where X is 1, 2,4, 8, 16 and such
```<code># arrayCount.asm
  .data
arrayA: .word 11, 3, 4, 5, 6, 7
count:  .word 6

  .text
main:
    # code to setup the variable mappings
    la $t0, arrayA
    la $t1, count

    # code for reading in the user value X
    li $v0, 5
    move $t3, $v0
    syscall

    # code for counting multiples of X in arrayA
    addi $t4, $zero, 0 #number
start:
    beq $t1, $zero, exit

    lw $t6, 0($t0)
    and $t5, $t3, $t6
    addi, $t1, $t1, -1
    la $t0, 4($t0)
    beq $t5, $zero, update
    j start

update:
    addi $t4, $t4, 1
    j start

    # code for printing result
exit:
    li $v0, 1
    la $a0, number
    syscall

    # code for terminating program
    li  $v0, 10
    syscall
</code>```

I keep getting an exception error what is wrong with my code? Thanks!

答:
There are quite few errors

You use la $t1, count which load the address of the count, but not
the value of it (6).

You try to save the return of the user input reading before it is even happened.

On exit you try to load number symbol, but that is not exists.

Also your algorithm does not make that much sense, but you are not too clear about what your goal so I can not fix it.

The code with the fixes:

```<code># arrayCount.asm
  .data
arrayA: .word 11, 3, 4, 5, 6, 7
count:  .word 6

  .text
main:
    # code to setup the variable mappings
    la $t0, arrayA
    lw $t1, count    # fix #1

    # code for reading in the user value X
    li $v0, 5
    syscall    # fix #2
    move $t3, $v0

    # code for counting multiples of X in arrayA
    addi $t4, $zero, 0 #number
start:
    beq $t1, $zero, exit

    lw $t6, 0($t0)
    and $t5, $t3, $t6
    addi, $t1, $t1, -1
    la $t0, 4($t0)
    beq $t5, $zero, update
    j start

update:
    addi $t4, $t4, 1
    j start

    # code for printing result
exit:
    li $v0, 1
    move $a0, $t4    # fix #3
    syscall

    # code for terminating program
    li  $v0, 10
    syscall

</code>```

Body:
# arrayCount.asm
  .data
arrayA: .word 11, 3, 4, 5, 6, 7
count:  .word 6

  .text
main:
    # code to setup the variable mappings
    la $t0, arrayA
    la $t1, count

    # code for reading in the user value X
    li $v0, 5
    move $t3, $v0
    syscall

    # code for counting multiples of X in arrayA
    addi $t4, $zero, 0 #number
start:
    beq $t1, $zero, exit

    lw $t6, 0($t0)
    and $t5, $t3, $t6
    addi, $t1, $t1, -1
    la $t0, 4($t0)
    beq $t5, $zero, update
    j start

update:
    addi $t4, $t4, 1
    j start

    # code for printing result
exit:
    li $v0, 1
    la $a0, number
    syscall

    # code for terminating program
    li  $v0, 10
    syscall

I keep getting an exception error what is wrong with my code? Thanks!

Body:
There are quite few errors

You use la $t1, count which load the address of the count, but not
the value of it (6).

You try to save the return of the user input reading before it is even happened.

On exit you try to load number symbol, but that is not exists.

Also your algorithm does not make that much sense, but you are not too clear about what your goal so I can not fix it.

The code with the fixes:

# arrayCount.asm
  .data
arrayA: .word 11, 3, 4, 5, 6, 7
count:  .word 6

  .text
main:
    # code to setup the variable mappings
    la $t0, arrayA
    lw $t1, count    # fix #1

    # code for reading in the user value X
    li $v0, 5
    syscall    # fix #2
    move $t3, $v0

    # code for counting multiples of X in arrayA
    addi $t4, $zero, 0 #number
start:
    beq $t1, $zero, exit

    lw $t6, 0($t0)
    and $t5, $t3, $t6
    addi, $t1, $t1, -1
    la $t0, 4($t0)
    beq $t5, $zero, update
    j start

update:
    addi $t4, $t4, 1
    j start

    # code for printing result
exit:
    li $v0, 1
    move $a0, $t4    # fix #3
    syscall

    # code for terminating program
    li  $v0, 10
    syscall


来源: stackexchange

问:
How to get an entity's key when using django-nonrel on App Engine
I'm using django-nonrel (http://www.allbuttonspressed.com/projects/djangoappengine) on Google App Engine. I have my models etc. setup and everything works great. I had one question though. I want to be able to access an entity's key. Given a model named 'Review', I do Review.objects.get(pk = 1).key() which throws an error (AttributeError).

Is there any way I can get the given entity's key so that I can use it instead of being forced to use the pk/id? I want to use the key as a unique identifier for unique & secret URLS (if someone has a better suggestion to achieve this, I'm all ears).

答: You can get id by calling object.key().id() which returns a unique key inside python .In templates you can simply call object.key.id . Then you can use get_by_id to get the object </p>

ContentLicense: CC BY-SA 3.0


问:
Sheets IF Function setup and/or formatting errors
Cell C5 on the Trip Assignment Form tab is a dropdown selection list of destinations.  I am trying to make sheets automatically fill in the C6 cell with the matching address (coming from a tab called Schools).  When I put the below formula in I get an error or FALSE but I cannot figure out why.

=if(C5=Schools!A1, C6=Schools!B1, "Other Error")

I need to make the formula work for any destination selected so that the appropriate address is inserted into the cell.  Can I do this like the way I am thinking or would Apps Script be better and if so how would I go about that?

"Trip Assignment Form"

"Schools" data sheet

Link to copy of my sheet:

https://docs.google.com/spreadsheets/d/1Xkwxjtf6syEd-zGaPUVsyE2_6Kfczu8c-8W3RuRg9CY/edit?usp=sharing

答:
```<code>=VLOOKUP(C5, Schools!A:B, 2, 0)
</code>```

Lookup C5 in Schools A:B and retrieve the second column

ContentLicense: CC BY-SA 4.0

Body:
=VLOOKUP(C5, Schools!A:B, 2, 0)

Lookup C5 in Schools A:B and retrieve the second column


问:
What is the equivalent of document.getElementById("root").appendChild(node) in React?
How do I get this functionality using React?

function myFunction() {
  var node = document.createElement("div");
  var textnode = document.createTextNode("Button was clicked.");
  node.appendChild(textnode);
  document.getElementById("root").appendChild(node);
}```

答:
in your render function write the div you want and make a state
then change a state to true to the div to be shown

somthing like this

```<code>   constructor(props) {
        super(props)
        this.state = {
            showDiv: false
        }
    }
   render (){
       return (
            {
                this.state.showDiv ? your div : <React.Fragment />
            }
       )
   }

   changeDivDisplay(){
      this.setState({showDiv:true})
   }

</code>```

also i do recommend you to read about the state and the refs of react

Body:
in your render function write the div you want and make a state
then change a state to true to the div to be shown

somthing like this

   constructor(props) {
        super(props)
        this.state = {
            showDiv: false
        }
    }
   render (){
       return (
            {
                this.state.showDiv ? your div : <React.Fragment />
            }
       )
   }

   changeDivDisplay(){
      this.setState({showDiv:true})
   }

also i do recommend you to read about the state and the refs of react


问:
C# - Constant value '4294901760' cannot be converted to a 'int'
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

```<code>// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;
</code>```

If I put an (int) cast around it like so, I get another error:

```<code>// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;
</code>```

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

答:
```<code>public const uint RED = 0xffff0000;
</code>```

Body:
Greetings,

I can't believe I'm asking such a basic question, but it doesn't make sense so here it is :).

In C# on Windows Phone 7 / .net, I'm trying to define a constant in a class as follows:

// error CS0266: Cannot implicitly convert type 'uint' to 'int'.
// An explicit conversion exists (are you missing a cast?)
public const int RED = 0xffff0000;

If I put an (int) cast around it like so, I get another error:

// error CS0221: Constant value '4294901760' cannot be converted to a 'int'
// (use 'unchecked' syntax to override)
public const int RED = (int)0xffff0000;

But I know that my int is 32-bit, hence has a range of -2,147,483,648 to 2,147,483,647, see http://msdn.microsoft.com/en-us/library/5kzh1b5w(v=vs.80).aspx

So what gives?

Thanks in advance!

swine

Body: public const uint RED = 0xffff0000;


问:
Add new key to json array using jq
Why is the accepted answer in "Append new keypair to JSON file with jq" not working in my case?

I have a file newFile.json which contains:

```<code>[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 } ]
</code>```

I want to insert another value to the array in ruleGroup.json which has:

```<code>{ "groupId": "0", "target": { "alarm_id": "69" }, "upperThreshold":
"20", "lowerThreshold": "10", "thresholdPeriod": "5" }
</code>```

As per the accepted answer, I saved ruleGroup.json to obj.

When I run

```<code>jq --argjson obj '$obj' '. + [$obj]' < newFile.json
</code>```

it returns:

```<code>[ "{\n \"groupId\": \"0\",\n \"target\": {\n \"alarm_id\": \"69\"\n
},\n \"upperThreshold\": \"20\",\n \"lowerThreshold\": \"10\",\n
\"thresholdPeriod\": \"5\"\n}" ]
</code>```

Which is similar to the $obj value itself. It didn't create the expected result which was to append this value to the array:

```<code>[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": "0",
"target": { "alarm_id": "69" }, "upperThreshold": "20",
"lowerThreshold": "10", "thresholdPeriod": "5" } ]
</code>```

答:
If the object you want to add is in a file, you should be using --slurpfile instead of trying to read it into a shell variable and then pass that to jq:

```<code>$ jq --slurpfile obj ruleGroup.json '. + $obj' newFile.json
[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]
</code>```

Title: Add new key to json array using jq

Body:
Why is the accepted answer in "Append new keypair to JSON file with jq" not working in my case?

I have a file newFile.json which contains:

[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 } ]

I want to insert another value to the array in ruleGroup.json which has:

{ "groupId": "0", "target": { "alarm_id": "69" }, "upperThreshold":
"20", "lowerThreshold": "10", "thresholdPeriod": "5" }

As per the accepted answer, I saved ruleGroup.json to obj.

When I run

jq --argjson obj '$obj' '. + [$obj]' < newFile.json

it returns:

[ "{\n \"groupId\": \"0\",\n \"target\": {\n \"alarm_id\": \"69\"\n
},\n \"upperThreshold\": \"20\",\n \"lowerThreshold\": \"10\",\n
\"thresholdPeriod\": \"5\"\n}" ]

Which is similar to the $obj value itself. It didn't create the expected result which was to append this value to the array:

[ { "groupId": 11, "lowerThreshold": 33, "target": { "alarm_id": 22 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": 31,
"lowerThreshold": 33, "target": { "alarm_id": 122 },
"thresholdPeriod": 3, "upperThreshold": 44 }, { "groupId": "0",
"target": { "alarm_id": "69" }, "upperThreshold": "20",
"lowerThreshold": "10", "thresholdPeriod": "5" } ]

Body:
If the object you want to add is in a file, you should be using --slurpfile instead of trying to read it into a shell variable and then pass that to jq:

$ jq --slurpfile obj ruleGroup.json '. + $obj' newFile.json
[
  {
    "groupId": 11,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 22
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": 31,
    "lowerThreshold": 33,
    "target": {
      "alarm_id": 122
    },
    "thresholdPeriod": 3,
    "upperThreshold": 44
  },
  {
    "groupId": "0",
    "target": {
      "alarm_id": "69"
    },
    "upperThreshold": "20",
    "lowerThreshold": "10",
    "thresholdPeriod": "5"
  }
]


问:
Right way to fetch parent table with it's child tables
I have one to many relationship on parent and child tables. And trying to fetch parent table with it's child tables as json.

I tried something like below.

```<code>if (request.method == "GET"):

    parents = Parent.objects.all()
    datas = []
    childTables = []
    for parent in parents:

        #fetching parent first and creating DICT for json
        #also creating an array for the child tables

        parentDict = {
            "id": parent.id,
            "project_name": parent.project_name,
            childTables: childTables,
        }

        #then fetching child tables NO problem at this part as well.
        childs = parent.child_set.filter(parent_id=parent)
        for child in childs:
            #creating a DICT FOR THE json.
            childDict = {
                "id":child.id,
                "ad_kind":child.ad_kind,
                "parent_id":child.parent_id,
            }

            #i am trying to append project's childs into ParentDict
            #but still it's appending all childs into every ParentDict...
            #not just its parent's childs.
            parentDict["childTables"].append(childDict)

        #at last append all parent table inside an array and send it as JSON.
        datas.append(parentDict)

    return JsonResponse(datas, safe=False)
</code>```

the problem starts when I try to append child tables inside it's parent dict. But in above way, I just append all childs into every parent dict...

is there any other simpler way to achieve this?

答:
The problem lies at your childTables array. You should put it inside the parent loop and if you do that it will renew on each loop. Then you can get the expected results.

```<code>for parent in parents:

    #childTable array placed in here.
    #to renew on each loop.
    childTable = []

    parentDict = {
        "id": parent.id,
        "project_name": parent.project_name,
        childTables: childTables,
    }

    #... the rest is fine.
</code>```

Body:
I have one to many relationship on parent and child tables. And trying to fetch parent table with it's child tables as json.

I tried something like below.

if (request.method == "GET"):

    parents = Parent.objects.all()
    datas = []
    childTables = []
    for parent in parents:

        #fetching parent first and creating DICT for json
        #also creating an array for the child tables

        parentDict = {
            "id": parent.id,
            "project_name": parent.project_name,
            childTables: childTables,
        }

        #then fetching child tables NO problem at this part as well.
        childs = parent.child_set.filter(parent_id=parent)
        for child in childs:
            #creating a DICT FOR THE json.
            childDict = {
                "id":child.id,
                "ad_kind":child.ad_kind,
                "parent_id":child.parent_id,
            }

            #i am trying to append project's childs into ParentDict
            #but still it's appending all childs into every ParentDict...
            #not just its parent's childs.
            parentDict["childTables"].append(childDict)

        #at last append all parent table inside an array and send it as JSON.
        datas.append(parentDict)

    return JsonResponse(datas, safe=False)

the problem starts when I try to append child tables inside it's parent dict. But in above way, I just append all childs into every parent dict...

is there any other simpler way to achieve this?

Body:
The problem lies at your childTables array. You should put it inside the parent loop and if you do that it will renew on each loop. Then you can get the expected results.

for parent in parents:

    #childTable array placed in here.
    #to renew on each loop.
    childTable = []

    parentDict = {
        "id": parent.id,
        "project_name": parent.project_name,
        childTables: childTables,
    }

    #... the rest is fine.


问:
C++ including a ".h" file, function duplication confusion
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).

Basically, my program was structured as follows:

The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).

Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc).  CalledByCurrent.h contains a class definition.

There was a non-class function defined in CalledByCurrent.cc called thisFunction().  thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function).  In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc.  However, when I did this, I got an error saying that the function was duplicated.  Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?

Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc.  However, when I did this, I found that Current.cc did not know what function I was talking about.  What the heck?  I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem.  Could you help me understand this behavior?  Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?

p.s - I apologize for how confusing this post is.  Please let me know if there's anything I can clear up.

答:
There are 2 distinct errors coming from 2 different phases of the build.

In the first case where you have a duplicate, the COMPILER is happy, but the LINKER is complaining because when it picks up all the function definitions across the different source files it notices 2 are named the same. As the other answers state, you can use the static keyword or use a common definition.

In the second case where you see your function not declared in this scope, its because the COMPILER is complaining because each file needs to know about what functions it can use.

Compiling happens before Linking, so the COMPILER cannot know ahead of time whether or not the LINKER will find a matching function, thats why you use declarations to notify the COMPILER that a definition will be found by the LINKER later on.

As you can see, your 2 errors are not contradictory, they are the result of 2 separate processes in the build that have a particular order.


问:
How to filter/compare 2 arrays of objects by single property with lodash?
I have the following arrays of objects?

let arr1 = [{
  id: 1,
  props: []
}, {
  id: 2,
  props: []
}, {
  id: 3,
  props: []
}]

let arr2 = [{
  id: 1,
  props: ['a', 'b']
}, {
  id: 3,
  props: []
}]
```

<p>I need to somehow compare these 2 arrays and return a new array that contains only objects which IDs are not in both of the original arrays. So in the case above it should contain only the object with ID 2, since it's only in arr1.</p>

<p>I tried to use</p>

```let arr3 = _.differenceWith(arr1, arr2, _.isEqual)
```

<p>And it works as long as props array in objects are similar and I don't change it (I'm changing it only in the second array).</p>

<p>I also tried this:</p>

```let arr3 = _.filter(arr1, o => o.id === _.find(arr2, obj2 => o.id === obj2.id))
```

But that didn't work at all.

Any ideas?

答:
You could use _.differenceBy with the wanted key id to compare.

let array1 = [{ id: 1, props: [] }, { id: 2, props: [] }, { id: 3, props: [] }],
    array2 = [{ id: 1, props: ['a', 'b'] }, { id: 3, props: [] }],
    difference = _.differenceBy(array1, array2, 'id');

console.log(difference);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script></code>```

Body:
I have the following arrays of objects?

let arr1 = [{
  id: 1,
  props: []
}, {
  id: 2,
  props: []
}, {
  id: 3,
  props: []
}]

let arr2 = [{
  id: 1,
  props: ['a', 'b']
}, {
  id: 3,
  props: []
}]

I need to somehow compare these 2 arrays and return a new array that contains only objects which IDs are not in both of the original arrays. So in the case above it should contain only the object with ID 2, since it's only in arr1.

I tried to use

let arr3 = _.differenceWith(arr1, arr2, _.isEqual)

And it works as long as props array in objects are similar and I don't change it (I'm changing it only in the second array).

I also tried this:

let arr3 = _.filter(arr1, o => o.id === _.find(arr2, obj2 => o.id === obj2.id))

But that didn't work at all.

Any ideas?

Body:
You could use _.differenceBy with the wanted key id to compare.

let array1 = [{ id: 1, props: [] }, { id: 2, props: [] }, { id: 3, props: [] }],
    array2 = [{ id: 1, props: ['a', 'b'] }, { id: 3, props: [] }],
    difference = _.differenceBy(array1, array2, 'id');

console.log(difference);

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>


问:
How can I use xsl:import with a variable in the path name?
Essentially I want do this in XSL:

```<code><xsl:include href="_domains/{$domain}/templates/header.xsl" />
</code>```

But I can't seem to use a variable ($domain) in the include.  Any suggestions on a work around?

答:
Another solution is to load an XML file and transform it by a set of rules (this file could even be a simple XSLT variant).</p>

```<code><xsl:param name="domain">_default</xsl:param>

<xsl:variable name="header-template"
   select="document( concat('_domains/', $domain, '/templates/header.xml' ) )" />

<xsl:template name="header">
  <xsl:apply-templates mode="transform" select="$header-template"/>
</xsl:template>
</code>```

Body:
Essentially I want do this in XSL:

<xsl:include href="_domains/{$domain}/templates/header.xsl" />

But I can't seem to use a variable ($domain) in the include.  Any suggestions on a work around?

Body:
Another solution is to load an XML file and transform it by a set of rules (this file could even be a simple XSLT variant).

<xsl:param name="domain">_default</xsl:param>

<xsl:variable name="header-template"
   select="document( concat('_domains/', $domain, '/templates/header.xml' ) )" />

<xsl:template name="header">
  <xsl:apply-templates mode="transform" select="$header-template"/>
</xsl:template>


问:
Power law regression problem between curve_fit, python and excel
Sorry, I am new in python and stack flow. So I can not post an image.

I want to do the power law regression with curve_fit function in python. But the result is quite strange to me. I use excel to check it further. It looks big difference between these two. Black line is the result from curve_fit and the parameter of red line is from excel. Could someone let me know the difference? Thank you!

```<code>x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x,a,b):
    return a*x**b

popt,pocv=curve_fit(f,x,y)

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px=np.linspace(10,1000000,1000)

#parameter form curve_fit
py=a*px**b
[enter image description here][1]
#parameter from excel
pyy=3E-6*px**0.8305

ax.loglog(px,pyy,color="red")
ax.loglog(px,py,color="k")
</code>```

答:
Log fitting with least_squares is problematic, because differences between points and fitted line are increasing with bigger x value.  That is why fit is not as you expected. To correct this you can add bounds on parameters like below:

```<code>popt,pcov=curve_fit(f,x,y, bounds=(0, [3*10**(-6), 0.9]))
</code>```

The summary parameters error you can get from pcov.

```<code>error = np.sum(np.sqrt(np.diag(pcov)))
</code>```

Output:

or change fitting method.

Body:
Sorry, I am new in python and stack flow. So I can not post an image.

I want to do the power law regression with curve_fit function in python. But the result is quite strange to me. I use excel to check it further. It looks big difference between these two. Black line is the result from curve_fit and the parameter of red line is from excel. Could someone let me know the difference? Thank you!

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x,a,b):
    return a*x**b

popt,pocv=curve_fit(f,x,y)

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px=np.linspace(10,1000000,1000)

#parameter form curve_fit
py=a*px**b
[enter image description here][1]
#parameter from excel
pyy=3E-6*px**0.8305

ax.loglog(px,pyy,color="red")
ax.loglog(px,py,color="k")

Body:
Log fitting with least_squares is problematic, because differences between points and fitted line are increasing with bigger x value.  That is why fit is not as you expected. To correct this you can add bounds on parameters like below:

popt,pcov=curve_fit(f,x,y, bounds=(0, [3*10**(-6), 0.9]))

The summary parameters error you can get from pcov.

error = np.sum(np.sqrt(np.diag(pcov)))

Output:

or change fitting method.


问:
ERROR 1273 (HY000) at line 1520: Unknown collation: 'utf8mb4_0900_ai_ci'
I used to copy the db from remote to my local using script

```<code>ssh -Tq remotehost.com 'mysqldump -C -u remoteuser -p"remotepwd" -h remotehost.com remote_db_name --skip-lock-tables | gzip' | gzip -d | mysql -u localuser -plocalpwd local_db_name
</code>```

It used to work fine but now I'm getting below error -

ERROR 1273 (HY000) at line 1520: Unknown collation: 'utf8mb4_0900_ai_ci'

If I just get sql from remotehost and do run the below command I get below error -

sed -i 's/utf8mb4/utf8/g' portal_dump.sql I get error

```<code>sed: 1: "portal_dump.sql": extra characters at the end of p command
</code>```

What should I do to fix this script?

答: Replace all utf8mb4_0900_ai_ci to utf8mb4_general_ci in your sql file. I think it would be the closest match and it will solve your error.

Body:
I used to copy the db from remote to my local using script

ssh -Tq remotehost.com 'mysqldump -C -u remoteuser -p"remotepwd" -h remotehost.com remote_db_name --skip-lock-tables | gzip' | gzip -d | mysql -u localuser -plocalpwd local_db_name

It used to work fine but now I'm getting below error -

ERROR 1273 (HY000) at line 1520: Unknown collation: 'utf8mb4_0900_ai_ci'

If I just get sql from remotehost and do run the below command I get below error -

sed -i 's/utf8mb4/utf8/g' portal_dump.sql I get error

sed: 1: "portal_dump.sql": extra characters at the end of p command

What should I do to fix this script?


问:
How to shrink dataset using the minimum and the maximum of columns? Can I use apply family of functions?
I have a data set in this form:

```<code>  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA
</code>```

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

```<code>  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium
</code>```

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

答:
We can convert the time variables to POSIXct class, then for each combination of species and date, get the minimum value of start.time, maximum value of end.time and get unique value of remarks.

```<code>library(dplyr)

df %>%
  mutate_at(vars(ends_with('time')), as.POSIXct) %>%
  group_by(species, date) %>%
  summarise(start.time = min(start.time, na.rm = TRUE),
            end.time = max(end.time, na.rm = TRUE),
            remarks = toString(unique(na.omit(remarks))))

#  species date       start.time          end.time            remarks
#  <fct>   <fct>      <dttm>              <dttm>              <chr>
#1  A       2020-02-01 2020-02-01 08:00:00 2020-02-02 00:00:00 slow
#2  A       2020-02-02 2020-02-01 08:00:00 2020-02-01 11:30:00 medium
</code>```

Doing this in base R :

```<code>#Convert time to POSIXct
df[3:4] <- lapply(df[3:4], as.POSIXct)
#Get min start.time
df1 <- aggregate(start.time~species + date, df, min, na.rm = TRUE,
                 na.action = "na.pass")
#Get max end.time
df2 <- aggregate(end.time~species + date, df, max, na.rm = TRUE,
                 na.action = "na.pass")
#Get combined remarks
df3 <- aggregate(remarks~species + date, df, function(x)
            toString(unique(na.omit(x))), na.action = "na.pass")
#merge into one dataset
Reduce(merge, list(df1, df2, df3))
</code>```

data

```<code>df <- structure(list(species = structure(c(1L, 1L, 1L, 1L), .Label = "A",
class = "factor"), date = structure(c(1L, 1L, 2L, 2L), .Label = c("2020-02-01",
"2020-02-02"), class = "factor"), start.time = structure(c(1L,
2L, 1L, NA), .Label = c("2020-02-018:00:00", "2020-02-019:00:00"
), class = "factor"), end.time = structure(c(2L, 3L, NA,
1L), .Label = c("2020-02-0111:30:00", "2020-02-0112:00:00",
"2020-02-0200:00:00"), class = "factor"), remarks = structure(c(2L,
NA, 1L, NA), .Label = c("medium", "slow"), class = "factor")),
class = "data.frame", row.names = c(NA, -4L))
</code>```

Body:
I have a data set in this form:

  species  date         start.time           end.time              remarks
  A        2020-02-01   2020-02-01 8:00:00   2020-02-01 12:00:00   slow
  A        2020-02-01   2020-02-01 9:00:00   2020-02-02 00:00:00   NA
  A        2020-02-02   2020-02-01 8:00:00   NA                    medium
  A        2020-02-02   NA                   2020-02-01 11:30:00    NA

I have 20 different species and 200 different dates. The data pretty much behaves the same in every species.

How can I shrink the data to get the minimum start.time, maximum end.time and every unique remark for each species and date? The output is:

  species  date         start.time   end.time   remarks
  A        2020-02-01   8:00am       12:00am    slow
  A        2020-02-02   8:00am       11:30am    medium

I need the codes to be done in BASE R to be able to use it in a computer without the internet.

Body:
We can convert the time variables to POSIXct class, then for each combination of species and date, get the minimum value of start.time, maximum value of end.time and get unique value of remarks.

library(dplyr)

df %>%
  mutate_at(vars(ends_with('time')), as.POSIXct) %>%
  group_by(species, date) %>%
  summarise(start.time = min(start.time, na.rm = TRUE),
            end.time = max(end.time, na.rm = TRUE),
            remarks = toString(unique(na.omit(remarks))))

#  species date       start.time          end.time            remarks
#  <fct>   <fct>      <dttm>              <dttm>              <chr>
#1  A       2020-02-01 2020-02-01 08:00:00 2020-02-02 00:00:00 slow
#2  A       2020-02-02 2020-02-01 08:00:00 2020-02-01 11:30:00 medium

Doing this in base R :

#Convert time to POSIXct
df[3:4] <- lapply(df[3:4], as.POSIXct)
#Get min start.time
df1 <- aggregate(start.time~species + date, df, min, na.rm = TRUE,
                 na.action = "na.pass")
#Get max end.time
df2 <- aggregate(end.time~species + date, df, max, na.rm = TRUE,
                 na.action = "na.pass")
#Get combined remarks
df3 <- aggregate(remarks~species + date, df, function(x)
            toString(unique(na.omit(x))), na.action = "na.pass")
#merge into one dataset
Reduce(merge, list(df1, df2, df3))

data

df <- structure(list(species = structure(c(1L, 1L, 1L, 1L), .Label = "A",
class = "factor"), date = structure(c(1L, 1L, 2L, 2L), .Label = c("2020-02-01",
"2020-02-02"), class = "factor"), start.time = structure(c(1L,
2L, 1L, NA), .Label = c("2020-02-018:00:00", "2020-02-019:00:00"
), class = "factor"), end.time = structure(c(2L, 3L, NA,
1L), .Label = c("2020-02-0111:30:00", "2020-02-0112:00:00",
"2020-02-0200:00:00"), class = "factor"), remarks = structure(c(2L,
NA, 1L, NA), .Label = c("medium", "slow"), class = "factor")),
class = "data.frame", row.names = c(NA, -4L))


问:
How to delete few middle commits in gitlab?
I need a help in git/gitlab.
I got gitlab with test repo e.g. 6 commits:
A->B->C->D->E->F
Commit A is first and F the last one.
How Can I do this: remove commits B,C,D,E?
I want to have only the first one and last one"
A->F
I do it because my repo weights a lot.
What commands shoul I enter?</p>

答:
Begin an interactive rebase, choosing a commit early enough that it is before the commits you want to remove, such as A.

```<code>git rebase -i <hash-A>
</code>```

A file opens with a list of commits up to A, with the instruction to pick all the commits.

In that file that opens, delete the lines of the commits you want to remove.

Save and close the file.

The rebase will begin automatically and apply your desired changes.

Push your changes, which will require force push due to rewriting history.

```<code>git push -f
</code>```

Body:
Begin an interactive rebase, choosing a commit early enough that it is before the commits you want to remove, such as A.

git rebase -i <hash-A>

A file opens with a list of commits up to A, with the instruction to pick all the commits.

In that file that opens, delete the lines of the commits you want to remove.

Save and close the file.

The rebase will begin automatically and apply your desired changes.

Push your changes, which will require force push due to rewriting history.

git push -f


问:
Jolt json transform question. Have a record with an array inside and need to convert to an array of records
I need to transform some flow files in NIFI and would like to use Jolt transforms. I have been playing with this for a while and cannot figure out a transform that will work. I have...

```<code>{
  "asset": "transformer1",
  "readings": {
    "oil_temp": 0.7499248991503604,
    "otc_top_temp": 0.2870503485615279
  },
  "timestamp": "02/17/2020 19:07:31",
  "key": "e2af07ab-4d21-4a70-ba3f-9113bb335d1e"
}
</code>```

and need to transform that into an array of records like this...

```<code>[
  {
    "tag": "transformer1.oil_temp",
    "timestamp": "02/17/2020 19:07:31",
    "value": 0.7499248991503604
  },
  {
    "tag": "transformer1.otc_top_temp",
    "timestamp": "02/17/2020 19:07:31",
    "value": 0.2870503485615279
  }
]

</code>```

I hope that this is possible. I would greatly appreciate any help. Thank you.

答:
You can achieve this with multiple transform steps:

Readings map to list

Create new tag field by using concat operation

Pass through only values you want as a result

JoltSpec:

```<code>[
  {
    "operation": "shift",
    "spec": {
      "readings": {
        "*": {
          "@(2,asset)": "[#2].asset",
          "$": "[#2].name",
          "@": "[#2].value",
          "@(2,timestamp)": "[#2].timestamp"
        }
      }
    }
  }, {
    "operation": "modify-default-beta",
    "spec": {
      "*": {
        "tag": "=concat(@(1,asset),'.',@(1,name))"
      }
    }
  }, {
    "operation": "shift",
    "spec": {
      "*": {
        "tag": "[&1].tag",
        "timestamp": "[&1].timestamp",
        "value": "[&1].value"
      }
    }
  }
]
</code>```

Input:

```<code>{
  "asset": "transformer1",
  "readings": {
    "oil_temp": 0.7499248991503604,
    "otc_top_temp": 0.2870503485615279
  },
  "timestamp": "02/17/2020 19:07:31",
  "key": "e2af07ab-4d21-4a70-ba3f-9113bb335d1e"
}
</code>```

Output:

```<code>[ {
  "tag" : "transformer1.oil_temp",
  "timestamp" : "02/17/2020 19:07:31",
  "value" : 0.7499248991503604
}, {
  "tag" : "transformer1.otc_top_temp",
  "timestamp" : "02/17/2020 19:07:31",
  "value" : 0.2870503485615279
} ]
</code>```

Test it here: https://jolt-demo.appspot.com/#inception

Body:
I need to transform some flow files in NIFI and would like to use Jolt transforms. I have been playing with this for a while and cannot figure out a transform that will work. I have...

{
  "asset": "transformer1",
  "readings": {
    "oil_temp": 0.7499248991503604,
    "otc_top_temp": 0.2870503485615279
  },
  "timestamp": "02/17/2020 19:07:31",
  "key": "e2af07ab-4d21-4a70-ba3f-9113bb335d1e"
}

and need to transform that into an array of records like this...

[
  {
    "tag": "transformer1.oil_temp",
    "timestamp": "02/17/2020 19:07:31",
    "value": 0.7499248991503604
  },
  {
    "tag": "transformer1.otc_top_temp",
    "timestamp": "02/17/2020 19:07:31",
    "value": 0.2870503485615279
  }
]

I hope that this is possible. I would greatly appreciate any help. Thank you.

Body:
You can achieve this with multiple transform steps:

Readings map to list

Create new tag field by using concat operation

Pass through only values you want as a result

JoltSpec:

[
  {
    "operation": "shift",
    "spec": {
      "readings": {
        "*": {
          "@(2,asset)": "[#2].asset",
          "$": "[#2].name",
          "@": "[#2].value",
          "@(2,timestamp)": "[#2].timestamp"
        }
      }
    }
  }, {
    "operation": "modify-default-beta",
    "spec": {
      "*": {
        "tag": "=concat(@(1,asset),'.',@(1,name))"
      }
    }
  }, {
    "operation": "shift",
    "spec": {
      "*": {
        "tag": "[&1].tag",
        "timestamp": "[&1].timestamp",
        "value": "[&1].value"
      }
    }
  }
]

Input:

{
  "asset": "transformer1",
  "readings": {
    "oil_temp": 0.7499248991503604,
    "otc_top_temp": 0.2870503485615279
  },
  "timestamp": "02/17/2020 19:07:31",
  "key": "e2af07ab-4d21-4a70-ba3f-9113bb335d1e"
}

Output:

[ {
  "tag" : "transformer1.oil_temp",
  "timestamp" : "02/17/2020 19:07:31",
  "value" : 0.7499248991503604
}, {
  "tag" : "transformer1.otc_top_temp",
  "timestamp" : "02/17/2020 19:07:31",
  "value" : 0.2870503485615279
} ]

Test it here: https://jolt-demo.appspot.com/#inception


问:
How to increase the font size of first two letters of any word/sentence?
I am trying to make the font size bigger for first two letters of nav links. I know for first letter it can be achieved using :first-letter. However I have tried it using span like below and it's increasing the font size but not getting aligned horizontally. About and Contact links are moving to top, both should be aligned with rest of the links (from bottom). I don't want to set line-height to the main container because the sub links are supposed to display below the main links. Any idea about this?

```<code><li><a href="#"><span>01</span> Architectural Design</a></li>
</code>```

CSS

```<code>ul li a span {
  font-size: 25px;
}
</code>```

.nav {
  font-family: arial;
  background: #dddddd;
  overflow: hidden;
  padding: 10px;
}

a {
  color: #000;
  text-decoration: none;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  font-size: 12px;
  float: left;
  margin-right: 30px;
}

ul li a span {
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li>About</li>
    <li><span>01</span> Architectural Design</li>
    <li><span>02</span> Media</li>
    <li><span>03</span> Developments</li>
    <li>Contact</li>
  </ul>
</div></code>```

答:
It can only be used with the pseudo elements :before that make your code much cleaner and easy to read.

.empty:before {
  content: "";
  font-size: 25px;
}

.nav {
  font-family: arial;
  background: #dddddd;
  overflow: hidden;
  padding: 10px;
}

a {
  color: #000;
  text-decoration: none;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  font-size: 12px;
  float: left;
  margin-right: 30px;
}

ul li a span {
  font-size: 25px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="nav">
  <ul>
    <li>About</li>
    <li><span>01</span> Architectural Design</li>
    <li><span>02</span> Media</li>
    <li><span>03</span> Developments</li>
    <li>Contact</li>
  </ul>
</div></code>```

Body:
I am trying to make the font size bigger for first two letters of nav links. I know for first letter it can be achieved using :first-letter. However I have tried it using span like below and it's increasing the font size but not getting aligned horizontally. About and Contact links are moving to top, both should be aligned with rest of the links (from bottom). I don't want to set line-height to the main container because the sub links are supposed to display below the main links. Any idea about this?

01 Architectural Design

CSS

ul li a span {
  font-size: 25px;
}

.nav {
  font-family: arial;
  background: #dddddd;
  overflow: hidden;
  padding: 10px;
}

a {
  color: #000;
  text-decoration: none;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  font-size: 12px;
  float: left;
  margin-right: 30px;
}

ul li a span {
  font-size: 25px;
}

About

01 Architectural Design

02 Media

03 Developments

Contact

Body:
It can only be used with the pseudo elements :before that make your code much cleaner and easy to read.

.empty:before {
  content: "";
  font-size: 25px;
}

.nav {
  font-family: arial;
  background: #dddddd;
  overflow: hidden;
  padding: 10px;
}

a {
  color: #000;
  text-decoration: none;
}

ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

li {
  font-size: 12px;
  float: left;
  margin-right: 30px;
}

ul li a span {
  font-size: 25px;
}

<div class="nav">
  <ul>
    <li><a class='empty' href="#">About</a></li>
    <li><a href="#"><span>01</span> Architectural Design</a></li>
    <li><a href="#"><span>02</span> Media</a></li>
    <li><a href="#"><span>03</span> Developments</a></li>
    <li><a class='empty' href="#">Contact</a></li>
  </ul>
</div>


问:
UnhandledExceptionFilter not called with redirected stderr output
I am having a problem hitting an UnhandledExceptionFilter set by SetUnhandledExceptionFilter() when the stderr is being redirected.

There is an custom exception filter set by SetUnhandledExceptionFilter(), that is supposed to write out details about the exception as well as the stack to stderr. The problem is, that it is not working when I redirect the stderr output into a file. It is not even called at all.

If I execute the program using

```<code>app.exe > log
</code>```

the filter is called, but if I execute it like this

```<code>app.exe 2> log
</code>```

it isn't called. I already tried a different approach since I call the application in question from another program using system(). I used _pipe() and _spawnvp() to redirect the output and reading it from the pipe, but that didn't help.

I started looking into AddVectoredExceptionHandler() and it seems to work, but it is called on any exception and I have no idea how to figure out how this plays out with try/catch code since I just want the unhandled exceptions.

I am already aware, that an UnhandledExceptionFilter is not called when the program is run in a debugger (http://support.microsoft.com/kb/173652/en-us), but why does it treat a redirection of stderr like it is run in a debugger? Any ideas how to prevent this?

答:
Found my stupid mistake.

The exception filter is called, but since the application terminates after the function the data is still stuck in the stream and is never flushed. If I add

```<code>fflush(stderr);
</code>```

at the end of my exception filter the stuff is actually written.

Sorry for once again figuring my mistake out short after posting it, but this is actually an issue, that bugged me for months and not just a few hours.

Body:
I am having a problem hitting an UnhandledExceptionFilter set by SetUnhandledExceptionFilter() when the stderr is being redirected.

There is an custom exception filter set by SetUnhandledExceptionFilter(), that is supposed to write out details about the exception as well as the stack to stderr. The problem is, that it is not working when I redirect the stderr output into a file. It is not even called at all.

If I execute the program using

app.exe > log

the filter is called, but if I execute it like this

app.exe 2> log

it isn't called. I already tried a different approach since I call the application in question from another program using system(). I used _pipe() and _spawnvp() to redirect the output and reading it from the pipe, but that didn't help.

I started looking into AddVectoredExceptionHandler() and it seems to work, but it is called on any exception and I have no idea how to figure out how this plays out with try/catch code since I just want the unhandled exceptions.

I am already aware, that an UnhandledExceptionFilter is not called when the program is run in a debugger (http://support.microsoft.com/kb/173652/en-us), but why does it treat a redirection of stderr like it is run in a debugger? Any ideas how to prevent this?

Body:
Found my stupid mistake.

The exception filter is called, but since the application terminates after the function the data is still stuck in the stream and is never flushed. If I add

fflush(stderr);

at the end of my exception filter the stuff is actually written.

Sorry for once again figuring my mistake out short after posting it, but this is actually an issue, that bugged me for months and not just a few hours.


问:
React native EXPO / while installing sketch npm all are showing RNSketch error
```<code>requireNativeComponent: "RNSketch" was not found in the UIManager.
- node_modules/react-native/Libraries/ReactNative/getNativeComponentAttributes.js:30:4 in getNativeComponentAttributes
- node_modules/react-native/Libraries/Renderer/shims/ReactNativeViewConfigRegistry.js:102:25 in exports.get
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:4097:40 in createInstance
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:15835:12 in completeWork
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19409:28 in completeUnitOfWork
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19380:30 in performUnitOfWork
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19347:39 in workLoopSync
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18997:22 in renderRoot
* [native code]:null in renderRoot
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18709:28 in runRootCallback
* [native code]:null in runRootCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5642:32 in runWithPriority$argument_1
- node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5638:22 in flushSyncCallbackQueueImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5627:28 in flushSyncCallbackQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18556:30 in scheduleUpdateOnFiber
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:21822:15 in scheduleRootUpdate
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:23042:20 in ReactNativeRenderer.render
- node_modules/react-native/Libraries/ReactNative/renderApplication.js:52:52 in renderApplication
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:116:10 in runnables.appKey.run
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:197:26 in runApplication
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue

Warning: %s: Error boundaries should implement getDerivedStateFromError(). In that method, return a state update to display an error message or fallback UI., RootErrorBoundary
- node_modules/expo/build/environment/muteWarnings.fx.js:27:24 in error
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:645:36 in warningWithoutStack
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18056:16 in callback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:7595:16 in callCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:7639:19 in commitUpdateEffects
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:7630:22 in commitUpdateQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:17116:10 in commitLifeCycles
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:20002:23 in commitLayoutEffects
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:307:15 in invokeGuardedCallbackImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:531:36 in invokeGuardedCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19768:10 in commitRootImpl
* [native code]:null in commitRootImpl
- node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:19590:4 in commitRoot
* [native code]:null in commitRoot
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18709:28 in runRootCallback
* [native code]:null in runRootCallback
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5642:32 in runWithPriority$argument_1
- node_modules/scheduler/cjs/scheduler.development.js:643:23 in unstable_runWithPriority
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5638:22 in flushSyncCallbackQueueImpl
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:5627:28 in flushSyncCallbackQueue
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:18556:30 in scheduleUpdateOnFiber
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:21822:15 in scheduleRootUpdate
- node_modules/react-native/Libraries/Renderer/implementations/ReactNativeRenderer-dev.js:23042:20 in ReactNativeRenderer.render
- node_modules/react-native/Libraries/ReactNative/renderApplication.js:52:52 in renderApplication
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:116:10 in runnables.appKey.run
- node_modules/react-native/Libraries/ReactNative/AppRegistry.js:197:26 in runApplication
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:436:47 in __callFunction
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:111:26 in __guard$argument_0
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:384:10 in __guard
- node_modules/react-native/Libraries/BatchedBridge/MessageQueue.js:110:17 in __guard$argument_0
* [native code]:null in callFunctionReturnFlushedQueue
</code>```

答: This module is not on android and if you are using expo , you need to detach it to pure react native . Please see the below link too rn-skecth:


问:
Undefined contants.ts API value
I have a constant.ts file that exports the base API. When I try to import the constants file and use the base API, I get an undefined. Here is my code</p>

```<code>Constants.ts

export class Constants {
  public static API_ENDPOINT: 'https://www.techiediaries.com/api/';
}

App.module.ts

 providers: [Constants],

Api.service.ts

import { Constants } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}
</code>```

答:
You're declaring the type in constants.ts, not assigning it a value.

It should be

```<code>export class Constants {
  public static API_ENDPOINT = 'https://www.techiediaries.com/api/';
}
</code>```

This is setting the value 'https://www.techiediaries.com/api/' rather than declaring the type to be 'https://www.techiediaries.com/api/'.

Edit:

You don't need to set it as a provider if you're calling it directly. And as the other answer states, if it is a constant, then you should export is as a constant.

Even better, add it to environment.ts and the related environment files.

environment.ts

```<code>export const environment = {
  API_ENDPOINT = 'https://www.techiediaries.com/api/'
};
</code>```

Then you can call a different endpoint in each environment if you wish.

Title: Undefined contants.ts API value

Body:
I have a constant.ts file that exports the base API. When I try to import the constants file and use the base API, I get an undefined. Here is my code

Constants.ts

export class Constants {
  public static API_ENDPOINT: 'https://www.techiediaries.com/api/';
}

App.module.ts

 providers: [Constants],

Api.service.ts

import { Constants } from '../constants/constants';

getData() {
  console.log(Constants.API_ENDPOINT);
  return this.httpClient.get(Constants.API_ENDPOINT + 'data.json');
}

Body:
You're declaring the type in constants.ts, not assigning it a value.

It should be

export class Constants {
  public static API_ENDPOINT = 'https://www.techiediaries.com/api/';
}

This is setting the value 'https://www.techiediaries.com/api/' rather than declaring the type to be 'https://www.techiediaries.com/api/'.

Edit:

You don't need to set it as a provider if you're calling it directly. And as the other answer states, if it is a constant, then you should export is as a constant.

Even better, add it to environment.ts and the related environment files.

environment.ts

export const environment = {
  API_ENDPOINT = 'https://www.techiediaries.com/api/'
};

Then you can call a different endpoint in each environment if you wish.


问:
Copy array items into another array
I have a JavaScript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the items into the new array:

```<code>var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...
</code>```

or even better:

```<code>var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);
</code>```

So now the new array contains all the values of the individual data arrays.  Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the items one by one?

答:
Try this:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayB.reduce((pre, cur) => [...pre, ...cur], arrayA);
console.log(newArray)
```

Title: Copy array items into another array

Body:
I have a JavaScript array dataArray which I want to push into a new array newArray. Except I don't want newArray[0] to be dataArray. I want to push in all the items into the new array:

var newArray = [];

newArray.pushValues(dataArray1);
newArray.pushValues(dataArray2);
// ...

or even better:

var newArray = new Array (
   dataArray1.values(),
   dataArray2.values(),
   // ... where values() (or something equivalent) would push the individual values into the array, rather than the array itself
);

So now the new array contains all the values of the individual data arrays.  Is there some shorthand like pushValues available so I don't have to iterate over each individual dataArray, adding the items one by one?


问:
how do I override a setter function at runtime in actionscript?
I have an AS class with setter and getter functions.
I need to tweak one of this class's instances so that it's setter function will process the input before assigning it to the local variable.

or, in a more elaborated way, what should I use instead of $$$ in the example below?

```<code>class MyClass{
    private var _legend:Array;
    function set legend(legend:Array):void{
        _legend= legend;
    }
    function get legend():Array{
        return _legend;
    }
    function someFunction():void{
        foo();
    }
}
var mc:MyClass = new MyClass();
mc.someFunction = function():void{
    bar();
}
mc.$$$ = new function(legend:Array):void{
    _legend = process(legend);
}
</code>```

答:
Why don't you pass the instance a processed input?

```<code>mc.legend = process(legend);
</code>```

If this is not possible, you can modify the setter in MyClass and take an optional boolean to do processing.

```<code>function set legend(legend:Array, flag:bool = false):void{
            _legend = flag ? process(legend) : legend;
}
</code>```

Note that prototype inheritance does not restrict itself to a particular instance. From the documentation:

Prototype inheritance - is the only inheritance mechanism in previous versions of ActionScript and serves as an alternate form of inheritance in ActionScript 3.0. Each class has an associated prototype object, and the properties of the prototype object are shared by all instances of the class.

OwnerDisplayName: Amir Arad

ContentLicense: CC BY-SA 2.5

Body:
I have an AS class with setter and getter functions.
I need to tweak one of this class's instances so that it's setter function will process the input before assigning it to the local variable.

or, in a more elaborated way, what should I use instead of $$$ in the example below?

class MyClass{
    private var _legend:Array;
    function set legend(legend:Array):void{
        _legend= legend;
    }
    function get legend():Array{
        return _legend;
    }
    function someFunction():void{
        foo();
    }
}
var mc:MyClass = new MyClass();
mc.someFunction = function():void{
    bar();
}
mc.$$$ = new function(legend:Array):void{
    _legend = process(legend);
}

LastEditorDisplayName: Amir Arad

Body:
Why don't you pass the instance a processed input?

mc.legend = process(legend);

If this is not possible, you can modify the setter in MyClass and take an optional boolean to do processing.

function set legend(legend:Array, flag:bool = false):void{
            _legend = flag ? process(legend) : legend;
}

Note that prototype inheritance does not restrict itself to a particular instance. From the documentation:

Prototype inheritance - is the only inheritance mechanism in previous versions of ActionScript and serves as an alternate form of inheritance in ActionScript 3.0. Each class has an associated prototype object, and the properties of the prototype object are shared by all instances of the class.

OwnerDisplayName: dirkgently


问:
Cannot use a find function inside a return function in react redux project
I tried to use a find function inside the return function of the react component. but it is not working
the error report shows anonymous function.
What i tried to do is fetching the 'product' and 'category' from the API through redux and display the list of product along with the category name instead of the categoryid stored in the product object
**THE QUESTION IS HOW TO MAKE THIS WORK
   category = categories.find(category => category.id === product.category)
**</p>

```<code>    import React,{useEffect} from 'react'
import {useSelector,useDispatch} from 'react-redux'
import {fetchProduct} from '../../../actions/product.actions'
import {fetchCategory} from '../../../actions/category.actions'
import { Table } from 'semantic-ui-react'

const ProductList=()=>{
    const productsData=useSelector(state=>state.products)
    const categoriesData=useSelector(state=>state.categories)
    const dispatch=useDispatch()
    const category={}
    const categories=categoriesData.categories[1]

    useEffect(()=>{
        dispatch(fetchProduct())
        dispatch(fetchCategory())

    },[])

    const findCategory=(categoryId)=>{
    return categories.find(category => category.id === categoryId)
    }

    return productsData.loading ?(

        <h2>Loading</h2>
    ): productsData.error?(
        <h2>{productsData.error}</h2>
    ):(
        <div>

            <Table striped>
                <Table.Header>
                <Table.Row>
                    <Table.HeaderCell>Name</Table.HeaderCell>
                    <Table.HeaderCell>Category</Table.HeaderCell>
                    <Table.HeaderCell>Brand</Table.HeaderCell>
                    <Table.HeaderCell>Model</Table.HeaderCell>
                </Table.Row>
                </Table.Header>

                <Table.Body>
                    {
                        productsData.products.map(product=>{
                            category = categories.find(category => category.id === product.category)

                            return(

                                <Table.Row key={product.id}>
                                    <Table.Cell>{product.name}</Table.Cell>
                                    <Table.Cell>{category.name}</Table.Cell>
                                    <Table.Cell>{product.brand}</Table.Cell>
                                    <Table.Cell>{product.model}</Table.Cell>
                                </Table.Row>
                            )
                        })
                    }

                </Table.Body>
        </Table>
        {console.log(categories)}
        {console.log(productsData) }
        </div>
    )
}

export default ProductList
</code>```

答:
You don't actually mention what the error is you're seeing (other than it occurs in an anonymous function), but I suspect it is some "cannot access * of undefined", either in the find function callback itself, or in the return value of the map function.

Undefined in Find Callback?

```<code>category = categories.find(category => category.id === product.category)
</code>```

Here it appears only product can be undefined when trying to access product.category. By definition category has to be defined since it is from mapping over categories array.

But for the same reason we know we can check category.id we know product is defined from the outer map callback anonymous scope and checking product.category is safe.

Undefined in Map Callback?

```<code>productsData.products.map(product=>{
  category = categories.find(category => category.id === product.category);

  return (
    <Table.Row key={product.id}>
      <Table.Cell>{product.name}</Table.Cell>
      <Table.Cell>{category.name}</Table.Cell>
      <Table.Cell>{product.brand}</Table.Cell>
      <Table.Cell>{product.model}</Table.Cell>
    </Table.Row>
  )
})
</code>```

So we've determined that both product from the map function callback and category from the find function callback should be defined we're left with the find function's return value. array::find returns undefined if no elements match the predicate and are found in the array. You should guard for this.

```<code>productsData.products.map(product=>{
  category = categories.find(category => category.id === product.category);

  if (!category) return null;

  return(
    <Table.Row key={product.id}>
      <Table.Cell>{product.name}</Table.Cell>
      <Table.Cell>{category.name}</Table.Cell>
      <Table.Cell>{product.brand}</Table.Cell>
      <Table.Cell>{product.model}</Table.Cell>
    </Table.Row>
  )
})
</code>```

null is valid renderable JSX, but mapping an array to null values may seem odd

NOTE: This doesn't preclude the fact that there could be an external issue where either of the arrays being iterated over are for some reason undefined, but that could mean you don't have good default prop values, or your reducers return undefined initial values (or both).

Body:
I tried to use a find function inside the return function of the react component. but it is not working
the error report shows anonymous function.
What i tried to do is fetching the 'product' and 'category' from the API through redux and display the list of product along with the category name instead of the categoryid stored in the product object
**THE QUESTION IS HOW TO MAKE THIS WORK
   category = categories.find(category => category.id === product.category)
**

    import React,{useEffect} from 'react'
import {useSelector,useDispatch} from 'react-redux'
import {fetchProduct} from '../../../actions/product.actions'
import {fetchCategory} from '../../../actions/category.actions'
import { Table } from 'semantic-ui-react'

const ProductList=()=>{
    const productsData=useSelector(state=>state.products)
    const categoriesData=useSelector(state=>state.categories)
    const dispatch=useDispatch()
    const category={}
    const categories=categoriesData.categories[1]

    useEffect(()=>{
        dispatch(fetchProduct())
        dispatch(fetchCategory())

    },[])

    const findCategory=(categoryId)=>{
    return categories.find(category => category.id === categoryId)
    }

    return productsData.loading ?(

Loading

    ): productsData.error?(

{productsData.error}

    ):(

Name

Category

Brand

Model

                    {
                        productsData.products.map(product=>{
                            category = categories.find(category => category.id === product.category)

                            return(

{product.name}

{category.name}

{product.brand}

{product.model}

                            )
                        })
                    }

        {console.log(categories)}
        {console.log(productsData) }

    )
}

export default ProductList

Body:
You don't actually mention what the error is you're seeing (other than it occurs in an anonymous function), but I suspect it is some "cannot access * of undefined", either in the find function callback itself, or in the return value of the map function.

Undefined in Find Callback?

category = categories.find(category => category.id === product.category)

Here it appears only product can be undefined when trying to access product.category. By definition category has to be defined since it is from mapping over categories array.

But for the same reason we know we can check category.id we know product is defined from the outer map callback anonymous scope and checking product.category is safe.

Undefined in Map Callback?

productsData.products.map(product=>{
  category = categories.find(category => category.id === product.category);

  return (
    <Table.Row key={product.id}>
      <Table.Cell>{product.name}</Table.Cell>
      <Table.Cell>{category.name}</Table.Cell>
      <Table.Cell>{product.brand}</Table.Cell>
      <Table.Cell>{product.model}</Table.Cell>
    </Table.Row>
  )
})

So we've determined that both product from the map function callback and category from the find function callback should be defined we're left with the find function's return value. array::find returns undefined if no elements match the predicate and are found in the array. You should guard for this.

productsData.products.map(product=>{
  category = categories.find(category => category.id === product.category);

  if (!category) return null;

  return(
    <Table.Row key={product.id}>
      <Table.Cell>{product.name}</Table.Cell>
      <Table.Cell>{category.name}</Table.Cell>
      <Table.Cell>{product.brand}</Table.Cell>
      <Table.Cell>{product.model}</Table.Cell>
    </Table.Row>
  )
})

null is valid renderable JSX, but mapping an array to null values may seem odd

NOTE: This doesn't preclude the fact that there could be an external issue where either of the arrays being iterated over are for some reason undefined, but that could mean you don't have good default prop values, or your reducers return undefined initial values (or both).


问:
Show different header after and before logging in PHP
I am looking for a solution to show different menu-bar to users as per their login status.

For example, if the user is not logged in , they will see the different menu-bar and once logged in they see the other.

I am able to attain this by making two different menu-bars and including them as per $_SESSION()

```<code><?php
        include('connection.php');
        session_start();
        if($_SESSION["login"] != "login"){
            unset($_SESSION['login']);
            include('includes/header.php'); // menubar to display if not logged in.
        }else {
            include('includes/header-login.php'); // menubar to display when logged in.
        }
    ?>
</code>```

This allows me to show different menu-bar as per the user login status, but the problem is that when the user ins not logged in and they access the page, they see this error

Notice:  Undefined index: login in C:\xxx\htdocs\xxx\abc.php on line 34

So what can be the solution for same ?

答:
Instead of if(!$_SESSION["login"] == "yes")try the following as your condition check

```<code>if (isset($_SESSION['login'])) {
    // menubar to display when logged in.
}else{
    //menubar to display if not logged in.
}
</code>```

Body:
I am looking for a solution to show different menu-bar to users as per their login status.

For example, if the user is not logged in , they will see the different menu-bar and once logged in they see the other.

I am able to attain this by making two different menu-bars and including them as per $_SESSION()

<?php
        include('connection.php');
        session_start();
        if($_SESSION["login"] != "login"){
            unset($_SESSION['login']);
            include('includes/header.php'); // menubar to display if not logged in.
        }else {
            include('includes/header-login.php'); // menubar to display when logged in.
        }
    ?>

This allows me to show different menu-bar as per the user login status, but the problem is that when the user ins not logged in and they access the page, they see this error

Notice:  Undefined index: login in C:\xxx\htdocs\xxx\abc.php on line 34

So what can be the solution for same ?

Body:
Instead of if(!$_SESSION["login"] == "yes")try the following as your condition check

if (isset($_SESSION['login'])) {
    // menubar to display when logged in.
}else{
    //menubar to display if not logged in.
}


问:
How to search for pointers to functions using grep?
I am trying to grep for lines that contain the below pattern

```<code>       foo(somethingHere -> somethingThere,...)
</code>```

The below line contains the pattern that I am trying to grep for.

```<code>       ReconnectAddr(master -> Addrin, Node);
</code>```

I tried using:

```<code>grep "([A-Za-z]\\->[A-Za-z])"
</code>```

But, it does not show the results that I am looking for.
Can someone help me?

答:
Try:

```<code>grep -i -E '\([a-z]+ *-> *[a-z]+\)' filename
</code>```

You need the + quantifier to match a sequence of letters rather than just a single letter, and this requires using extended regexp with the -E option.

You need to match optional whitespace around the -> with *.

Since () have special meaning in ERE, they need to be escaped.

Body:
I am trying to grep for lines that contain the below pattern

       foo(somethingHere -> somethingThere,...)

The below line contains the pattern that I am trying to grep for.

       ReconnectAddr(master -> Addrin, Node);

I tried using:

grep "([A-Za-z]\\->[A-Za-z])"

But, it does not show the results that I am looking for.
Can someone help me?

Body:
Try:

grep -i -E '\([a-z]+ *-> *[a-z]+\)' filename

You need the + quantifier to match a sequence of letters rather than just a single letter, and this requires using extended regexp with the -E option.

You need to match optional whitespace around the -> with *.

Since () have special meaning in ERE, they need to be escaped.


问:
How to convert from docx to pdf with a python function (WINDOWS)?
I am working on an env with a python function to convert docx to pdf files. I'm using postman to send base64. Then I mount the docx file (everything works yet), but when it converts the docx file into pdf, an error shows up. I'm thinking that is because I do not have Office on my env? How can I fix it without having office? Thanks.

```<code>import sys
import os
import comtypes.client
import pythoncom
import uuid
import requests
from docx import Document
import base64
from os import listdir
from os.path import isfile, join
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
  bytesDoc = req.get_json()['base']

  path = '/users/echornet/pruebas/'
  newFile = open(path + 'prueba.docx','wb')
  newFile.write(base64.b64decode(bytesDoc))

  newFile.close()
  wdFormatPDF = 17

  out_file = path + 'prueba.pdf'
  word = comtypes.client.CreateObject('Word.Application')

  doc = word.Documents.Open(newFile)
  doc.SaveAs(out_file, FileFormat=wdFormatPDF)
  doc.Close()
</code>```

This is the error I'm getting. I get the docx created from base64, but no conversion.

System.Private.CoreLib: Exception while executing function:
  Functions.FunConverter. System.Private.CoreLib: Result: Failure
  Exception: AttributeError: module 'comtypes.gen.Word' has no attribute
  '_Application' Stack:   File
  "C:\PruebaFunction\ConvEnv\lib\site-packages\azure\functions_worker\dispatcher.py",
  line 288, in _handle__invocation_request
      self.run_sync_func, invocation_id, fi.func, args)   File "C:\Users\echornet\AppData\Local\Programs\Python\Python36\lib\concurrent\futures\thread.py",
  line 55, in run
      result = self.fn(*self.args, **self.kwargs)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\azure\functions_worker\dispatcher.py",
  line 347, in __run_sync_func
      return func(**params)   File "C:\PruebaFunction\FunConverter__init.py", line 32, in main
      word = comtypes.client.CreateObject('Word.Application')   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 250, in CreateObject
      return _manage(obj, clsid, interface=interface)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 188, in _manage
      obj = GetBestInterface(obj)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 112, in GetBestInterface
      interface = getattr(mod, itf_name)

答:
You can use the python library docx2pdf which internally uses win32com: https://github.com/AlJohri/docx2pdf

Install:

```<code>pip install docx2pdf
</code>```

Usage:

```<code>from docx2pdf import convert
convert("input.docx", "output.pdf")
</code>```

As you mentioned, this approach does require having Microsoft Office installed.

Disclaimer: I wrote this library and command line tool.

Body:
I am working on an env with a python function to convert docx to pdf files. I'm using postman to send base64. Then I mount the docx file (everything works yet), but when it converts the docx file into pdf, an error shows up. I'm thinking that is because I do not have Office on my env? How can I fix it without having office? Thanks.

import sys
import os
import comtypes.client
import pythoncom
import uuid
import requests
from docx import Document
import base64
from os import listdir
from os.path import isfile, join
import azure.functions as func

def main(req: func.HttpRequest) -> func.HttpResponse:
  bytesDoc = req.get_json()['base']

  path = '/users/echornet/pruebas/'
  newFile = open(path + 'prueba.docx','wb')
  newFile.write(base64.b64decode(bytesDoc))

  newFile.close()
  wdFormatPDF = 17

  out_file = path + 'prueba.pdf'
  word = comtypes.client.CreateObject('Word.Application')

  doc = word.Documents.Open(newFile)
  doc.SaveAs(out_file, FileFormat=wdFormatPDF)
  doc.Close()

This is the error I'm getting. I get the docx created from base64, but no conversion.

System.Private.CoreLib: Exception while executing function:
  Functions.FunConverter. System.Private.CoreLib: Result: Failure
  Exception: AttributeError: module 'comtypes.gen.Word' has no attribute
  '_Application' Stack:   File
  "C:\PruebaFunction\ConvEnv\lib\site-packages\azure\functions_worker\dispatcher.py",
  line 288, in _handle__invocation_request
      self.run_sync_func, invocation_id, fi.func, args)   File "C:\Users\echornet\AppData\Local\Programs\Python\Python36\lib\concurrent\futures\thread.py",
  line 55, in run
      result = self.fn(*self.args, **self.kwargs)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\azure\functions_worker\dispatcher.py",
  line 347, in __run_sync_func
      return func(**params)   File "C:\PruebaFunction\FunConverter__init.py", line 32, in main
      word = comtypes.client.CreateObject('Word.Application')   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 250, in CreateObject
      return _manage(obj, clsid, interface=interface)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 188, in _manage
      obj = GetBestInterface(obj)   File "C:\PruebaFunction\ConvEnv\lib\site-packages\comtypes\client__init__.py",
  line 112, in GetBestInterface
      interface = getattr(mod, itf_name)

Body:
You can use the python library docx2pdf which internally uses win32com: https://github.com/AlJohri/docx2pdf

Install:

pip install docx2pdf

Usage:

from docx2pdf import convert
convert("input.docx", "output.pdf")

As you mentioned, this approach does require having Microsoft Office installed.

Disclaimer: I wrote this library and command line tool.


问:
Stock candleStick chart in iOS?
I need to create Stock CandleStick chart from scratch, Because we have some complex customization about Buy, Sell and Hold signal. I have prepared all data now looking forward to see some sort of starting point, I know Object C well but not too much experience in iOS platform. Can someone refer me to a good site or library, Thanks in advance.</p>

答:
I have used core-plot in past projects. I think its pretty good. It even has several built in pre-sets for stock graphs.

http://code.google.com/p/core-plot/

Title: Stock candleStick chart in iOS?


问:
axios get function not working in Reactjs
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

```<code>app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

</code>```

and I call the API in my reactjs page component

```<code>class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList
</code>```

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

答:
First, check your API response it might look like this

 {
  "status": 200,
  "response": [{...}, {...}]
 }
```

<p>
then when receiving your data make sure you've set it to the state properly
e.g:</p>

<pre class="lang-js prettyprint-override"><code>await axios.get(Url)
  .then(enduser_tbl => {
    this.setState({
      enduser_tbl: enduser_tbl.response
    })
  })
</code>```

finally, make sure that you've destructured it properly just like xdeepkav said e.g

const { enduser_tbl } = this.state;

The error the you're encountering is because enduser_tbl can't be read as mappable data/array. To make it clear here's an example of your error

Body:
I am working on a web dev using ReactJs, NodeJs and Mysql. I got problem in displaying fetching data using axios.

here is my API :

app.get('/enduser',(req, res) => {
    let ENDUSER_QUERY = "SELECT * FROM enduser_tbl";
    let query = dbConn.query(ENDUSER_QUERY, (err, results) => {
      if(err) {
        console.log(err)
      } else {
        return res.status(200).json({"status": 200, "err" : null, "response": results});
      }
    });
  });

and I call the API in my reactjs page component

class ProjectList extends Component {
    constructor(props){
        super(props);
        this.state = {
            enduser_tbl : []
        }
    }

    async componentDidMount() {
        const Url = "http://localhost:4000/enduser"
        await axios.get(Url)
        .then( enduser_tbl => {
            console.log(enduser_tbl.data)
            this.setState({
                enduser_tbl : enduser_tbl.data
            })
        })
    }

    render() {
        const enduser_tbl = this.state;
        return (
            <Container>
                { enduser_tbl.map ((enduser, project_id) =>
                    <ListGroup>
                        <ListGroup.Item key={project_id}> {enduser.project_type} </ListGroup.Item>
                    </ListGroup>
                )}
            </Container>
        )
    }
}

export default ProjectList

I got no error in my terminal but many problem appears in Chrome. here is the response from chrome

Body:
First, check your API response it might look like this

 {
  "status": 200,
  "response": [{...}, {...}]
 }

then when receiving your data make sure you've set it to the state properly
e.g:

await axios.get(Url)
  .then(enduser_tbl => {
    this.setState({
      enduser_tbl: enduser_tbl.response
    })
  })

finally, make sure that you've destructured it properly just like xdeepkav said e.g

const { enduser_tbl } = this.state;

The error the you're encountering is because enduser_tbl can't be read as mappable data/array. To make it clear here's an example of your error


问:
How this c++ code runs without definition of function
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.</p>

```<code>#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}
</code>```

答:
That's why you shouldn't do using namespace std;, it just leads to confusion like this.

What happens is that std::swap is called instead when you do swap(x, y);.

By the way, your swap won't work. It takes int pointers, but you give it int. This wouldn't compile, you need to do swap(&x, &y); instead. It only worked because it was always using std::swap.

Body:
Can anyone explain the logic behind the working of defined function in this program. This gives the correct output in this case even after commenting the whole logic of function.

#include <iostream>
using namespace std;
void swap(int *a, int *b)
{ /*
int temp=0;
 temp= *a;
 *a= *b;
 *b=temp;
*/
}
int main()
{
    int x, y;
    cout << "This program is the demo of function call by pointer \n\n";
    cout << "Enter the value of x & y \n";
    cout << "x: ";
    cin >> x;
    cout << "y: ";
    cin >> y;
    cout << "Value befor swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    swap(x, y);
    cout << "Value after swap " << endl;
    cout << "x= " << x << " y= " << y << endl;
    return 0;
}


问:
Executing coding directives in the python interpreter
I'm using PythonQL and finding that it takes a bit of time to learn the complexities of the language, so I would like to try things out directly in the interpreter in a pythonesque way. How can I instruct the interpreter to pay attention to my coding declaration? The declaration is required to get PythonQL to understand my code. The interpreter REPL loop seems to understand the declaration by changing the prompt but it doesn't follow through with running the declaration processing. Here's some code that illustrates the problem.

```<code>$ pip install pythonql3
</code>```

... output from pip here

```<code>$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> #coding: pythonql
... x = [ select x for x in range(0,2) ]
  File "<stdin>", line 2
    x = [ select x for x in range(0,2) ]
                 ^
SyntaxError: invalid syntax
>>>
</code>```

The python interpreter ignores the coding declaration and thus "select" bombs because it is not legal python.

However, if we run the same code from a file, everything works fine because python file processing does listen to the declaration.

```<code>$ cat <<EOF > x.py
> #coding: pythonql
> x = [ select x for x in range(0,2) ]
> print(x)
> EOF
$ python x.py
[0, 1]
$
</code>```

So it would be nice to somehow direct the python interpreter to understand the coding declaration. But I haven't found a way to do that.

答:
You're making a coding declaration. It doesn't change the interpreter of the REPL, only scripts (files)

In the standard REPL, it is interpreted as a comment.

Note, your code is the same as list(range(2))

You might be able to use IPython or Jupyter instead

Body:
I'm using PythonQL and finding that it takes a bit of time to learn the complexities of the language, so I would like to try things out directly in the interpreter in a pythonesque way. How can I instruct the interpreter to pay attention to my coding declaration? The declaration is required to get PythonQL to understand my code. The interpreter REPL loop seems to understand the declaration by changing the prompt but it doesn't follow through with running the declaration processing. Here's some code that illustrates the problem.

$ pip install pythonql3

... output from pip here

$ python
Python 3.6.5 |Anaconda, Inc.| (default, Apr 26 2018, 08:42:37)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> #coding: pythonql
... x = [ select x for x in range(0,2) ]
  File "<stdin>", line 2
    x = [ select x for x in range(0,2) ]
                 ^
SyntaxError: invalid syntax
>>>

The python interpreter ignores the coding declaration and thus "select" bombs because it is not legal python.

However, if we run the same code from a file, everything works fine because python file processing does listen to the declaration.

$ cat <<EOF > x.py
> #coding: pythonql
> x = [ select x for x in range(0,2) ]
> print(x)
> EOF
$ python x.py
[0, 1]
$

So it would be nice to somehow direct the python interpreter to understand the coding declaration. But I haven't found a way to do that.


问:
Is there any separate JVM availbale for hybris?? and How to check?
I have searched through SAP help portal but I can't find anything (https://help.sap.com/viewer/product/SAP_COMMERCE/1905/en-US)</p>

答:
CX Commerce (hybris) 1905 support SapMachine 11 (SAP OpenJDK alternative).

You can search on help portal as "third party", you will find Third-Party Compatibility page.

Given information said that SapMachine required, not Oracle JDK nor OpenJDK.


问:
How to fetch data from remote oracle database Ruby on rails
I want to fetch data from a remote Oracle database and display it on my web page how do i do that ?

despite i have successfully connected to the remote database by modifying the database.yml and using SQL developer to test out the connection.

Ruby version :2.6.5
Rails version : 6.0.2.1
database version: 19c

*
I have oracle instant client setup as well as the oracle gem and i can connect to the remote database however i still can't fetch data from the remote DB

Due to this error

Puma caught this error: '{ development => }' is not a valid configuration. Expected '' to be a URL string or a Hash. (ActiveRecord::DatabaseConfigurations::InvalidConfigurationError)

my database.yml

default: &default

adapter: oracle_enhanced

pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

host: link to server

database: dbname

username: dbuser

password: dbpass

port: portnum

development:

adapter: oracle_enhanced

username: dbuser

password: dbpass

database: serverlink/dbname

答:
Install Oracle Instant Client and Ruby-OCI8

Install ActiveRecord oracle_enhanced adapter (version 1.3.1 is recommended)
gem install activerecord-oracle_enhanced-adapter

Replace the development section in the file config/database.yml with the following content and then save and close the file.

```<code>development:
    adapter: oracle_enhanced
    username: rubyhol
    password: welcome
    database: localhost/orcl
</code>```

For more details follow this link: https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/oow10/rubyhol/instructions/rubyrails.htm

Body:
Install Oracle Instant Client and Ruby-OCI8

Install ActiveRecord oracle_enhanced adapter (version 1.3.1 is recommended)
gem install activerecord-oracle_enhanced-adapter

Replace the development section in the file config/database.yml with the following content and then save and close the file.

development:
    adapter: oracle_enhanced
    username: rubyhol
    password: welcome
    database: localhost/orcl

For more details follow this link: https://www.oracle.com/webfolder/technetwork/tutorials/obe/db/oow10/rubyhol/instructions/rubyrails.htm


问:
PHP Laravel : How to get client browser/ Device?
I'm building a laravel application where I want to keep track of client browser details such as browser name.
How do I do it using Laravel ?

```<code>public function postUser(Request $request)
    {
            $user = new User();
            $user->name = $request->Input(['name']);
            $device=   $request->header('User-Agent');
            dd($device);
            $user->save();
            return redirect('userSavePage');
    }
</code>```

I have used this  $device=   $request->header('User-Agent');
But while I dd() the output I get something Like this:

```<code>"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
</code>```

How do I get actual browser details?

答:
With latest version of BrowserDetect package, you can get browser information as below:

Install using below command:

composer require hisorange/browser-detect

Once installed, add dependency in config/app.php file.

Add below line in providers array.

hisorange\BrowserDetect\ServiceProvider::class,

Add below line in alias array.

'BrowserDetect' => hisorange\BrowserDetect\Facade::class,

Include package in any class file as below to use:

use BrowserDetect;

After this you can access BrowserDetect methods as explained in below package link:

BrowserDetect package link

Body:
I'm building a laravel application where I want to keep track of client browser details such as browser name.
How do I do it using Laravel ?

public function postUser(Request $request)
    {
            $user = new User();
            $user->name = $request->Input(['name']);
            $device=   $request->header('User-Agent');
            dd($device);
            $user->save();
            return redirect('userSavePage');
    }

I have used this  $device=   $request->header('User-Agent');
But while I dd() the output I get something Like this:

"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"

How do I get actual browser details?


问:
Adobe Air how to check if folder exists?
Adobe Air (2.0) how to check if folder exists? (like folder C:\Program Files (x86) on windows) (code example needed, please)</p>

答:
```<code> import flash.filesystem.File;

 var tempFold:File = File.userDirectory.resolvePath("FolderPath");

 if(tempFold.exists)
 {
     trace("The directory exists.");
 }
 else
 {
     trace("The directory does not exists.");
 }
</code>```


问:
Use Doctrine SQLLogger in TYPO3 Backend to log all executed SQL queries
We are facing very long load times for the record list view in many pages. To understand what is causing this, we want to analyze the SQL queries executed. (Ultimately, we might want a admin panel for the backend).

Theoretically, Doctrine DBAL supports hooking SQLLogger, but we don't know where the proper Class replacement/injection for this would be.

We did find the ability to patch the file typo3/cms/typo3/sysext/core/Classes/Database/Connection.php and simply create a new method overwriting the parent:

```<code> /**
 * Debug all the things
 *
 * If the query is parametrized, a prepared statement is used.
 * If an SQLLogger is configured, the execution is logged.
 *
 * @param string                                      $query  The SQL query to execute.
 * @param array                                       $params The parameters to bind to the query, if any.
 * @param array                                       $types  The types the previous parameters are in.
 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
 *
 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
 *
 * @throws \Doctrine\DBAL\DBALException
 */
public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) {
    $fp = fopen('/var/www/html/logs/mysql.log', 'a'); fwrite($fp, '[QUERY-DOCTRINE] ' . $query . "\n"); fclose($fp);

    return parent::executeQuery($query, $params, $types, $qcp);
}
</code>```

But that approach isn't really portable and requires to patch composer-generated vendor files. Also, it's lacking proper raw logging and the abilities of sophisticated SQLLoggers. So somewhere we should be able to call the Doctrine Configuration class methods?

答:
You can modify/extend the connection class and make the database layer use yor custom class with the config option of wrapperClass that is part of the configuration for the database connection.

work in progress @medz, just created an extension.
https://packagist.org/packages/datenbetrieb/sqllog
requires some config

```<code>$GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['wrapperClass']= \Datenbetrieb\Sqllog\Database\Connection::class;
$GLOBALS['TYPO3_CONF_VARS']['LOG']['Datenbetrieb']['Sqllog']['Database']['Logging']['writerConfiguration'] = array(
    \TYPO3\CMS\Core\Log\LogLevel::DEBUG => array(
        'TYPO3\\CMS\\Core\\Log\\Writer\\FileWriter' => array(),
    ),
);
</code>```

Body:
We are facing very long load times for the record list view in many pages. To understand what is causing this, we want to analyze the SQL queries executed. (Ultimately, we might want a admin panel for the backend).

Theoretically, Doctrine DBAL supports hooking SQLLogger, but we don't know where the proper Class replacement/injection for this would be.

We did find the ability to patch the file typo3/cms/typo3/sysext/core/Classes/Database/Connection.php and simply create a new method overwriting the parent:

 /**
 * Debug all the things
 *
 * If the query is parametrized, a prepared statement is used.
 * If an SQLLogger is configured, the execution is logged.
 *
 * @param string                                      $query  The SQL query to execute.
 * @param array                                       $params The parameters to bind to the query, if any.
 * @param array                                       $types  The types the previous parameters are in.
 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
 *
 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
 *
 * @throws \Doctrine\DBAL\DBALException
 */
public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null) {
    $fp = fopen('/var/www/html/logs/mysql.log', 'a'); fwrite($fp, '[QUERY-DOCTRINE] ' . $query . "\n"); fclose($fp);

    return parent::executeQuery($query, $params, $types, $qcp);
}

But that approach isn't really portable and requires to patch composer-generated vendor files. Also, it's lacking proper raw logging and the abilities of sophisticated SQLLoggers. So somewhere we should be able to call the Doctrine Configuration class methods?

Body:
You can modify/extend the connection class and make the database layer use yor custom class with the config option of wrapperClass that is part of the configuration for the database connection.

work in progress @medz, just created an extension.
https://packagist.org/packages/datenbetrieb/sqllog
requires some config

$GLOBALS['TYPO3_CONF_VARS']['DB']['Connections']['Default']['wrapperClass']= \Datenbetrieb\Sqllog\Database\Connection::class;
$GLOBALS['TYPO3_CONF_VARS']['LOG']['Datenbetrieb']['Sqllog']['Database']['Logging']['writerConfiguration'] = array(
    \TYPO3\CMS\Core\Log\LogLevel::DEBUG => array(
        'TYPO3\\CMS\\Core\\Log\\Writer\\FileWriter' => array(),
    ),
);