问:
Using Cspice with mingw
I am trying to use cspice with  g++ for windows via mingw. Unfortunately cspice does not provide a library for mingw. The libraries are available at https://naif.jpl.nasa.gov/naif/toolkit_C.html.
It gives undefined reference errors for the functions defined through cspice. It runs properly in Linux.
Can anyone suggest a method to make it work.

I run:

g++ -LK:\Data\cspice\lib -IF:\CPP\Libraries\Boost\boost_1_68_0 -o foo foo.cpp -l:cspice.a -lm

The errors I get are:

undefined reference to 'furnsh_c'
and other functions I use from 'SpiceUsr.h'.

Am I not linking the file properly or what is the error.

答:
I managed to compile this in windows using MinGW.

I downloaded the code from NASA website for UNIX not WINDOWS.

You need to download a libf2c library, the arith.h (comment this line //#include <config.h>) header and the times.h header.

Then I use the following CMakeLists.txt with MinGW and CMAKE for windows.

```<code>mkdir build
cd build
cmake .. -G "MinGW Makefiles"
mingw32-make
</code>```

Some compilation errors will came out but they are very straightforward to solve.

```<code># CMAKE version and project name
cmake_minimum_required( VERSION 2.8.11 )
project( cspice )

# Add preprocessor directives
SET( GCC_COVERAGE_COMPILE_FLAGS "-c -ansi -m64 -O2 -fPIC -DNON_UNIX_STDIO" )
#SET( GCC_COVERAGE_LINK_FLAGS   "-lf2c -lm" )
#SET( GCC_COVERAGE_LINK_FLAGS   "-lf2c" )

SET(CMAKE_CXX_FLAGS        "${CMAKE_CXX_FLAGS}        ${GCC_COVERAGE_COMPILE_FLAGS}" )
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}" )

# Include directories
include_directories( include
                     libf2c )

file( GLOB f2c_src      "libf2c/*.c" )
file( GLOB f2c_headers  "libf2c/*.h" )

file( GLOB csupport_src     "src/csupport/*.c" )
file( GLOB csupport_headers "src/csupport/*.h" )

file( GLOB brief_src     "src/brief_c/*.c" )
file( GLOB chronos_src   "src/chrnos_c/*.c" )
file( GLOB ckbrief_src   "src/ckbref_c/*.c" )
file( GLOB commnt_src    "src/commnt_c/*.c" )
file( GLOB dskbrief_src  "src/dskbrief_c/*.c" )
file( GLOB dskexp_src    "src/dskexp_c/*.c" )
file( GLOB frmdiff_src   "src/frmdif_c/*.c" )
file( GLOB inspekt_src   "src/inspkt_c/*.c" )
file( GLOB mkdsk_src     "src/mkdsk_c/*.c" )
file( GLOB mkspk_src     "src/mkspk_c/*.c" )
file( GLOB msopck_src    "src/msopck_c/*.c" )
file( GLOB spacit_src    "src/spacit_c/*.c" )
file( GLOB spkdiff_src   "src/spkdif_c/*.c" )
file( GLOB spkmerge_src  "src/spkmrg_c/*.c" )
file( GLOB tobin_src     "src/tobin_c/*.c" )
file( GLOB toxfr_src     "src/toxfr_c/*.c" )
file( GLOB version_src   "src/versn_c/*.c" )

file( GLOB cspice_src     "src/cspice/*.c" )
file( GLOB cspice_headers "include/*.h" )

# Libraries
add_library( f2c ${f2c_src} ${f2c_header} )

add_library( csupport ${csupport_src} ${csupport_header} )

add_library( brief    ${brief_src} )
add_library( chronos  ${chronos_src} )
add_library( ckbrief  ${ckbrief_src} )
add_library( commnt   ${commnt_src} )
add_library( dskbrief ${dskbrief_src} )
add_library( dskexp   ${dskexp_src} )
add_library( frmdiff  ${frmdiff_src} )
add_library( inspekt  ${inspekt_src} )
add_library( mkdsk    ${mkdsk_src} )
add_library( mkspk    ${mkspk_src} )
add_library( msopck   ${msopck_src} )
add_library( spacit   ${spacit_src} )
add_library( spkdiff  ${spkdiff_src} )
add_library( spkmerge ${spkmerge_src} )
add_library( tobin    ${tobin_src} )
add_library( toxfr    ${toxfr_src} )
add_library( version  ${version_src} )

add_library( cspice ${cspice_src} ${cspice_headers} )

# Executable
add_executable( simple src/cook_c/simple.c )
add_executable( states src/cook_c/states.c )
add_executable( subpt  src/cook_c/subpt.c )
add_executable( tictoc src/cook_c/tictoc.c )

# Link the executable and libraries
target_link_libraries ( f2c )

target_link_libraries ( csupport f2c )

target_link_libraries ( brief    f2c )
target_link_libraries ( chronos  f2c )
target_link_libraries ( ckbrief  f2c )
target_link_libraries ( commnt   f2c )
target_link_libraries ( dskbrief f2c )
target_link_libraries ( dskexp   f2c )
target_link_libraries ( frmdiff  f2c )
target_link_libraries ( inspekt  f2c )
target_link_libraries ( mkdsk    f2c )
target_link_libraries ( mkspk    f2c )
target_link_libraries ( msopck   f2c )
target_link_libraries ( spacit   f2c )
target_link_libraries ( spkdiff  f2c )
target_link_libraries ( spkmerge f2c )
target_link_libraries ( tobin    f2c )
target_link_libraries ( toxfr    f2c )
target_link_libraries ( version  f2c )

target_link_libraries ( cspice brief chronos ckbrief commnt dskbrief dskexp frmdiff inspekt mkdsk mkspk msopck spacit spkdiff spkmerge tobin toxfr version )

target_link_libraries ( simple cspice )
target_link_libraries ( states cspice )
target_link_libraries ( subpt  cspice )
target_link_libraries ( tictoc cspice )
</code>```

Title: Using Cspice with mingw

Body:
I managed to compile this in windows using MinGW.

I downloaded the code from NASA website for UNIX not WINDOWS.

You need to download a libf2c library, the arith.h (comment this line //#include <config.h>) header and the times.h header.

Then I use the following CMakeLists.txt with MinGW and CMAKE for windows.

mkdir build
cd build
cmake .. -G "MinGW Makefiles"
mingw32-make

Some compilation errors will came out but they are very straightforward to solve.

# CMAKE version and project name
cmake_minimum_required( VERSION 2.8.11 )
project( cspice )

# Add preprocessor directives
SET( GCC_COVERAGE_COMPILE_FLAGS "-c -ansi -m64 -O2 -fPIC -DNON_UNIX_STDIO" )
#SET( GCC_COVERAGE_LINK_FLAGS   "-lf2c -lm" )
#SET( GCC_COVERAGE_LINK_FLAGS   "-lf2c" )

SET(CMAKE_CXX_FLAGS        "${CMAKE_CXX_FLAGS}        ${GCC_COVERAGE_COMPILE_FLAGS}" )
SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${GCC_COVERAGE_LINK_FLAGS}" )

# Include directories
include_directories( include
                     libf2c )

file( GLOB f2c_src      "libf2c/*.c" )
file( GLOB f2c_headers  "libf2c/*.h" )

file( GLOB csupport_src     "src/csupport/*.c" )
file( GLOB csupport_headers "src/csupport/*.h" )

file( GLOB brief_src     "src/brief_c/*.c" )
file( GLOB chronos_src   "src/chrnos_c/*.c" )
file( GLOB ckbrief_src   "src/ckbref_c/*.c" )
file( GLOB commnt_src    "src/commnt_c/*.c" )
file( GLOB dskbrief_src  "src/dskbrief_c/*.c" )
file( GLOB dskexp_src    "src/dskexp_c/*.c" )
file( GLOB frmdiff_src   "src/frmdif_c/*.c" )
file( GLOB inspekt_src   "src/inspkt_c/*.c" )
file( GLOB mkdsk_src     "src/mkdsk_c/*.c" )
file( GLOB mkspk_src     "src/mkspk_c/*.c" )
file( GLOB msopck_src    "src/msopck_c/*.c" )
file( GLOB spacit_src    "src/spacit_c/*.c" )
file( GLOB spkdiff_src   "src/spkdif_c/*.c" )
file( GLOB spkmerge_src  "src/spkmrg_c/*.c" )
file( GLOB tobin_src     "src/tobin_c/*.c" )
file( GLOB toxfr_src     "src/toxfr_c/*.c" )
file( GLOB version_src   "src/versn_c/*.c" )

file( GLOB cspice_src     "src/cspice/*.c" )
file( GLOB cspice_headers "include/*.h" )

# Libraries
add_library( f2c ${f2c_src} ${f2c_header} )

add_library( csupport ${csupport_src} ${csupport_header} )

add_library( brief    ${brief_src} )
add_library( chronos  ${chronos_src} )
add_library( ckbrief  ${ckbrief_src} )
add_library( commnt   ${commnt_src} )
add_library( dskbrief ${dskbrief_src} )
add_library( dskexp   ${dskexp_src} )
add_library( frmdiff  ${frmdiff_src} )
add_library( inspekt  ${inspekt_src} )
add_library( mkdsk    ${mkdsk_src} )
add_library( mkspk    ${mkspk_src} )
add_library( msopck   ${msopck_src} )
add_library( spacit   ${spacit_src} )
add_library( spkdiff  ${spkdiff_src} )
add_library( spkmerge ${spkmerge_src} )
add_library( tobin    ${tobin_src} )
add_library( toxfr    ${toxfr_src} )
add_library( version  ${version_src} )

add_library( cspice ${cspice_src} ${cspice_headers} )

# Executable
add_executable( simple src/cook_c/simple.c )
add_executable( states src/cook_c/states.c )
add_executable( subpt  src/cook_c/subpt.c )
add_executable( tictoc src/cook_c/tictoc.c )

# Link the executable and libraries
target_link_libraries ( f2c )

target_link_libraries ( csupport f2c )

target_link_libraries ( brief    f2c )
target_link_libraries ( chronos  f2c )
target_link_libraries ( ckbrief  f2c )
target_link_libraries ( commnt   f2c )
target_link_libraries ( dskbrief f2c )
target_link_libraries ( dskexp   f2c )
target_link_libraries ( frmdiff  f2c )
target_link_libraries ( inspekt  f2c )
target_link_libraries ( mkdsk    f2c )
target_link_libraries ( mkspk    f2c )
target_link_libraries ( msopck   f2c )
target_link_libraries ( spacit   f2c )
target_link_libraries ( spkdiff  f2c )
target_link_libraries ( spkmerge f2c )
target_link_libraries ( tobin    f2c )
target_link_libraries ( toxfr    f2c )
target_link_libraries ( version  f2c )

target_link_libraries ( cspice brief chronos ckbrief commnt dskbrief dskexp frmdiff inspekt mkdsk mkspk msopck spacit spkdiff spkmerge tobin toxfr version )

target_link_libraries ( simple cspice )
target_link_libraries ( states cspice )
target_link_libraries ( subpt  cspice )
target_link_libraries ( tictoc cspice )


来源: stackexchange

问:
Why am I getting compilation error in STS
I have opened a project in STS 3.9.5.RELEASE in mac os X, but I am getting compilation error in the editor only . But when I build the project in command line by mvn clean install , it builds fine, even in STS package explorer its shows no error when I do Maven Update. But when I click on the file and open it, it shows the error in Editor only. I think this is some kind of generated file..but not sure..

Even after doing mvn clean install is not generating the classes

答: Its generated via Java annotation processing..so it was not getting processed correctly via eclipse build...So I did a mvn clean and then mvn install separately..the artifacts are now generated and STS stopped complaining</p>

ContentLicense: CC BY-SA 4.0


问:
How to redirect from https non www to https www?
I need quick, suggestion.
My site is working https://example.com and I want to redirect it on https://www.example.com.
Please help me.</p>

答:
Put this in your .htaccess in your document root:

```<code>RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.%{HTTP_HOST}/$1 [L,R,NE]
</code>```

from https://httpd.apache.org/docs/2.4/rewrite/remapping.html

Body:
Put this in your .htaccess in your document root:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.%{HTTP_HOST}/$1 [L,R,NE]

from https://httpd.apache.org/docs/2.4/rewrite/remapping.html


问:
How I can encode a payload (application/pdf) into Base64 using Mule4 and Dataweave 2.0?
I am new to Mule4 and Dataweave 2.0 and I am having a hard time trying to convert an HTTP Request response into a Base64 value. In a few steps here is what I am doing:

Send a request to an API and outputting the response as "application/pdf"

Converting the payload to an string

"Encoding" the payload to Base64

Adding the result to an array

Here is the XML involved on the actions before:

```<code><foreach doc:name="For Each Documents in FactIntake" doc:id="6ee1729e-0280-41e6-bc29-039ad404d74d" collection="vars.factIntake.documents">
    <set-variable value="#[vars.factIntake.documents[0].documentId]" doc:name="Set documentId" doc:id="c28e1d72-bb82-43af-b340-d91b5cbc428e" variableName="docId"/>
    <http:request method="GET" doc:name="GetDocumentMetadata" doc:id="87006616-e519-4f0f-b5e2-be33c6cf5dae" config-ref="HTTP_Request_DocManagement" path="documents/{documentId}" outputMimeType="application/pdf">
        <http:uri-params><![CDATA[#[output application/java
---
{
    documentId : vars.factIntake.documents[0].documentId
}]]]></http:uri-params>
        <http:response-validator>
            <http:success-status-code-validator values="200, 404"/>
        </http:response-validator>
    </http:request>
    <choice doc:name="Condition" doc:id="76c0dc6f-3d9c-452f-960d-6bd8a0039ebc">
        <when expression="#[attributes.statusCode == 200]">
            <ee:transform doc:name="Transform Message" doc:id="ad2a1dd7-0973-4854-b44c-bdfe8eb54778">
                <ee:message>
                    <ee:set-payload><![CDATA[%dw 2.0
output application/java
---

write(payload, "text/plain")]]></ee:set-payload>
                </ee:message>
                <ee:variables>
                    <ee:set-variable variableName="documentsArray"><![CDATA[%dw 2.0
output application/java
---
vars.documentsArray + vars.document]]></ee:set-variable>
                </ee:variables>
            </ee:transform>
            <ee:transform doc:name="Transform Message" doc:id="9ef64824-ffc1-4a56-b97c-d57cc37800a5">
                <ee:message>
                    <ee:set-payload><![CDATA[%dw 2.0
import * from dw::core::Binaries
output application/java
---
vars.documentsArray + toBase64(payload)]]></ee:set-payload>
                </ee:message>
            </ee:transform>
        </when>
        <otherwise>
            <flow-ref doc:name="Document Not Found Logging" doc:id="0d6b7df4-fde1-4d77-9257-2ffe1e9f5468" name="IntegrationFabricLogsFlow"/>
        </otherwise>
    </choice>
</foreach>
</code>```

The problem? The values added to documentsArray are NULL. What I am missing here? I am running out of ideas and Google/Internet hasn't been helpful on this topic.

Any help/ideas?

答:
seems like your payload is a java object and not binary, so convert it to binary before converting to base 64</p>

```<code>%dw 2.0
import * from dw::core::Binaries
var binaryPayload = payload as Binary
output application/java
---
    vars.documentsArray + toBase64(binaryPayload)
</code>```

Body:
I am new to Mule4 and Dataweave 2.0 and I am having a hard time trying to convert an HTTP Request response into a Base64 value. In a few steps here is what I am doing:

Send a request to an API and outputting the response as "application/pdf"

Converting the payload to an string

"Encoding" the payload to Base64

Adding the result to an array

Here is the XML involved on the actions before:

<foreach doc:name="For Each Documents in FactIntake" doc:id="6ee1729e-0280-41e6-bc29-039ad404d74d" collection="vars.factIntake.documents">
    <set-variable value="#[vars.factIntake.documents[0].documentId]" doc:name="Set documentId" doc:id="c28e1d72-bb82-43af-b340-d91b5cbc428e" variableName="docId"/>
    <http:request method="GET" doc:name="GetDocumentMetadata" doc:id="87006616-e519-4f0f-b5e2-be33c6cf5dae" config-ref="HTTP_Request_DocManagement" path="documents/{documentId}" outputMimeType="application/pdf">
        <http:uri-params><![CDATA[#[output application/java
---
{
    documentId : vars.factIntake.documents[0].documentId
}]]]></http:uri-params>
        <http:response-validator>
            <http:success-status-code-validator values="200, 404"/>
        </http:response-validator>
    </http:request>
    <choice doc:name="Condition" doc:id="76c0dc6f-3d9c-452f-960d-6bd8a0039ebc">
        <when expression="#[attributes.statusCode == 200]">
            <ee:transform doc:name="Transform Message" doc:id="ad2a1dd7-0973-4854-b44c-bdfe8eb54778">
                <ee:message>
                    <ee:set-payload><![CDATA[%dw 2.0
output application/java
---

write(payload, "text/plain")]]></ee:set-payload>
                </ee:message>
                <ee:variables>
                    <ee:set-variable variableName="documentsArray"><![CDATA[%dw 2.0
output application/java
---
vars.documentsArray + vars.document]]></ee:set-variable>
                </ee:variables>
            </ee:transform>
            <ee:transform doc:name="Transform Message" doc:id="9ef64824-ffc1-4a56-b97c-d57cc37800a5">
                <ee:message>
                    <ee:set-payload><![CDATA[%dw 2.0
import * from dw::core::Binaries
output application/java
---
vars.documentsArray + toBase64(payload)]]></ee:set-payload>
                </ee:message>
            </ee:transform>
        </when>
        <otherwise>
            <flow-ref doc:name="Document Not Found Logging" doc:id="0d6b7df4-fde1-4d77-9257-2ffe1e9f5468" name="IntegrationFabricLogsFlow"/>
        </otherwise>
    </choice>
</foreach>

The problem? The values added to documentsArray are NULL. What I am missing here? I am running out of ideas and Google/Internet hasn't been helpful on this topic.

Any help/ideas?

Body:
seems like your payload is a java object and not binary, so convert it to binary before converting to base 64

%dw 2.0
import * from dw::core::Binaries
var binaryPayload = payload as Binary
output application/java
---
    vars.documentsArray + toBase64(binaryPayload)


问:
Excel VBA loop and show interactively changes
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

```<code>Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub
</code>```

Unfortunately my application freezes until it has finished..

答:
```<code>ActiveWindow.ScrollRow = Row.Row
</code>```

should do what you want

Body:
I have a VBA Application which loops through a range and does some changes.
However, I don't care much about the running time but I want to show the User that changes were made in run time.

I was thinking about something like this.

Private Sub ProcessALBODY(ByRef Fullpath, ByRef MasterWB)
...

    For Each Row In rng.rows
    ... 'Do Something

    DoEvents
    ActiveWindow.ScrollRow = 1 'for each row scrolldown and proceed to next row
    Next

...
End Sub

Unfortunately my application freezes until it has finished..

Body:
ActiveWindow.ScrollRow = Row.Row

should do what you want


问:
How to return this state
I have a function InternetStatus() like below. I call this function in the  render() through console.log but it still show undefined? How do i fix it? Thank you!</p>

```<code>function InternetStatus() {

  NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
    return (state.isConnected)
  });

}
</code>```

```<code>render() {
    console.log(InternetStatus())
    return (
        <View>
          <Text>
            hello
          </Text>
        </View>
      );
  }
}
</code>```

答:
NetInfo.fetch() is an async function which means the the InternetStatus function will resume execution and in the code above it is not returning anything hence you are getting undefined. One way to handle is to chain promises.

```<code>function InternetStatus() {

  return NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
    return (state.isConnected)
  });
}
</code>```

```<code>render() {
    InternetStatus().then(result => {
        console.log(result)
    })
    return (
        <View>
          <Text>
            hello
          </Text>
        </View>
      );
  }
}
</code>```

If you mean to use api response on the UI, then you need to force a state change.

Title: How to return this state

Body:
I have a function InternetStatus() like below. I call this function in the  render() through console.log but it still show undefined? How do i fix it? Thank you!

function InternetStatus() {

  NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
    return (state.isConnected)
  });

}

render() {
    console.log(InternetStatus())
    return (
        <View>
          <Text>
            hello
          </Text>
        </View>
      );
  }
}

Body:
NetInfo.fetch() is an async function which means the the InternetStatus function will resume execution and in the code above it is not returning anything hence you are getting undefined. One way to handle is to chain promises.

function InternetStatus() {

  return NetInfo.fetch().then(state => {
    console.log("Connection type", state.type);
    console.log("Is connected?", state.isConnected);
    return (state.isConnected)
  });
}

render() {
    InternetStatus().then(result => {
        console.log(result)
    })
    return (
        <View>
          <Text>
            hello
          </Text>
        </View>
      );
  }
}

If you mean to use api response on the UI, then you need to force a state change.


问:
how to append something to array correctly?
I'm going to make a custom cell, already have some labels on it, then I create a cell object and array, try to append that object to array then show on table, but after append, there's no content in my array's properties

I've tried to find out solutions but likely no one has these problems

//tableview implement

var recordCell : [RecordCell] = []
let note = RecordCell()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordCell.count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "recordCell",for: indexPath) as! RecordCell
        let indexPath = indexPath.row

        cell.recordFileName?.text = self.recordCell[indexPath].recordFileName?.text
        cell.recordDate?.text = self.recordCell[indexPath].recordDate?.text
        cell.delegate = self
        cell.playBtn.tag = indexPath
        return cell
    }
```

<p>//append to array</p>

<pre class="lang-swift prettyprint-override"><code>let alertController = UIAlertController(title: "請輸入錄音名稱", message: "錄音名稱", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
            var name : String = ""
            if(alertController.textFields![0].text == ""){
                name = "record"
            }else{
                name = alertController.textFields![0].text!
            }

            guard self.audioRecorder == nil else{return}
                self.recordNumber += 1
                self.record.isEnabled = false
                self.pause.isEnabled = true
                self.stop.isEnabled = true
                let destinationUrl = self.getFileURL().appendingPathComponent("\(name).m4a")

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

                do {
                    self.audioRecorder = try AVAudioRecorder(url: destinationUrl, settings: settings)
                    self.audioRecorder.record()
                    self.note.recordFileName?.text = name
                    self.note.recordDate?.text = self.getDate()
                    self.recordCell.append(self.note)
                } catch {
                    print("Record error:", error.localizedDescription)
                }

        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in
            self.dismiss(animated: true, completion: {
                self.audioRecorder.stop()
            })
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "輸入名稱"
            textField.keyboardType = .default
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.present(alertController,animated: true,completion: nil)
    }
</code>```

I expect when I append something, there's something in array

答:
After appending a new value to the array, call insertRows method like this

```<code>self.recordCell.append(self.note)
self.tableView.insertRows(at: [IndexPath(row: recordCell.count-1, section: 0)], with: .automatic)
</code>```

Body:
I'm going to make a custom cell, already have some labels on it, then I create a cell object and array, try to append that object to array then show on table, but after append, there's no content in my array's properties

I've tried to find out solutions but likely no one has these problems

//tableview implement

var recordCell : [RecordCell] = []
let note = RecordCell()

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.recordCell.count
    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "recordCell",for: indexPath) as! RecordCell
        let indexPath = indexPath.row

        cell.recordFileName?.text = self.recordCell[indexPath].recordFileName?.text
        cell.recordDate?.text = self.recordCell[indexPath].recordDate?.text
        cell.delegate = self
        cell.playBtn.tag = indexPath
        return cell
    }

//append to array

let alertController = UIAlertController(title: "請輸入錄音名稱", message: "錄音名稱", preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { (_) in
            var name : String = ""
            if(alertController.textFields![0].text == ""){
                name = "record"
            }else{
                name = alertController.textFields![0].text!
            }

            guard self.audioRecorder == nil else{return}
                self.recordNumber += 1
                self.record.isEnabled = false
                self.pause.isEnabled = true
                self.stop.isEnabled = true
                let destinationUrl = self.getFileURL().appendingPathComponent("\(name).m4a")

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

                do {
                    self.audioRecorder = try AVAudioRecorder(url: destinationUrl, settings: settings)
                    self.audioRecorder.record()
                    self.note.recordFileName?.text = name
                    self.note.recordDate?.text = self.getDate()
                    self.recordCell.append(self.note)
                } catch {
                    print("Record error:", error.localizedDescription)
                }

        }
        let cancelAction = UIAlertAction(title: "取消", style: .cancel) { (_) in
            self.dismiss(animated: true, completion: {
                self.audioRecorder.stop()
            })
        }
        alertController.addTextField { (textField) in
            textField.placeholder = "輸入名稱"
            textField.keyboardType = .default
        }
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
        self.present(alertController,animated: true,completion: nil)
    }

I expect when I append something, there's something in array

Body:
After appending a new value to the array, call insertRows method like this

self.recordCell.append(self.note)
self.tableView.insertRows(at: [IndexPath(row: recordCell.count-1, section: 0)], with: .automatic)


问:
java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value
I am trying to convert my json string to java object and I am getting error

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonInclude$Value
    at com.fasterxml.jackson.databind.cfg.MapperConfig.<clinit>(MapperConfig.java:45)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:535)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:452)
    at com.allianz.cmis.util.ApacheHttpClientGet.main(ApacheHttpClientGet.java:65)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 4 more
</code>```

Here is my json string and my code snippet

json string
{'ctpnsw': [{'abc' , 'def' }]}

Model

```<code>    public class Fields {

         private List<String> ctpnsw;

        public List<String> getCtpnsw() {
            return ctpnsw;
        }

        public void setCtpnsw(List<String> ctpnsw) {
            this.ctpnsw = ctpnsw;
        }

    }
</code>```

Java code

```<code>`ObjectMapper mapper = new ObjectMapper();
                List<Fields> list = mapper.readValue(output, TypeFactory.defaultInstance().constructCollectionType(List.class,Fields.class));
                System.out.println(list);`
</code>```

答:
Even though this answer was too late, I'm adding it because I also went through a horrible time finding answer for the same matter. Only different was, I was struggling with AWS Comprehend Medical API.

At the moment I'm writing this answer, if anyone come across the same issue with any AWS SDKs please downgrade jackson-annotaions or any jackson dependencies to 2.8.* versions.
The latest 2.9.* versions does not working properly with AWS SDK for some reason. Anyone have any idea about the reason behind that feel free to comment below.

Just in case if anyone is lazy to google maven repos, I have linked down necessary repos.Check them out!

Jackson-Core Repo

Jackson-Core-Databind - 2.8.11.3

Jackson-Core - 2.8.6

Jackson Annotations - 2.8.11

Body:
I am trying to convert my json string to java object and I am getting error

Exception in thread "main" java.lang.NoClassDefFoundError: com/fasterxml/jackson/annotation/JsonInclude$Value
    at com.fasterxml.jackson.databind.cfg.MapperConfig.<clinit>(MapperConfig.java:45)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:535)
    at com.fasterxml.jackson.databind.ObjectMapper.<init>(ObjectMapper.java:452)
    at com.allianz.cmis.util.ApacheHttpClientGet.main(ApacheHttpClientGet.java:65)
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 4 more

Here is my json string and my code snippet

json string
{'ctpnsw': [{'abc' , 'def' }]}

Model

    public class Fields {

         private List<String> ctpnsw;

        public List<String> getCtpnsw() {
            return ctpnsw;
        }

        public void setCtpnsw(List<String> ctpnsw) {
            this.ctpnsw = ctpnsw;
        }

    }

Java code

`ObjectMapper mapper = new ObjectMapper();
                List<Fields> list = mapper.readValue(output, TypeFactory.defaultInstance().constructCollectionType(List.class,Fields.class));
                System.out.println(list);`


问:
Xcode 6 Editor doesn't recognize unit tests
I have a problem that the Xcode IDE 6 doesn't detect my swift unit test cases correctly. When I run the unit tests, all tests were executed.

But in the IDE while editing the unit tests aren't recognized. I have to run the whole unit test suite in order to run a single test.

I couldn't figure out how I avoid this glitch.

答: Here is what worked for me.  Even though the unit test says it has 0 tests available, I clicked play, and then it ran through all 4 tests and then it showed.

ContentLicense: CC BY-SA 3.0


问:
Apache redirect .js request to PHP request
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

```<code><script type=\"text/javascript\" src=\"http://www.mydomain.com/generatejs.js\" charset=\"UTF-8\"></script>
</code>```

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

```<code>RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]
</code>```

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

答:
```<code>RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.+)\.js$ $1.js.php [NC,L]
</code>```

Now every smth.js file is redirected to smth.js.php

Body:
I am trying to serve a JavaScript response from a JavaScript request using PHP.

Assuming that the request is embedded into the HTML source as

And i have a PHP script that is called generatejs.js.php which outputs more JavaScript code

The Apache rewrite condition/rule are

RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^([^\.]+)$ $1.php [NC,L]

But I am getting a 404 when trying to access http://www.mydomain.com/generatejs.js. Can someone please help me with the missing bit? :)

Body:
RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.+)\.js$ $1.js.php [NC,L]

Now every smth.js file is redirected to smth.js.php


问:
Create multiple copies of an array in javascript
I want to create multiple copies of an array, copies would only be a maximum of 5. I've been trying to do it this way.

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers;
}

console.log(numbersCopy);```

But I'm getting circular object reference. How can I solve this?

答:
The variable numbers holds a reference to the array, and you are copying this reference into the new array, so you will get an array with multiple references to the same object (an array is a special type of object in Javascript). One possible solution to create a new clone of the array every time is to spread numbers into a new array:

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++)
{
    numbersCopy[i] = [...numbers];
}

console.log(numbersCopy);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Also, you can use Array.from() to do something like this:

let numbers = [1, 2, 3];
let numbersCopy = Array.from({length: 5}, _ => [...numbers]);
console.log(numbersCopy);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}</code>```

Body:
I want to create multiple copies of an array, copies would only be a maximum of 5. I've been trying to do it this way.

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++) {
  numbersCopy[i] = numbers;
}

console.log(numbersCopy);

But I'm getting circular object reference. How can I solve this?

Body:
The variable numbers holds a reference to the array, and you are copying this reference into the new array, so you will get an array with multiple references to the same object (an array is a special type of object in Javascript). One possible solution to create a new clone of the array every time is to spread numbers into a new array:

let numbers = [1, 2, 3];
let numbersCopy = [];

for (i = 0; i < 5; i++)
{
    numbersCopy[i] = [...numbers];
}

console.log(numbersCopy);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Also, you can use Array.from() to do something like this:

let numbers = [1, 2, 3];
let numbersCopy = Array.from({length: 5}, _ => [...numbers]);
console.log(numbersCopy);

.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}


问:
redirect http to https ubuntu/apache
I am trying to redirect to https, and fairly certain Ive written my htaccess correctly, but Its not redirecting for some reason. Any help is much appreciated.

#

```<code>RewriteEngine on

#### TJOSELFSTORAGE ####
RewriteCond %{ENV:CARET_ENV} live [NC]
RewriteCond %{HTTP_HOST} !^www.tjoselfstorage.com$ [NC]
RewriteCond %{HTTP_HOST} ((.*).(org|net|com)|(.*).(.*).(org|net|com)|[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}) [NC]

RewriteRule ^(.*)$ https://www.tjoselfstorage.com/$1 [R,L]

RewriteRule (^/images.*) https://www.tjoselfstorage.com? [R=301,L]

RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_FILENAME} !__\^.php
RewriteRule ^(.*)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f [OR]

RewriteCond %{REQUEST_FILENAME} !resources

RewriteCond %{REQUEST_FILENAME} !__\^.php
RewriteRule (.*) \__\^.php/$0 [L
</code>```

]

答:
This is the preferred method of redirecting http to https straight from Apache's documentation:</p>

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
</code>```

Title: redirect http to https ubuntu/apache

Body:
I am trying to redirect to https, and fairly certain Ive written my htaccess correctly, but Its not redirecting for some reason. Any help is much appreciated.

#

RewriteEngine on

#### TJOSELFSTORAGE ####
RewriteCond %{ENV:CARET_ENV} live [NC]
RewriteCond %{HTTP_HOST} !^www.tjoselfstorage.com$ [NC]
RewriteCond %{HTTP_HOST} ((.*).(org|net|com)|(.*).(.*).(org|net|com)|[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}) [NC]

RewriteRule ^(.*)$ https://www.tjoselfstorage.com/$1 [R,L]

RewriteRule (^/images.*) https://www.tjoselfstorage.com? [R=301,L]

RewriteCond %{REQUEST_URI} !^/$
RewriteCond %{REQUEST_FILENAME} !__\^.php
RewriteRule ^(.*)/$ /$1 [R=301,L]

RewriteCond %{REQUEST_FILENAME} !-f [OR]

RewriteCond %{REQUEST_FILENAME} !resources

RewriteCond %{REQUEST_FILENAME} !__\^.php
RewriteRule (.*) \__\^.php/$0 [L

]

Body:
This is the preferred method of redirecting http to https straight from Apache's documentation:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]


问:
Flask mysqldb Python DELETE table entry
I'm having an issue trying to delete data from the database. I can't find any issues with my code for deletions. Inserting data works perfectly fine, but deleting data is failing me. Here is my route which shows both inserting and deleting data.</p>

```<code>@app.route('/our-ma/addsite', methods=['POST', 'GET'])
def addsite():
    cur = mysql.connection.cursor()
    sites = cur.execute('Select * from site_info')
    data = cur.fetchall()
    cur.close()
    form = Edit_Delete()
    addForm = SiteInfo()
    if request.method == 'POST':
        if form.validate_on_submit():
            mycur = mysql.connection.cursor()
            # print("This is the site to delete:", form.site.data)
            sql = f"""delete from site_info where site_name="{{form.site.data}}"; """
            mycur.execute(sql)
            mycur.connection.commit()
            sites = mycur.execute('select * from site_info')
            data = mycur.fetchall()
            for x in data:
                print(x)
            mycur.close()
            return render_template('add_site.html', title='Add Site', data=data, form = form, addForm=addForm)

        if addForm.validate_on_submit():
            print("This addsite form is being called right now.")
            specialnotes = request.form['specialnotes']
            cur = mysql.connection.cursor()
            cur.execute(f"""INSERT INTO site_info (`site_contact`, `contact_num`, `site_name`, `printer_count`, `terminal_count`, `cd_count`, `contract_status`, `special_notes`) values ("{addForm.contact.data}", "{addForm.contactnum.data}", "{addForm.sitename.data}", "{addForm.printercount.data}", "{addForm.termcount.data}", "{addForm.cdcount.data}", "{addForm.contractstatus.data}", "{specialnotes}"); """)
            cur.connection.commit()
            x = cur.execute('SELECT * FROM site_info')
            data = cur.fetchall()
            cur.close()
            return render_template('add_site.html', title='Add site', data=data, form=form, addForm=addForm)

    return render_template('add_site.html', title='Add Site', data=data, form = form, addForm=addForm)
</code>```

答:
Your format syntax is off:

...site_name="{{form.site.data}}";...

Should be

...site_name="{form.site.data}";...

Title: Flask mysqldb Python DELETE table entry

Body:
I'm having an issue trying to delete data from the database. I can't find any issues with my code for deletions. Inserting data works perfectly fine, but deleting data is failing me. Here is my route which shows both inserting and deleting data.

@app.route('/our-ma/addsite', methods=['POST', 'GET'])
def addsite():
    cur = mysql.connection.cursor()
    sites = cur.execute('Select * from site_info')
    data = cur.fetchall()
    cur.close()
    form = Edit_Delete()
    addForm = SiteInfo()
    if request.method == 'POST':
        if form.validate_on_submit():
            mycur = mysql.connection.cursor()
            # print("This is the site to delete:", form.site.data)
            sql = f"""delete from site_info where site_name="{{form.site.data}}"; """
            mycur.execute(sql)
            mycur.connection.commit()
            sites = mycur.execute('select * from site_info')
            data = mycur.fetchall()
            for x in data:
                print(x)
            mycur.close()
            return render_template('add_site.html', title='Add Site', data=data, form = form, addForm=addForm)

        if addForm.validate_on_submit():
            print("This addsite form is being called right now.")
            specialnotes = request.form['specialnotes']
            cur = mysql.connection.cursor()
            cur.execute(f"""INSERT INTO site_info (`site_contact`, `contact_num`, `site_name`, `printer_count`, `terminal_count`, `cd_count`, `contract_status`, `special_notes`) values ("{addForm.contact.data}", "{addForm.contactnum.data}", "{addForm.sitename.data}", "{addForm.printercount.data}", "{addForm.termcount.data}", "{addForm.cdcount.data}", "{addForm.contractstatus.data}", "{specialnotes}"); """)
            cur.connection.commit()
            x = cur.execute('SELECT * FROM site_info')
            data = cur.fetchall()
            cur.close()
            return render_template('add_site.html', title='Add site', data=data, form=form, addForm=addForm)

    return render_template('add_site.html', title='Add Site', data=data, form = form, addForm=addForm)


问:
Preventing progressive download of mp3?
I'm looking for some solutions for creating an mp3 player in flash; one that either uses streaming or some kind of obfuscation to prevent users from downloading the source mp3. If I used a server/solution that used the RMTP: protocol, would that prevent the download? Are there any possibilities for using Amazon S3 server for serving the files but hiding the actual URL of the file?</p>

答:
I bet no matter what solution you come up with I can capture and save it as MP3. This assumes you expect me to actually listen to something.

So the answer is, you can't hide the data if you give your  user the data.

OwnerDisplayName: TypeOneError

ContentLicense: CC BY-SA 2.5

Title: Preventing progressive download of mp3?

OwnerDisplayName: Scott Evernden


问:
Automating workflows locally with branching logic
I've used Apache Oozie and Airflow to automate workflows in Hadoop clusters, which is easy to use for specifying branching logic.

I'm now finding myself needing the same framework to automate a simple pipeline locally, on a Linux box. This pipeline consists of Bash scripts, Python scripts, and branching & parallelization logic (which decides which and how many jobs to execute next based on the output from the previous); the output should be written to the local filesystem.

I'm trying to automate this with Oozie running locally. But I feel this might be overkill - is it? Do people actually use Oozie for simple automation tasks? Or are there better tools/frameworks for what I'm trying to do?

答:
Try out Sparrow6 - language agnostic automation framework, that runs tasks - plugins written on many languages ( Perl, Python, Bash, Ruby, Powershell ). The high level DSL is Perl6, for example:

```<code>#!perl6

directory "foo/bar"; # create directory, this is a core plugin

bash "uptime"; # execute Bash scripts, this is a core plugin

task-run "custom task", "cool-task" # execute custom plugin, created by user
</code>```

Now, when create a plugin you can return a state from it and handle this state inside DSL code:

```<code>my %state = task-run "get balance", "ATM", %( action => "get_balance" );

if %state<balance> > 0 {

  task-run "withdraw cash", "ATM", %(
    amount => %state<balance>
  )
}

</code>```

Here is the idea of how you can implement pipelines/branches through plugins and states.

Body:
Try out Sparrow6 - language agnostic automation framework, that runs tasks - plugins written on many languages ( Perl, Python, Bash, Ruby, Powershell ). The high level DSL is Perl6, for example:

#!perl6

directory "foo/bar"; # create directory, this is a core plugin

bash "uptime"; # execute Bash scripts, this is a core plugin

task-run "custom task", "cool-task" # execute custom plugin, created by user

Now, when create a plugin you can return a state from it and handle this state inside DSL code:

my %state = task-run "get balance", "ATM", %( action => "get_balance" );

if %state<balance> > 0 {

  task-run "withdraw cash", "ATM", %(
    amount => %state<balance>
  )
}

Here is the idea of how you can implement pipelines/branches through plugins and states.


问:
How to store ontology's TBOX and ABOX and where should the reasoning take place?
I am working on a semantic IoT architecture that comprises of some services some services. The goal is to add semantic annotation using an ontology which I built on Protege. I am also using Virtuoso 6 set up on an Ubuntu 18.04 server along with Jena 3.6 API (Java 8) with Pellet reasoner. I understand it is best practice to keep TBOX and ABOX split so that the reasoning and SPARQL querying should be faster, but how am I supposed to do that using Virtuoso? So given my ontology in .owl file along with all the individuals I have how am I supposed to store my TBOX and how my ABOX and at what phase should the reasoning take place?

At first  the way I built my architecture was that every time I had to make a SPARQL request I would send to Jena which would in turn take the graph that is uploaded on Virtuoso, and then make a query using the reasoner, which would eventually return the results.

My professor, however, did not agree with this approach, as he stated that it is not fast enough, and suggested I change my architecture to a one that does reasoning only when necessary and not every time I have to make a SPARQL query. So I am asking how to use Virtuoso (or any other triple store) to generally store my ontology in an efficient way.

答:
Virtuoso supports Named Graphs (since it's an RDF Quad store in its RDF DBMS aspect).

Just load your TBox Triples into one Named Graph and then your ABox Triples into another.

Reasoning and inference in Virtuoso is offered in two forms. In either case, it's controlled by pragmas; i.e., you turn it on and off as required:

Built-In -- see this post about Built-In Reasoning and Inference

Custom -- See this post about Custom Reasoning and Inference

Note: both posts demonstrate the utility of the Virtuoso approach with live examples.


答:
Use slice for a more elegant solution:

let numbers = [1, 2, 3];
let numbersCopy = numbers.slice();
console.log(numbersCopy);```

Title: Create multiple copies of an array in javascript


答:
do you understand what you are doing?  you are creating one array, and then you are populating a second array by assigning the same single pointer to the first one, to elements of the second one.  there is no circular reference here, but there's no "copying" of anything.

look: after you do what you say you do, you can alter the initial numbers array, and the change is reflected in every member of the numbersCopy.  duh.  it's all the same numbers array, obviously they all change.

what are you trying to do, really?

and where what you do isn't what you expect?


答:
For this you could also use Object.assign:

let numbers = [1, 2, 3];
let numbersCopy = Object.assign([], numbers);  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]```
</div>
</div>
</p>

<p>Or could use Array.concat:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let numbers = [1, 2, 3];
let numbersCopy = numbers.concat()  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]</code>```

Or Array.from:

let numbers = [1, 2, 3];
let numbersCopy = Array.from(numbers)  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]```
</div>
</div>
</p>

<p>And as already pointed out Array.slice and ES6 spread:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let numbers = [1, 2, 3];
let numbersCopy = numbers.slice()  // <-- shallow clone array

// or

let numbersCopy2 = [...numbers]  // <-- shallow clone array

console.log(numbersCopy)   // [1,2,3]
console.log(numbersCopy2)  // [1,2,3]</code>```

Note that this is all fine for array of primitives. With array of objects things are different since you have to individually clone each object via Object.assign / spread etc.

Body:
For this you could also use Object.assign:

let numbers = [1, 2, 3];
let numbersCopy = Object.assign([], numbers);  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]

Or could use Array.concat:

let numbers = [1, 2, 3];
let numbersCopy = numbers.concat()  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]

Or Array.from:

let numbers = [1, 2, 3];
let numbersCopy = Array.from(numbers)  // <-- shallow clone array

numbers[0] = 22  // <-- modify original array

console.log(numbersCopy)  // [1,2,3]

And as already pointed out Array.slice and ES6 spread:

let numbers = [1, 2, 3];
let numbersCopy = numbers.slice()  // <-- shallow clone array

// or

let numbersCopy2 = [...numbers]  // <-- shallow clone array

console.log(numbersCopy)   // [1,2,3]
console.log(numbersCopy2)  // [1,2,3]

Note that this is all fine for array of primitives. With array of objects things are different since you have to individually clone each object via Object.assign / spread etc.


问:
Google search console fails to fetch sitemaps | "Sitemap could not be read"
I have generated a sitemap from online generators, it seems to be working and even i tested it on old google search console sitemap testor and it works. but when i submit it in both versions it just displays error message.

答:
I had this issue and it was because I didn't set the content-type to application/xml

This sitemap validator notified me of the issue: https://www.xml-sitemaps.com/validate-xml-sitemap.html


问:
how to extended template call the other template in jinja2?
I'm calling a template in extended template.

I can't not find 'how to extended template call the other template in jinja2?'

base.html

  {% block content %}
  {% endblock %}

```

<p>child.html</p>

<pre class="lang-html prettyprint-override"><code>{% extends "base.html" %}
{% block content %}
<div class="child">
  <button class="modal"/>
  {% modal content %}
  {% endblock %}
</div>
{% endblock %}
</code>```

modal content.html

...some code

```

I want call modal content in child.html.

答:
If you're meaning you want to add the content.html into the child.html page, use include

Within child.html:

{% include 'content.html' %}

Body:
I'm calling a template in extended template.

I can't not find 'how to extended template call the other template in jinja2?'

base.html

  {% block content %}
  {% endblock %}

child.html

{% extends "base.html" %}
{% block content %}

  <button class="modal"/>
  {% modal content %}
  {% endblock %}

{% endblock %}

modal content.html

...some code

I want call modal content in child.html.


问:
Get value from Bottom Sheet Dialog Fragment
I'm starting bottomSheetDialogFragment from a fragment A.
I want to select the date from that bottomSheetDialogFragment then set it in the fragment A.

The select date is already done, I just want to get it in the fragment A to set it in some fields.

How can I get the value?
Any suggestions how to do it?

答:
override the constructor of a fragment is a bad practice as the document said:

Every fragment must have an
       * empty constructor, so it can be instantiated when restoring its
       * activity's state.

if you using another constructor that passing a callback as the param, when the fragment is resotored by the framework, your app crash

the recommend way is using viewModel and livedata.


问:
What is the difference between back button and finish ?
I am in details activity and I want to return to the home activity , what is the difference between pressing back button and calling finish method on details activity ? </p>

答:
onBackPressed:

If you are defining onBackPressed() Method in your activity it means you are overriding the
default behavior of backButton as onBackPressed() method gets called when you press back button.

If you have not Override onBackPressed() method from your Activity then,
it will invoke finish() for your Activity. You don't need to call finish() explicitly.
It will display Activity which is in the top of the Activity Stack and there is empty Stack then you will quite
from the application. If you have Override onBackPressed() method then you have to call finish() explicitly
to destroy activity.

Finish:

If you implement finish() method it intended to close current Activity. If your application don't have top backstack will redirect to android Home Screen. When calling finish() on an activity, the method onDestroy() is executed.
This method can do things like:

Dismiss any dialogs the activity was managing.

Close any cursors the activity was managing.

Close any open search dialog

Also, onDestroy() isn't a destructor. It doesn't actually destroy the object. It's just a method that's called based on a certain state.
So your instance is still alive and very well* after the superclass's onDestroy() runs and returns.Android keeps processes around in case
the user wants to restart the app, this makes the startup phase faster. The process will not be doing anything and if memory needs to be reclaimed,
the process will be killed


问:
Fatal Error while unwrapping UIImage(data: data) in Xcode
I have a tableview that is responsible for showcasing a contacts list, however whenever I attempt to load the tableview my project crashes with the error |Fatal error: Unexpectedly found nil while unwrapping an Optional value|
this is what my code regarding loading the data looks like as of right now

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",
    for: indexPath) as!TableClass
  let contacts = contact[indexPath.row]
  cell.Name.text = contacts.name
  cell.Picture.image = UIImage(data: contacts.image!, scale: 1) //this is the line of code that seems to make my project crash
  return cell
}
</code>```

I've also attempted to use a case method such as this:

```<code>if case let cell.Picture.image = UIImage(data: contacts.image!, scale: 1) {
  print("Hello")
}
</code>```

However when I attempt this the project still crashes and Xcode point to the if case let line and reports the same error

答:
You should use Optional Binding to get the optional image.</p>

```<code>if let image = contacts.image {
    cell.Picture.image = UIImage(data: image, scale: 1)
} else {
    //use default placeholder image
}
</code>```

Body:
I have a tableview that is responsible for showcasing a contacts list, however whenever I attempt to load the tableview my project crashes with the error |Fatal error: Unexpectedly found nil while unwrapping an Optional value|
this is what my code regarding loading the data looks like as of right now

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell",
    for: indexPath) as!TableClass
  let contacts = contact[indexPath.row]
  cell.Name.text = contacts.name
  cell.Picture.image = UIImage(data: contacts.image!, scale: 1) //this is the line of code that seems to make my project crash
  return cell
}

I've also attempted to use a case method such as this:

if case let cell.Picture.image = UIImage(data: contacts.image!, scale: 1) {
  print("Hello")
}

However when I attempt this the project still crashes and Xcode point to the if case let line and reports the same error

Body:
You should use Optional Binding to get the optional image.

if let image = contacts.image {
    cell.Picture.image = UIImage(data: image, scale: 1)
} else {
    //use default placeholder image
}


问:
porting a java6 swing code to java5
I have some code that uses JTabbedPane java 6 extension (it uses the method indexOfTabComponent(Component))
How can I make this code compatible with java 5?

Please don't tell me to upgrade to java 6, I can't.

答: One option would be to extend JTabbedPane circa 1.5 and implement indexOfTabComponent(Component) in your extension, then switch your code to use your new extension.

Title: porting a java6 swing code to java5


问:
How to re-enable right click so that I can inspect HTML elements in Chrome?
I am looking at a web page which has overwritten the right-click button so to display its own popup HTML element.

This prevents me from using Chrome Developer Tools to inspect elements.

Does anybody know a JavaScript snippet I could inject from the Chrome Console
to re-enable the right-click?

I am okay to break the existing 'right-click' functionality, so to be able to inspect the HTML elements easily.

答: The easiest way I found is to open the webpage in Read mode (browser that supports read mode like Safari, Firefox etc) and then copy as usual</p>


问:
docker exec command doesn't return after completing execution
I started a docker container based on an image which has a file "run.sh" in it. Within a shell script, i use docker exec as shown below

```<code>docker exec <container-id> sh /test.sh
</code>```

test.sh completes execution but docker exec does not return until i press ctrl+C. As a result, my shell script never ends. Any pointers to what might be causing this.

答:
OK, I got it.

docker stop a590382c2943

docker start a590382c2943

then will be ok.

```<code>docker exec -ti a590382c2943 echo "5"
</code>```

will return immediately, while add -it or not, no use

actually, in my program, the deamon has the std input and std output, std err. so I change my python deamon like following, things work like a charm:

```<code>if __name__ == '__main__':
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)

    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            os._exit(0)
    except OSError, e:
        print "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        os._exit(0)
    # decouple from parent environment
    #os.chdir("/")
    os.setsid()
    os.umask(0)
    #std in out err, redirect
    si = file('/dev/null', 'r')
    so = file('/dev/null', 'a+')
    se = file('/dev/null', 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())
    # do second fork
    while(True):
        try:
            pid = os.fork()
            if pid == 0:
                serve()
            if pid > 0:
                print "Server PID %d, Daemon PID: %d" % (pid, os.getpid())
                os.wait()
                time.sleep(3)
        except OSError, e:
            #print "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
            os._exit(0)
</code>```

Body:
I started a docker container based on an image which has a file "run.sh" in it. Within a shell script, i use docker exec as shown below

docker exec <container-id> sh /test.sh

test.sh completes execution but docker exec does not return until i press ctrl+C. As a result, my shell script never ends. Any pointers to what might be causing this.

Body:
OK, I got it.

docker stop a590382c2943

docker start a590382c2943

then will be ok.

docker exec -ti a590382c2943 echo "5"

will return immediately, while add -it or not, no use

actually, in my program, the deamon has the std input and std output, std err. so I change my python deamon like following, things work like a charm:

if __name__ == '__main__':
    # do the UNIX double-fork magic, see Stevens' "Advanced
    # Programming in the UNIX Environment" for details (ISBN 0201563177)

    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            os._exit(0)
    except OSError, e:
        print "fork #1 failed: %d (%s)" % (e.errno, e.strerror)
        os._exit(0)
    # decouple from parent environment
    #os.chdir("/")
    os.setsid()
    os.umask(0)
    #std in out err, redirect
    si = file('/dev/null', 'r')
    so = file('/dev/null', 'a+')
    se = file('/dev/null', 'a+', 0)
    os.dup2(si.fileno(), sys.stdin.fileno())
    os.dup2(so.fileno(), sys.stdout.fileno())
    os.dup2(se.fileno(), sys.stderr.fileno())
    # do second fork
    while(True):
        try:
            pid = os.fork()
            if pid == 0:
                serve()
            if pid > 0:
                print "Server PID %d, Daemon PID: %d" % (pid, os.getpid())
                os.wait()
                time.sleep(3)
        except OSError, e:
            #print "fork #2 failed: %d (%s)" % (e.errno, e.strerror)
            os._exit(0)


问:
Xcode Storyboard Warning not providing context: Unsupported Configuration of constraint attributes
I have this warning, which does not appear to cause any issues when running, but it has been the only warning I have for a while now, and I'd like to see it gone.

Clicking it opens the storyboard, but nothing is selected in the view hierarchy nor on the storyboard. Right clicking and clicking "view in log" does nothing. Right clicking and selecting "Open As > Source Code" crashes XCode every time.  Right clicking the storyboard from the project navigator and opening as source code does not show any warning information near the top, as other storyboard warnings I have encountered did.

I can not find any information on this warning on SO or Apple documentation. I can find other "Unsupported Configuration" warnings, but none with this type of message.

Any idea how I can find the source of and resolve this warning?

Thanks

Edit - My particular issue is a bug on Apple's part, dealing with web views, and there is no way around it.  It is mis-categorizing a warning. If you've got this error with similar results while trying to source it as I have, you may be running into the same issue: https://forums.developer.apple.com/thread/63254

However, JOM's answer is incredibly helpful for fixing what seems to be the actual intended occurrence of this warning, as well as very helpful for tracking similar issues. Seeing as how it provides the proper way of resolving this warning, and people are more likely to find this question by running into the warning and not experiencing the same issue as me, I'll mark it as correct.

And for better SEO, the warning is: "Unsupported configuration of constraint attributes. This may produce unexpected results at runtime before Xcode 5.1"

答: I'm just clean project and problem gone (cmd+k)</p>


问:
Redirect from https:// to https://www using .htaccess
I am trying to get my site to redirect all traffic to https://www.mylittleblackebook.com no matter how the URL is typed into the browser. There are six ways someone can type the URL into a browser. They are:

https://www.mylittleblackebook.com

https://mylittleblackebook.com

http://www.mylittleblackebook.com

http://mylittleblackebook.com

www.mylittleblackebook.com

mylittleblackebook.com

All of these URL’s will work EXCEPT FOR the second one. I cannot get the .htaccess file to redirect https:/mylittleblackebook.com to https://www.mylittleblackebook.com. Here is the code in my .htaccess file:

```<code>RewriteEngine on

# require SSL without mod_ssl
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

This code works for 5 out of the 6 ways. Can anyone tell me how to get it to work for all of them?

Thank you for taking the time to look this over.

答:
Your code looks correct, not sure why it doesn't work.  I would try this instead, it's in the opposite order and a bit different:</p>

```<code>RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.%{HTTP_HOST}/$1 [L,R,NE]
</code>```

Body:
I am trying to get my site to redirect all traffic to https://www.mylittleblackebook.com no matter how the URL is typed into the browser. There are six ways someone can type the URL into a browser. They are:

https://www.mylittleblackebook.com

https://mylittleblackebook.com

http://www.mylittleblackebook.com

http://mylittleblackebook.com

www.mylittleblackebook.com

mylittleblackebook.com

All of these URL’s will work EXCEPT FOR the second one. I cannot get the .htaccess file to redirect https:/mylittleblackebook.com to https://www.mylittleblackebook.com. Here is the code in my .htaccess file:

RewriteEngine on

# require SSL without mod_ssl
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

This code works for 5 out of the 6 ways. Can anyone tell me how to get it to work for all of them?

Thank you for taking the time to look this over.

Body:
Your code looks correct, not sure why it doesn't work.  I would try this instead, it's in the opposite order and a bit different:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^$
RewriteRule ^/?(.*) https://www.%{HTTP_HOST}/$1 [L,R,NE]


问:
Add event listener to all objects except for a few selected?
I'm trying to add event listener to all objects except for a few selected (the selected also have arbitrary child elements in arbitrary levels)?

I have asked this question before, but I didn't really got an answer to it. I have came close to solve it. Could you please help me with debugging it?

I'm adding an event listener to the body element called bodylistener and an event listener to the few selected elements called selectedElementsMarkTrue. The few selected elements that I don't want to execute some code, the listener selectedElementsMarkTrue performs prior to bodylistener with setTimeout function. selectedElementsMarkTrueset the variable selectedElements to true and bodylistenerchecks if selectedElements is true before execute some code. There is still something wrong with my code:

```<code>var selectedElements = false;
var bodylistener = function(){
    window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
        (function(){
            if(selectedElements == false){
                //Do some stuff
            }else{
                selectedElements = false;
            }
        });
    }, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
    selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
    this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);
</code>```

I can't get the setTimeout function to execute the underlying code?

答:
prevent event propagation by handling elements click event</p>

```<code>$('#dontAddEventListener1, #dontAddEventListener2').click( function(event){ event.preventDefault(); return false; });
</code>```

Body:
I'm trying to add event listener to all objects except for a few selected (the selected also have arbitrary child elements in arbitrary levels)?

I have asked this question before, but I didn't really got an answer to it. I have came close to solve it. Could you please help me with debugging it?

I'm adding an event listener to the body element called bodylistener and an event listener to the few selected elements called selectedElementsMarkTrue. The few selected elements that I don't want to execute some code, the listener selectedElementsMarkTrue performs prior to bodylistener with setTimeout function. selectedElementsMarkTrueset the variable selectedElements to true and bodylistenerchecks if selectedElements is true before execute some code. There is still something wrong with my code:

var selectedElements = false;
var bodylistener = function(){
    window.setTimeout(function(){//Setting timeout so that the other handler, selectedElementsMarkTrue, always performs first
        (function(){
            if(selectedElements == false){
                //Do some stuff
            }else{
                selectedElements = false;
            }
        });
    }, 10);//Could be 0, but te be sure I set 10
};
var selectedElementsMarkTrue = function(){
    selectedElements = true;
};
$('#dontAddEventListener1, #dontAddEventListener2').each(function(){
    this.addEventListener('click', selectedElementsMarkTrue, false);
});
document.body.addEventListener('click', bodylistener, false);

I can't get the setTimeout function to execute the underlying code?

Body:
prevent event propagation by handling elements click event

$('#dontAddEventListener1, #dontAddEventListener2').click( function(event){ event.preventDefault(); return false; });


问:
Cache Busting with Laravel
I've been developing a system and every time I update anything on the public folder, each computers must always clear their cache in order for it to take effect.

I've only been coding directly on to the public folder for the js and css files. When I push it to my git repository and pull it to our shared hosting through ssh after that I copy it to the public_html folder through ssh as well, all client computers still need to clear their caches manually in order for new public files to take effect. I've been studying a bit of laravel mix however I am still unsure how to actually use it in a live hosting.

I am unsure if cache busting is the right term at this time but I wanted my client computers to use the latest assets every time I update our system.

答:
You can include a version on your css and js files.</p>

```<code><link rel="stylesheet" href="{{asset('css/style.css?v=3.0')}}"> //specific versioning
<link rel="stylesheet" href="{{asset('css/style.css?v='.rand(1,99))}}"> //random .. every it treats as a new file
</code>```

Title: Cache Busting with Laravel

Body:
You can include a version on your css and js files.

<link rel="stylesheet" href="{{asset('css/style.css?v=3.0')}}"> //specific versioning
<link rel="stylesheet" href="{{asset('css/style.css?v='.rand(1,99))}}"> //random .. every it treats as a new file


问:
VBA - How to call SQL database connection from separate module
I have been digging on this but I couldn't find the solution related to it. I have a SQL database connection in a separate module (Module 5) that I wanted to call whenever I need to connect to my database from the other Module/form. This is for simplicity and single update so I don't need to go through every function to update the connection.

Database connection (Module5)

Function dbconnection()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

cnn.Open = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=casetracker; Trusted_Connection=Yes"

cnn.Close
Set cnn = Nothing

End Function
```

<p>And this is where I need to call the connection (Module2) - sends query to the database and displays result to my list box.</p>

<pre class="lang-vb prettyprint-override"><code>Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If

End Function
</code>```

答:
You can return the connection from your function:

Function dbconnection() as ADODB.connection

    Dim cnn As New ADODB.connection

    cnn.Open = "Driver={SQL Server};Server=HOLAP-IST9985\CASETRACKER;" & _
               "Database=casetracker; Trusted_Connection=Yes"

    Set dbconnection = cnn

End Function
```

<p>And then use it:</p>

<pre class="lang-vb prettyprint-override"><code>Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = dbconnection()
rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
'etc etc
</code>```

Body:
I have been digging on this but I couldn't find the solution related to it. I have a SQL database connection in a separate module (Module 5) that I wanted to call whenever I need to connect to my database from the other Module/form. This is for simplicity and single update so I don't need to go through every function to update the connection.

Database connection (Module5)

Function dbconnection()
Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset

cnn.Open = "Driver={SQL Server};Server=HOLAP-
IST9985\CASETRACKER;Database=casetracker; Trusted_Connection=Yes"

cnn.Close
Set cnn = Nothing

End Function

And this is where I need to call the connection (Module2) - sends query to the database and displays result to my list box.

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
i = 0

With maintenance_frm.maintenance_list
.Clear
Do
    .AddItem
    .List(i, 0) = rst![po_number]
    .List(i, 1) = rst![purpose]
    .List(i, 2) = rst![Vendor]
    .List(i, 3) = rst![id]

    i = i + 1
    rst.MoveNext
Loop Until rst.EOF
End With
Else
End If

End Function

Body:
You can return the connection from your function:

Function dbconnection() as ADODB.connection

    Dim cnn As New ADODB.connection

    cnn.Open = "Driver={SQL Server};Server=HOLAP-IST9985\CASETRACKER;" & _
               "Database=casetracker; Trusted_Connection=Yes"

    Set dbconnection = cnn

End Function

And then use it:

Function po_maintenance()

Dim cnn As New ADODB.connection
Dim rst As New ADODB.Recordset
Set rst = New ADODB.Recordset

Set cnn = dbconnection()
rst.Open "SELECT * FROM po_numberstbl ORDER BY [PO_Number];", cnn,
adOpenStatic
If rst.EOF = False Then
'etc etc


问:
Installing RMagick Gem Rails 3
```<code>Fetching gem metadata from https://rubygems.org/...........
Fetching gem metadata from https://rubygems.org/..
Could not find gem 'rmagick v 2.13.1 (>= 0) x86-mingw32' in the gems available o
n this machine.
</code>```

Hi I am getting message when I run bundle install below is my gemsfile

```<code>source 'https://rubygems.org'

gem 'rails', '3.2.6'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'

gem 'carrierwave'
gem 'rmagick v 2.13.1'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
 gem 'sass-rails',    '~> 3.2.3'
gem 'coffee-rails',  '~> 3.2.1'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby

gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
 gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
 # gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

 # To use debugger
# gem 'debugger'

gem 'will_paginate','~> 3.0'
</code>```

Is there another way to install the the RMagick gem in Rails 3? I installed carrierwave and need to use rmagick with it. Can I use carrierwave without rmagick?

答:
```<code>gem 'mini_magick', '~> 4.8'

bundle
</code>```

Title: Installing RMagick Gem Rails 3

Body:
Fetching gem metadata from https://rubygems.org/...........
Fetching gem metadata from https://rubygems.org/..
Could not find gem 'rmagick v 2.13.1 (>= 0) x86-mingw32' in the gems available o
n this machine.

Hi I am getting message when I run bundle install below is my gemsfile

source 'https://rubygems.org'

gem 'rails', '3.2.6'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'

gem 'carrierwave'
gem 'rmagick v 2.13.1'
# Gems used only for assets and not required
# in production environments by default.
group :assets do
 gem 'sass-rails',    '~> 3.2.3'
gem 'coffee-rails',  '~> 3.2.1'

# See https://github.com/sstephenson/execjs#readme for more supported runtimes
# gem 'therubyracer', :platforms => :ruby

gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
 gem 'bcrypt-ruby', '~> 3.0.0'

# To use Jbuilder templates for JSON
 # gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

 # To use debugger
# gem 'debugger'

gem 'will_paginate','~> 3.0'

Is there another way to install the the RMagick gem in Rails 3? I installed carrierwave and need to use rmagick with it. Can I use carrierwave without rmagick?

Body:
gem 'mini_magick', '~> 4.8'

bundle


问:
How to fix 'AttributeError: 'Person' object has no attribute '_default_manager' in Django is_valid() method
I'm using django rest and I'm trying to update my django model with the changed values from a form POST.I place the model to be updated and new data in the serializer instance.

```<code>model_serializer = serializer.PersonSerializer(queryset, request.POST)
</code>```

When performing model_serializer.is_valid() I get the error AttributeError: 'Person' object has no attribute '_default_manager'

I've looked at similar questions to this. I haven't found anything regarding a model object not having a '_default_manager'

In these questions they suggest changing the name of method/model due to conflicts. This hasn't worked for me.

```<code>class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
</code>```

```<code>class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Person()
        fields = '__all__'
</code>```

```<code>url(r'^api/personview/', views.PersonView.as_view()),
</code>```

```<code>class PersonView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'rest_person_form.html'

    def get(self, request):
        queryset = models.Person.objects.all().last()
        model_serializer = serializer.PersonSerializer(queryset)
        return Response({'serializer': model_serializer, 'queryset': queryset})

    def post(self, request):
        queryset = models.Person.objects.all().last()
        model_serializer = serializer.PersonSerializer(queryset, request.POST)
        model_serializer.is_valid()
        model_serializer.save()
        return Response({'serializer':model_serializer})
</code>```

I'm expecting the is_valid() method to pass without errors to allow me to save my updated details into my model.

答:
Attribute model is waiting for a class, not an instance.

```<code>class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Person # No () at the end
        fields = '__all__'
</code>```

Tip: If you aren't using the return from is_valid(), you could use is_valid(raise_exception=True) to raise error 400 automatically.

Body:
I'm using django rest and I'm trying to update my django model with the changed values from a form POST.I place the model to be updated and new data in the serializer instance.

model_serializer = serializer.PersonSerializer(queryset, request.POST)

When performing model_serializer.is_valid() I get the error AttributeError: 'Person' object has no attribute '_default_manager'

I've looked at similar questions to this. I haven't found anything regarding a model object not having a '_default_manager'

In these questions they suggest changing the name of method/model due to conflicts. This hasn't worked for me.

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Person()
        fields = '__all__'

url(r'^api/personview/', views.PersonView.as_view()),

class PersonView(APIView):
    renderer_classes = [TemplateHTMLRenderer]
    template_name = 'rest_person_form.html'

    def get(self, request):
        queryset = models.Person.objects.all().last()
        model_serializer = serializer.PersonSerializer(queryset)
        return Response({'serializer': model_serializer, 'queryset': queryset})

    def post(self, request):
        queryset = models.Person.objects.all().last()
        model_serializer = serializer.PersonSerializer(queryset, request.POST)
        model_serializer.is_valid()
        model_serializer.save()
        return Response({'serializer':model_serializer})

I'm expecting the is_valid() method to pass without errors to allow me to save my updated details into my model.

Body:
Attribute model is waiting for a class, not an instance.

class PersonSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Person # No () at the end
        fields = '__all__'

Tip: If you aren't using the return from is_valid(), you could use is_valid(raise_exception=True) to raise error 400 automatically.


问:
iPhone - Resizing an UIImage in less than a second on an iPhone 4
I have a 5MP image coming from the back camera. I want to downsize it to put it into an ImageView without having to wait too long (it take a logn time to the UIImageView to display a 5 MP picture). So I tried many methods to resize / resample the image to make it fit a just-screen resolution (retina one). But it take around 1 sec to downsize the image.

Would you know any optimised way to be able to resize this 5MP image to the retina 960 x 640 resolution as fast as possible, and at least at less that 0.7 sec on an iPhone 4 ?

答:
You're displaying an image in an UIImageView. I understand you want a version that is equal to the size of the screen. The way I would do it: display the original image in the UIImageView directly, this shouldn't take any noticeable amount of time.

Then in a background thread resize the same image down to the size you want and update the UIImageView as soon as that is done.

This gives you something on screen immediately while you generate an optimized version at the same time.

I don't know if you are using the original image for something else, but if you really only want the screen sized image it might be an idea to use an AVCaptureSession with a preset of AVCaptureSessionPresetHigh (see AVCaptureSession sessionPreset). This setting results in a more reasonably sized image, which might better suit your needs.


答:
You are looking for a cumulative sum:

```<code>select id, gooditem, amt,
       (2000 - sum(amt) over (partition by gooditem order by id desc)) as total_amt
from t
order by id;
</code>```

Here is a db<>fiddle.

EDIT:

If you need the total, you can calculate that with a window function as well:

```<code>select id, gooditem, amt,
       (sum(amt) over (partition by gooditem) -
        sum(amt) over (partition by gooditem order by id desc)
       ) as total_amt
from t
order by id;
</code>```

The db<>fiddle is pretty similar.

Title: group by somecolumn to get total value and sum the value in reverse order by somecolumn

Body:
Table&DDL:

|id |gooditem|amt  |
|---|--------|-----|
|1  |apple   |1000 |
|2  |apple   |2000 |
|3  |apple   |-3000|
|4  |apple   |500  |
|5  |apple   |1500 |
|6  |pen     |1000 |
|7  |pen     |2000 |
|8  |pen     |-3000|
|9  |pen     |500  |
|10 |pen     |2500 |

CREATE TABLE T
    ([id] int, [gooditem] varchar(5), [amt] int)
;

INSERT INTO T
    ([id], [gooditem], [amt])
VALUES
    (1, 'apple', 1000),
    (2, 'apple', 2000),
    (3, 'apple', -3000),
    (4, 'apple', 500),
    (5, 'apple', 1500),
    (6, 'pen', 1000),
    (7, 'pen', 2000),
    (8, 'pen', -3000),
    (9, 'pen', 500),
    (10, 'pen', 2500)
;

Test Demo Link

Logic

The total amount of product foo is 2000,pen  is 3000

Sum the amount in reverse order by ID

expected result

|id |gooditem|amt  |formula                      |total_amt|
|---|--------|-----|-----------------------------|---------|
|1  |foo     |1000 |2000-1500-500--3000-2000-1000|0        |
|2  |foo     |2000 |2000-1500-500--3000-2000     |1000     |
|3  |foo     |-3000|2000-1500-500--3000          |3000     |
|4  |foo     |500  |2000-1500-500                |0        |
|5  |foo     |1500 |2000-1500                    |500      |
|6  |pen     |1000 |3000-1500-500--3000-2000-1000|0        |
|7  |pen     |2000 |3000-1500-500--3000-2000     |1000     |
|8  |pen     |-3000|3000-1500-500--3000          |2000     |
|9  |pen     |500  |3000-1500-500                |1000        |
|10 |pen     |1500 |3000-1500                    |1500      |

My attempt & Problem

I've tried to use rownumber() to order id then and use the id sum data.
but I have problem on group by gooditem to get total value and sum the value in reverse order by somecolumn

Version

Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64)

My Answer for sql server 2008

with cte as (
    select row_number() over (partition by [gooditem] order by id desc) rnk
       ,sum(T1.amt) over (partition by T1.gooditem)  total_amt,*
    from T T1
)
,cte2 as (
    select T1.gooditem ,T1.id,T1.rnk,T1.amt ,T1.total_amt -T1.amt as total_amt  from cte T1
    where T1.rnk = 1
    union all
    select T1.gooditem ,T1.id,T1.rnk,T1.amt ,T2.total_amt - T1.amt as total_amt from cte T1
    inner join cte2 T2 on T1.[gooditem] = T2.[gooditem] and T1.rnk = T2.rnk+1
)
select T1.id,T1.gooditem,T1.amt ,T1.total_amt
from cte2 T1
order by id

db<>fiddle

Body:
You are looking for a cumulative sum:

select id, gooditem, amt,
       (2000 - sum(amt) over (partition by gooditem order by id desc)) as total_amt
from t
order by id;

Here is a db<>fiddle.

EDIT:

If you need the total, you can calculate that with a window function as well:

select id, gooditem, amt,
       (sum(amt) over (partition by gooditem) -
        sum(amt) over (partition by gooditem order by id desc)
       ) as total_amt
from t
order by id;

The db<>fiddle is pretty similar.


问:
grpc server won't release memory, is there a memory leak?
I build a grpc server with c++ and find that its memory won't be released after several requests. memory increase first, and if I keep sending requests, the memory stay at a peak value. After I stop sending requests, memory won't be released or little memory released. what's wrong with my code, memory should be released soon or keep as catch buffer?

class BaseCallData {
 public:
  BaseCallData(XFRProcessor *processor)
      : processor_(processor), status_(CallStatus::CREATE) {}
  virtual ~BaseCallData() = default;

  void Proceed() {
    if (status_ == CallStatus::CREATE) {
      status_ = CallStatus::PROCESS;
      Request();
    } else if (status_ == CallStatus::PROCESS) {
      NewCallData();

      //TODO
      OnRequest();

      Response();
      status_ = CallStatus::FINISH;
    } else if (status_ == CallStatus::FINISH) {
      delete this;
    } else {
      LOGGER_ERROR(Log::GetLog(), "wrong grpc status");
    }
  }

  template<class RpcReq, class RpcRes, class ReqData, class RspData>
  void WorkFlow(RpcReq &grpc_request,
                RpcRes &grpc_response,
                ServerContext &ctx,
                ReqData &request_data,
                RspData &response_data) {
    ErrorCode error_code = RequestReader::Instance()->ReadRequest(grpc_request, ctx, request_data);
    ReqTimer req_timer(request_data.log_id_, request_data.request_type_);
    if (error_code == OK) {
      error_code = processor_->Proceed(&request_data, &response_data, &req_timer);
      response_data.error_code = error_code;
      grpc_response = ResponseAssigner::Instance()->AssignResponse(response_data);
      if (OK == error_code) {
        req_timer.SetStatus(true);
      } else {
        LOGGER_WARN(Log::GetLog(),
                    "[REQ:{}][LOG:{}] fail to run, err[{}]",
                    request_data.GetRequestType(),
                    request_data.GetLogId(),
                    error_code);
        req_timer.SetStatus(false, std::to_string(error_code));
      }
    } else {
      LOGGER_WARN(Log::GetLog(), "fail to read request, err[{}]", error_code);
      req_timer.SetStatus(false, std::to_string(error_code));
      grpc_response.set_error_code(error_code);
      grpc_response.set_error_msg(GetErrorMsg(error_code));
    }
  }

  XFRProcessor *GetProcessor() {
    return processor_;
  }
 private:
  virtual void NewCallData() = 0;
  virtual void Request() = 0;
  virtual void Response() = 0;
  virtual void OnRequest() = 0;
  enum class CallStatus { CREATE, PROCESS, FINISH };
  CallStatus status_;
  XFRProcessor *processor_;
};

class DetectCallData : public BaseCallData {
 public:
  DetectCallData(::xfr::XFRService::AsyncService *service, ServerCompletionQueue *cq, XFRProcessor *processor)
      : BaseCallData(processor), p_service_(service), p_cq_(cq), responder_(&ctx_) {
    Proceed();
  }

  void NewCallData() override {
    new DetectCallData(p_service_, p_cq_, GetProcessor());
  }

  void Request() override {
    p_service_->RequestDetect(&ctx_, &request_, &responder_, p_cq_, p_cq_, this);
  }

  void Response() override {
    responder_.Finish(response_, Status::OK, this);
  }

  void OnRequest() override {
    WorkFlow(request_, response_, ctx_, request_data_, response_data_);
  }
 private:
  ServerContext ctx_;
  ::xfr::XFRService::AsyncService *p_service_;
  ServerCompletionQueue *p_cq_;
  ::xfr::DetectRequest request_;
  ::xfr::DetectResponse response_;
  DetectRequest request_data_;
  DetectResponse response_data_;
  ServerAsyncResponseWriter<::xfr::DetectResponse> responder_;
};

class CompareCallData : public BaseCallData {
 ...
};

class MatchCallData : public BaseCallData {
 ...
};

class XFRServer final {
 public:
  XFRServer(const XFRServer &) = delete;
  XFRServer &operator=(const XFRServer &) = delete;

  XFRServer() {
    Init();
    builder_.AddListeningPort(address_, InsecureServerCredentials());
    builder_.RegisterService(&service_);
    builder_.SetMaxReceiveMessageSize(max_receive_size_);
    builder_.SetMaxSendMessageSize(max_send_size_);

    for (int i = 0; i < thread_num_; ++i) {
      auto p_cq = builder_.AddCompletionQueue();
      v_cq_.push_back(std::move(p_cq));
    }
  }

  void Init() {
    auto grpc_config = hobot::vision::xfr::ServerConfig::GetConfig()->GetSubConfig("grpc");
    address_ = grpc_config->GetSTDStringValue("server_address");
    if (address_.empty()) {
      LOGGER_ERROR(Log::GetLog(), "fail to get server address: {}", address_);
      exit(0);
    }
    thread_num_ = grpc_config->GetIntValue("server_thread_count", 300);
    max_receive_size_ = grpc_config->GetIntValue("max_receive_message_bytes", 20971520);
    max_send_size_ = grpc_config->GetIntValue("max_send_message_bytes", 20971520);
  }

  ~XFRServer() {
    server_->Shutdown();
    //document shows that cq should always shutdown after server
    for (auto &cq : v_cq_) {
      cq->Shutdown();
    }
  }

  void HandleRpcs(ServerCompletionQueue *cq) {
    auto detect_processor = std::make_shared<DetectProcessor>();
    auto compare_processor = std::make_shared<CompareProcessor>();
    auto match_processor = std::make_shared<MatchProcessor>();
    new DetectCallData(&service_, cq, detect_processor.get());
    new CompareCallData(&service_, cq, compare_processor.get());
    new MatchCallData(&service_, cq, match_processor.get());

    void *tag{nullptr};
    bool ok{false};
    while (true) {
      if (!cq->Next(&tag, &ok)) {
        LOGGER_WARN(Log::GetLog(), "Server stream closed, quiting");
        break;
      }

      if (ok) {
        static_cast<BaseCallData *>(tag)->Proceed();
      }
    }
  }

  void run() {
    server_ = builder_.BuildAndStart();
    for (auto &cq:v_cq_) {
      v_threads_.emplace_back(
          std::thread([this, &cq] {
            HandleRpcs(cq.get());
          })
      );
    }
    LOGGER_INFO(Log::GetLog(), "grpc server start working...");

    v_threads_.emplace_back(
        std::thread([&zk_register] {
          zk_register.KeepPublished();
        })
    );

    for (auto &t: v_threads_) {
      t.join();
    }
  }

 private:
  std::string address_;
  int thread_num_;
  std::vector<std::thread> v_threads_;
  std::vector<std::unique_ptr<ServerCompletionQueue>> v_cq_;
  ::xfr::XFRService::AsyncService service_;
  std::unique_ptr<Server> server_;
  ServerBuilder builder_;

  int max_receive_size_;
  int max_send_size_;
};

```

答:
here may be one of the answer.
I didn't handle the state machine correctly.

 while (true) {
      if (!cq->Next(&tag, &ok)) {
        LOGGER_WARN(Log::GetLog(), "Server stream closed, quiting");
        break;
      }

      if (ok) {
        static_cast<BaseCallData *>(tag)->Proceed();
      }
    }
```

when ok!=true, object won't be deleted. so every time when I shutdown the client with 'ctl+c', memory leak.

Body:
here may be one of the answer.
I didn't handle the state machine correctly.

 while (true) {
      if (!cq->Next(&tag, &ok)) {
        LOGGER_WARN(Log::GetLog(), "Server stream closed, quiting");
        break;
      }

      if (ok) {
        static_cast<BaseCallData *>(tag)->Proceed();
      }
    }

when ok!=true, object won't be deleted. so every time when I shutdown the client with 'ctl+c', memory leak.


问:
Ubuntu Apache doesn't redirect http to https
im using Apache/2.2.15 (unix)
i had change the server to work on https, its work fine except a small warning, the server hostname is example and the cert CN is example.domain , so the HTTPS sign has red line on it.
im trying to redirect HTTP to HTTPS, but it's doesn't work.
i had read a lot, nothing solved it.

my httpd.conf file (only relevant part) :

```<code><virtualHost *:80>

ServerName name

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/* [NC]
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
<VirtualHost>
</code>```

my ssl.conf file is configured with virtualHost *:443 and ill post it on demand.

my error log file after the change and restart the httpd:

```<code>[error] Exception keyerror: keyerror(140406319183840,) in module 'threading' from '/usr/lib64/python2/threading.pyc' ignored
[notice] caucht SIGTERM, shutting down
[notice] suEXEC mechanism enabled (weapper: /usr/sbin/suexec)
[notice] Digest: generating secret for digest authentication...
[notice] Digest: done
[warn] mod_wsgi: compiled for paython/2.6.2
[warn] mod_wsgi:runtime using python/2.6.2
</code>```

the only thing i got from this error log is that i dont have the file /usr/lib64/python2/threading.pyc

thank you!

答:
You can solve this problem by listening on port 80 like so:

```<code>Listen 80 <VirtualHost *:80>
</code>```

Answer found in the comments from @bogin @ratskin

Body:
im using Apache/2.2.15 (unix)
i had change the server to work on https, its work fine except a small warning, the server hostname is example and the cert CN is example.domain , so the HTTPS sign has red line on it.
im trying to redirect HTTP to HTTPS, but it's doesn't work.
i had read a lot, nothing solved it.

my httpd.conf file (only relevant part) :

<virtualHost *:80>

ServerName name

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/* [NC]
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
<VirtualHost>

my ssl.conf file is configured with virtualHost *:443 and ill post it on demand.

my error log file after the change and restart the httpd:

[error] Exception keyerror: keyerror(140406319183840,) in module 'threading' from '/usr/lib64/python2/threading.pyc' ignored
[notice] caucht SIGTERM, shutting down
[notice] suEXEC mechanism enabled (weapper: /usr/sbin/suexec)
[notice] Digest: generating secret for digest authentication...
[notice] Digest: done
[warn] mod_wsgi: compiled for paython/2.6.2
[warn] mod_wsgi:runtime using python/2.6.2

the only thing i got from this error log is that i dont have the file /usr/lib64/python2/threading.pyc

thank you!

Body:
You can solve this problem by listening on port 80 like so:

Listen 80 <VirtualHost *:80>

Answer found in the comments from @bogin @ratskin