问:
How to correct a userform when error 13 is displayed in VBA?
I'm currently on a project that search in a product database all non-referenced product (blank fields). When I click on the button that opens a userform, error 13 is displayed, here is the code:

```<code>Dim i As Integer
Dim j As Integer
Dim t As Integer
Dim r As Integer

t = 1
While Feuil3.Cells(t, 1) <> ""
t = t + 1
Wend
t = t - 1

For r = 2 To t
    If Feuil3.Cells(r, 3) = "" Then
    i = 1
    While Feuil2.Cells(i, 1) <> ""
    i = i + 1
    Wend
    Feuil2.Cells(i, 1) = Feuil3.Cells(r, 2)
    End If
Next

i = 1
While Feuil2.Cells(i, 1) <> ""
i = i + 1
Wend

For j = 2 To i
    If Feuil2.Cells(j, 2) = "" Then
    list51.AddItem Feuil2.Cells(j, 1)
    End If
Next

End Sub
</code>```

It appears that the error comes from this line:If Feuil3.Cells(r, 3) = "" Then

My skills in VBA are limited, do you have any idea on how to fix this problem?

Thanks,

答:
Have a look at this. Should do the same just a lot less iteratively</p>

```<code>Dim Feuil2Rng As Range, Feuil3Rng As Range
Dim c

With Feuil3
    Set Feuil3Rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
End With
For Each c In Feuil3Rng
    If c.Offset(0, 2) = vbNullString Then
        With Feuil2
            .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1) = c.Offset(0,1)
        End With
    End If
Next

With Feuil2
    Set Feuil2Rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
End With

For Each c In Feuil2Rng
    If c.Offset(0, 1) = vbNullString Then
        list51.AddItem c.Value2
    End If
Next
</code>```

Body:
I'm currently on a project that search in a product database all non-referenced product (blank fields). When I click on the button that opens a userform, error 13 is displayed, here is the code:

Dim i As Integer
Dim j As Integer
Dim t As Integer
Dim r As Integer

t = 1
While Feuil3.Cells(t, 1) <> ""
t = t + 1
Wend
t = t - 1

For r = 2 To t
    If Feuil3.Cells(r, 3) = "" Then
    i = 1
    While Feuil2.Cells(i, 1) <> ""
    i = i + 1
    Wend
    Feuil2.Cells(i, 1) = Feuil3.Cells(r, 2)
    End If
Next

i = 1
While Feuil2.Cells(i, 1) <> ""
i = i + 1
Wend

For j = 2 To i
    If Feuil2.Cells(j, 2) = "" Then
    list51.AddItem Feuil2.Cells(j, 1)
    End If
Next

End Sub

It appears that the error comes from this line:If Feuil3.Cells(r, 3) = "" Then

My skills in VBA are limited, do you have any idea on how to fix this problem?

Thanks,

Body:
Have a look at this. Should do the same just a lot less iteratively

Dim Feuil2Rng As Range, Feuil3Rng As Range
Dim c

With Feuil3
    Set Feuil3Rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
End With
For Each c In Feuil3Rng
    If c.Offset(0, 2) = vbNullString Then
        With Feuil2
            .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row + 1, 1) = c.Offset(0,1)
        End With
    End If
Next

With Feuil2
    Set Feuil2Rng = .Range(.Cells(2, 1), .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1))
End With

For Each c In Feuil2Rng
    If c.Offset(0, 1) = vbNullString Then
        list51.AddItem c.Value2
    End If
Next


来源: stackexchange

问:
How to release GPU memory & use same buffer for different array in Pyopencl?
Following is my working code for reference:

```<code>vector = numpy.array([1, 2, 4, 8], numpy.float32) #cl.array.vec.float4
matrix = numpy.zeros((1, 4), cl.array.vec.float4)
matrix[0, 0] = (1, 2, 4, 8)
matrix[0, 1] = (16, 32, 64, 128)
matrix[0, 2] = (3, 6, 9, 12)
matrix[0, 3] = (5, 10, 15, 25)
# vector[0] = (1, 2, 4, 8)

platform=cl.get_platforms() #gets all platforms that exist on this machine
device=platform[0].get_devices(device_type=cl.device_type.GPU) #gets all GPU's that exist on first platform from platform list
context=cl.Context(devices=[device[0]]) #Creates context for all devices in the list of "device" from above. context.num_devices give number of devices in this context
print("everything good so far")
program=cl.Program(context,"""
__kernel void matrix_dot_vector(__global const float4 * matrix,__global const float *vector,__global float *result)
{
int gid = get_global_id(0);

result[gid]=dot(matrix[gid],vector[0]);
}

""" ).build()
queue=cl.CommandQueue(context)
# queue=cl.CommandQueue(context,cl_device_id device) #Context specific to a device if we plan on using multiple GPUs for parallel processing

mem_flags = cl.mem_flags
matrix_buf = cl.Buffer(context, mem_flags.READ_ONLY | mem_flags.COPY_HOST_PTR, hostbuf=matrix)
vector_buf = cl.Buffer(context, mem_flags.READ_ONLY | mem_flags.COPY_HOST_PTR, hostbuf=vector)
matrix_dot_vector = numpy.zeros(4, numpy.float32)
global_size_of_GPU= 0
destination_buf = cl.Buffer(context, mem_flags.WRITE_ONLY, matrix_dot_vector.nbytes)
# threads_size_buf = cl.Buffer(context, mem_flags.WRITE_ONLY, global_size_of_GPU.nbytes)
program.matrix_dot_vector(queue, matrix_dot_vector.shape, None, matrix_buf, vector_buf, destination_buf)

## Step #11. Move the kernel’s output data to host memory.
cl.enqueue_copy(queue, matrix_dot_vector, destination_buf)
# cl.enqueue_copy(queue, global_size_of_GPU, threads_size_buf)
print(matrix_dot_vector)
# print(global_size_of_GPU)

# COPY SAME ARRAY FROM GPU AGAIN
cl.enqueue_copy(queue, matrix_dot_vector, destination_buf)
print(matrix_dot_vector)
print('copied same array twice')
</code>```

How can i free the memory in matrix_buf & destination_buf on GPU. One is read only and other is write only.

How can i load different matrix array in same matrix_buf, without
having to create new buffer in pyopencl. I read that if I load new
data in same buffer its much faster then recreating same size
buffers each time.

Is it ok if new array that I load in old buffer
is smaller in size then the old array that was in that buffer. does
the new array have to be of exact same size of the buffer?

答:
matrix_buf.release() & destination_buf.release()  - this will release the memory assigned for respective buffers in the GPU. Its better to release memory if its of no use, in order to avoid running into memory errors. If the GPU function exits, all GPU memory is cleared by pyopencl automatically.  -{by doqtor}

cl.enqueue_copy(queue, matrix_buf, matrix_2)  - loading a new matrix_2 array into matrix_buf without recreating a new matrix buf.

It's ok to reuse existing buffer and use part of it. On the kernel side we have a control over which part we want to access.  -{by doqtor}

ContentLicense: CC BY-SA 3.0

Body:
Following is my working code for reference:

vector = numpy.array([1, 2, 4, 8], numpy.float32) #cl.array.vec.float4
matrix = numpy.zeros((1, 4), cl.array.vec.float4)
matrix[0, 0] = (1, 2, 4, 8)
matrix[0, 1] = (16, 32, 64, 128)
matrix[0, 2] = (3, 6, 9, 12)
matrix[0, 3] = (5, 10, 15, 25)
# vector[0] = (1, 2, 4, 8)

platform=cl.get_platforms() #gets all platforms that exist on this machine
device=platform[0].get_devices(device_type=cl.device_type.GPU) #gets all GPU's that exist on first platform from platform list
context=cl.Context(devices=[device[0]]) #Creates context for all devices in the list of "device" from above. context.num_devices give number of devices in this context
print("everything good so far")
program=cl.Program(context,"""
__kernel void matrix_dot_vector(__global const float4 * matrix,__global const float *vector,__global float *result)
{
int gid = get_global_id(0);

result[gid]=dot(matrix[gid],vector[0]);
}

""" ).build()
queue=cl.CommandQueue(context)
# queue=cl.CommandQueue(context,cl_device_id device) #Context specific to a device if we plan on using multiple GPUs for parallel processing

mem_flags = cl.mem_flags
matrix_buf = cl.Buffer(context, mem_flags.READ_ONLY | mem_flags.COPY_HOST_PTR, hostbuf=matrix)
vector_buf = cl.Buffer(context, mem_flags.READ_ONLY | mem_flags.COPY_HOST_PTR, hostbuf=vector)
matrix_dot_vector = numpy.zeros(4, numpy.float32)
global_size_of_GPU= 0
destination_buf = cl.Buffer(context, mem_flags.WRITE_ONLY, matrix_dot_vector.nbytes)
# threads_size_buf = cl.Buffer(context, mem_flags.WRITE_ONLY, global_size_of_GPU.nbytes)
program.matrix_dot_vector(queue, matrix_dot_vector.shape, None, matrix_buf, vector_buf, destination_buf)

## Step #11. Move the kernel’s output data to host memory.
cl.enqueue_copy(queue, matrix_dot_vector, destination_buf)
# cl.enqueue_copy(queue, global_size_of_GPU, threads_size_buf)
print(matrix_dot_vector)
# print(global_size_of_GPU)

# COPY SAME ARRAY FROM GPU AGAIN
cl.enqueue_copy(queue, matrix_dot_vector, destination_buf)
print(matrix_dot_vector)
print('copied same array twice')

How can i free the memory in matrix_buf & destination_buf on GPU. One is read only and other is write only.

How can i load different matrix array in same matrix_buf, without
having to create new buffer in pyopencl. I read that if I load new
data in same buffer its much faster then recreating same size
buffers each time.

Is it ok if new array that I load in old buffer
is smaller in size then the old array that was in that buffer. does
the new array have to be of exact same size of the buffer?


问:
force windows to have case sensitive for development
Today I spent hours to figure out what's wrong in my production environment (linux) when my project in my local (windows) is fine. I found this culprit:

```<code>import 'something' from '../App/myComponent'
</code>```

above code is running fine although my App folder is in lower case, during my development I didn't see any error, but in my product, stuffs are breaking.

How to force windows to have strict mode?

答:
While technically NTFS is case-sensitive, the insensitivity is too deep in the Win32 subsystem. I’m afraid it’s impossible to switch.

My advice is, use WSL instead. That thing is targeted towards developers, and these lxss.sys / lxcore.sys drivers will emulate Linux environment just fine, including case sensitive file system (since Win10 anniversary update).

Body:
Today I spent hours to figure out what's wrong in my production environment (linux) when my project in my local (windows) is fine. I found this culprit:

import 'something' from '../App/myComponent'

above code is running fine although my App folder is in lower case, during my development I didn't see any error, but in my product, stuffs are breaking.

How to force windows to have strict mode?


问:
Refreshing PyQt4 window
Hey I am trying to refresh the GUI window, but for some reason it does not refresh till all of the loops are finished. I read the other posts and tried their solutions but they didnt help. Can someone spot the thing that I did wrong or what I should add? The code is below, reads certain values from a json file and stores them in the GUI table. I am using PyQt4 and python 2.7. Thank you in advance.

```<code>import sys
from PyQt4 import QtCore, QtGui
import time
from PyQt4.QtGui import QApplication
import json
import threading

from GUI_Window import *
LastCommandTime=0

class MyForm(QtGui.QMainWindow):
   def __init__(self, parent=None):
      QtGui.QWidget.__init__(self, parent)
      self.ui = Ui_MainWindow()
      self.ui.setupUi(self)
      self.ui.button.clicked.connect(self.DataCollection)
   def DataCollection(self):
      print "button clicked"
      task1=threading.Thread(target=self.DisplayCommand)
      task1.start()
      task2=threading.Thread(target=self.DisplayTemp)
      task2.start()
      task1.join()
      task2.join()
   def DisplayCommand(self):
      start=time.time()
      with open("20170602153617003.log") as f:
         for line in f:
            data = []
            data=json.loads(line)
            try:
                if data['TYPE']== "             cmd":
                    command= data["command"]
                    print "1"
                    self.ui.command_table.setItem(0,0, QtGui.QTableWidgetItem(command["cmd_name"]))
                    self.ui.command_table.setItem(0,1, QtGui.QTableWidgetItem(command["opcode"]))
                    self.ui.command_table.setItem(0,2, QtGui.QTableWidgetItem("".join((str(x)+',') for x in command["param_type_list"])))
                    self.ui.command_table.setItem(0,3, QtGui.QTableWidgetItem("".join((str(x)+',') for x in command["param_val_list"])))
                    self.ui.commands_time.display((time.time()-start))
                    start=time.time()
                    time.sleep(1)
                if data['TYPE']== "       cmd_reply":
                    command= data["response"]
                    self.ui.reply_table.setItem(0,0, QtGui.QTableWidgetItem(data["cmd_name"].replace(" ","")))
                    self.ui.reply_table.setItem(0,1, QtGui.QTableWidgetItem("0x%02x"%command["opcode"]))
                    self.ui.reply_table.setItem(0,2, QtGui.QTableWidgetItem(str(command["error_control_type"])))
                    self.ui.reply_table.setItem(0,3, QtGui.QTableWidgetItem(str(command["data_present"])))
                    self.ui.reply_table.setItem(0,4, QtGui.QTableWidgetItem(str(command["command_reply"])))
                    self.ui.reply_table.setItem(0,5, QtGui.QTableWidgetItem(str(command["status_flags"])))
                    self.ui.reply_table.setItem(0,6, QtGui.QTableWidgetItem(str(command["condition_code"])))
                    self.ui.reply_table.setItem(0,7, QtGui.QTableWidgetItem(str(command["data_length"])))
                    self.ui.reply_table.setItem(0,8, QtGui.QTableWidgetItem(str(command["data"])))
                    self.ui.reply_table.setItem(0,9, QtGui.QTableWidgetItem(str(command["error_control"])))
                    flags=command['flags']
                    self.ui.replyflg_table.setItem(0,0, QtGui.QTableWidgetItem(str(flags["BOOT_FAIL"])))
                    self.ui.replyflg_table.setItem(0,1, QtGui.QTableWidgetItem(str(flags["BOOT_SOURCE"])))
                    self.ui.replyflg_table.setItem(0,2, QtGui.QTableWidgetItem(str(flags["COMM_SIDE"])))
                    self.ui.replyflg_table.setItem(0,3, QtGui.QTableWidgetItem(str(flags["SELF_TEST_FAIL"])))
                    self.ui.replyflg_table.setItem(0,4, QtGui.QTableWidgetItem(str(flags["STA_ERROR"])))
                    self.ui.replyflg_table.setItem(0,5, QtGui.QTableWidgetItem(str(flags["SPECTROMETER_ERROR"])))
                    self.ui.replyflg_table.setItem(0,6, QtGui.QTableWidgetItem(str(flags["SCCD_READY"])))
                    self.ui.replyflg_table.setItem(0,7, QtGui.QTableWidgetItem(str(flags["SCANNER_ON"])))
                    self.ui.replyflg_table.setItem(0,8, QtGui.QTableWidgetItem(str(flags["SCANNER_COMM_ERROR"])))
                    self.ui.replyflg_table.setItem(0,9, QtGui.QTableWidgetItem(str(flags["SCANNER_HOME_ERROR"])))
                    self.ui.replyflg_table.setItem(0,10, QtGui.QTableWidgetItem(str(flags["ERROR_LOG_NOT_EMPTY"])))
                    self.ui.replyflg_table.setItem(0,11, QtGui.QTableWidgetItem(str(flags["SEND_EVR"])))
                    self.ui.replyflg_table.setItem(0,12, QtGui.QTableWidgetItem(str(flags["SYS_ERROR"])))
                    self.ui.replyflg_table.setItem(0,13, QtGui.QTableWidgetItem(str(flags["UNDEFINED0"])))
                    self.ui.replyflg_table.setItem(0,14, QtGui.QTableWidgetItem(str(flags["UNDEFINED1"])))
                time.sleep(.1)
            except KeyError:
                time.sleep(.1)
                pass
            QApplication.processEvents()

    def DisplayTemp(self):
       i=0
       while i<10:
           print "hi"
           self.ui.flt_table.setItem(0,0, QtGui.QTableWidgetItem(str(i)))
           i=i+1
           QApplication.processEvents()
           time.sleep(.2)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    graphTimer = QtCore.QTimer()
    graphTimer.timeout.connect(app.processEvents)
    graphTimer.start(0.1)
    myapp.show()
    sys.exit(app.exec_())
</code>```

Also it appears that if I comment out the DisplayTemp() then it works just fine. I was thinking that the number of threads might be causing trouble but I am not sure how to fix it.

答: Apparently it was caused by the .join commands. They are blocking so apparently they stop the GUI from refreshing at some level. I hope this helps someone out in the future.</p>

Title: Refreshing PyQt4 window

Body:
Hey I am trying to refresh the GUI window, but for some reason it does not refresh till all of the loops are finished. I read the other posts and tried their solutions but they didnt help. Can someone spot the thing that I did wrong or what I should add? The code is below, reads certain values from a json file and stores them in the GUI table. I am using PyQt4 and python 2.7. Thank you in advance.

import sys
from PyQt4 import QtCore, QtGui
import time
from PyQt4.QtGui import QApplication
import json
import threading

from GUI_Window import *
LastCommandTime=0

class MyForm(QtGui.QMainWindow):
   def __init__(self, parent=None):
      QtGui.QWidget.__init__(self, parent)
      self.ui = Ui_MainWindow()
      self.ui.setupUi(self)
      self.ui.button.clicked.connect(self.DataCollection)
   def DataCollection(self):
      print "button clicked"
      task1=threading.Thread(target=self.DisplayCommand)
      task1.start()
      task2=threading.Thread(target=self.DisplayTemp)
      task2.start()
      task1.join()
      task2.join()
   def DisplayCommand(self):
      start=time.time()
      with open("20170602153617003.log") as f:
         for line in f:
            data = []
            data=json.loads(line)
            try:
                if data['TYPE']== "             cmd":
                    command= data["command"]
                    print "1"
                    self.ui.command_table.setItem(0,0, QtGui.QTableWidgetItem(command["cmd_name"]))
                    self.ui.command_table.setItem(0,1, QtGui.QTableWidgetItem(command["opcode"]))
                    self.ui.command_table.setItem(0,2, QtGui.QTableWidgetItem("".join((str(x)+',') for x in command["param_type_list"])))
                    self.ui.command_table.setItem(0,3, QtGui.QTableWidgetItem("".join((str(x)+',') for x in command["param_val_list"])))
                    self.ui.commands_time.display((time.time()-start))
                    start=time.time()
                    time.sleep(1)
                if data['TYPE']== "       cmd_reply":
                    command= data["response"]
                    self.ui.reply_table.setItem(0,0, QtGui.QTableWidgetItem(data["cmd_name"].replace(" ","")))
                    self.ui.reply_table.setItem(0,1, QtGui.QTableWidgetItem("0x%02x"%command["opcode"]))
                    self.ui.reply_table.setItem(0,2, QtGui.QTableWidgetItem(str(command["error_control_type"])))
                    self.ui.reply_table.setItem(0,3, QtGui.QTableWidgetItem(str(command["data_present"])))
                    self.ui.reply_table.setItem(0,4, QtGui.QTableWidgetItem(str(command["command_reply"])))
                    self.ui.reply_table.setItem(0,5, QtGui.QTableWidgetItem(str(command["status_flags"])))
                    self.ui.reply_table.setItem(0,6, QtGui.QTableWidgetItem(str(command["condition_code"])))
                    self.ui.reply_table.setItem(0,7, QtGui.QTableWidgetItem(str(command["data_length"])))
                    self.ui.reply_table.setItem(0,8, QtGui.QTableWidgetItem(str(command["data"])))
                    self.ui.reply_table.setItem(0,9, QtGui.QTableWidgetItem(str(command["error_control"])))
                    flags=command['flags']
                    self.ui.replyflg_table.setItem(0,0, QtGui.QTableWidgetItem(str(flags["BOOT_FAIL"])))
                    self.ui.replyflg_table.setItem(0,1, QtGui.QTableWidgetItem(str(flags["BOOT_SOURCE"])))
                    self.ui.replyflg_table.setItem(0,2, QtGui.QTableWidgetItem(str(flags["COMM_SIDE"])))
                    self.ui.replyflg_table.setItem(0,3, QtGui.QTableWidgetItem(str(flags["SELF_TEST_FAIL"])))
                    self.ui.replyflg_table.setItem(0,4, QtGui.QTableWidgetItem(str(flags["STA_ERROR"])))
                    self.ui.replyflg_table.setItem(0,5, QtGui.QTableWidgetItem(str(flags["SPECTROMETER_ERROR"])))
                    self.ui.replyflg_table.setItem(0,6, QtGui.QTableWidgetItem(str(flags["SCCD_READY"])))
                    self.ui.replyflg_table.setItem(0,7, QtGui.QTableWidgetItem(str(flags["SCANNER_ON"])))
                    self.ui.replyflg_table.setItem(0,8, QtGui.QTableWidgetItem(str(flags["SCANNER_COMM_ERROR"])))
                    self.ui.replyflg_table.setItem(0,9, QtGui.QTableWidgetItem(str(flags["SCANNER_HOME_ERROR"])))
                    self.ui.replyflg_table.setItem(0,10, QtGui.QTableWidgetItem(str(flags["ERROR_LOG_NOT_EMPTY"])))
                    self.ui.replyflg_table.setItem(0,11, QtGui.QTableWidgetItem(str(flags["SEND_EVR"])))
                    self.ui.replyflg_table.setItem(0,12, QtGui.QTableWidgetItem(str(flags["SYS_ERROR"])))
                    self.ui.replyflg_table.setItem(0,13, QtGui.QTableWidgetItem(str(flags["UNDEFINED0"])))
                    self.ui.replyflg_table.setItem(0,14, QtGui.QTableWidgetItem(str(flags["UNDEFINED1"])))
                time.sleep(.1)
            except KeyError:
                time.sleep(.1)
                pass
            QApplication.processEvents()

    def DisplayTemp(self):
       i=0
       while i<10:
           print "hi"
           self.ui.flt_table.setItem(0,0, QtGui.QTableWidgetItem(str(i)))
           i=i+1
           QApplication.processEvents()
           time.sleep(.2)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    graphTimer = QtCore.QTimer()
    graphTimer.timeout.connect(app.processEvents)
    graphTimer.start(0.1)
    myapp.show()
    sys.exit(app.exec_())

Also it appears that if I comment out the DisplayTemp() then it works just fine. I was thinking that the number of threads might be causing trouble but I am not sure how to fix it.


问:
Merge strings in javascript
I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?

For example:

```<code>var a = "abc"
var b = "def"

result = "adbecf"
</code>```

答:
If your strings are the same length, this will work. If not you'll have to append the rest of the longer string after the loop. You can declare i outside of the loop and then use substr() to get the end of the longer string.

const a = "abc"
const b = "def"

var res = "";
for (var i = 0;i < Math.min(a.length, b.length); i++) {
  res += a.charAt(i) + b.charAt(i)
}

console.log(res)```

Title: Merge strings in javascript

Body:
I want to merge two variable with stings alternately using javascript. What would be an algorithm to accomplish this task?

For example:

var a = "abc"
var b = "def"

result = "adbecf"


问:
Error: not found - missing when clicking on DB (Couchdb)
I am trying to view a Couchdb database in the browser named event_db. However, when I navigate to the following url: http://localhost:5984/_utils/database.html?event_db I get the an Error: not found missing and my url automatically redirects to http://localhost:5984/_utils/database.html?event_db/_changes.

This problem seemed to occur after I added _changes to the url and created a script checking the database for change here: couchdb-python change notifications

Has anyone ever experienced this problem? If so, how would I fix it?

My apologies I am new to Couchdb.

Thank you for your help,

Brian

答: Turns out I needed to clear my cache in my browser. After I did this, I was able to successfully navigate to the event_db.


问:
Couldn't load shared library 'gdx' for target
I'm having the same issue as in this question, but the answers there doesn't solve my problem.

I didn't create project by gdxsetup.jar, I just included gdx.jar and gdx-backend-android.jar. I added the libgdx.so to libs/x86, but it stills throws an exception. How should I solve this?

Logcat:

```<code>02-16 11:59:45.604: E/AndroidRuntime(14788): FATAL EXCEPTION: main
02-16 11:59:45.604: E/AndroidRuntime(14788): java.lang.ExceptionInInitializerError
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Class.newInstanceImpl(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Class.newInstance(Class.java:1130)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.os.Looper.loop(Looper.java:176)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.main(ActivityThread.java:5419)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.reflect.Method.invokeNative(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.reflect.Method.invoke(Method.java:525)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at dalvik.system.NativeStart.main(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788): Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load shared library 'gdx' for target: Linux, 32-bit
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:114)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.GdxNativesLoader.load(GdxNativesLoader.java:34)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.backends.android.AndroidApplication.<clinit>(AndroidApplication.java:62)
02-16 11:59:45.604: E/AndroidRuntime(14788):    ... 15 more
02-16 11:59:45.604: E/AndroidRuntime(14788): Caused by: java.lang.UnsatisfiedLinkError: Couldn't load gdx from loader dalvik.system.PathClassLoader[dexPath=/data/app/com.example.gamr-1.apk,libraryPath=/data/app-lib/com.example.gamr-1]: findLibrary returned null
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Runtime.loadLibrary(Runtime.java:355)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.System.loadLibrary(System.java:525)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:110)
02-16 11:59:45.604: E/AndroidRuntime(14788):    ... 17 more
</code>```

If it helps, I'm running 32-bit Linux.

答:
My problem was that I was trying to make my GDX app within a shared library (aka, not the thing that gets compiled into an APK), but hadn't finished setting up all the GDX-including stuff in my lib.

So I had:

```<code>MyProject
-->MyMainApp
-->-->build.gradle <-- no updates required, doesn't do anything with GDX
-->MySharedLibraryWhereMyGameEngineIs
-->-->build.gradle <-- this is where the problem was
</code>```

In the shared lib's build.gradle, I hadn't included the sourceSets parameter.

Adding it fixed my problem.  GDX now starts up successfully.

```<code>apply plugin: 'com.android.library'
android {
    ... config stuff ...

    sourceSets {                       // this wasn't here before
        main {                         // this wasn't here before
            jniLibs.srcDirs = ['libs'] // this wasn't here before
        }                              // this wasn't here before
        instrumentTest.setRoot('tests')// this wasn't here before
    }

    ... a bunch of other config stuff ...
}
</code>```

Body:
I'm having the same issue as in this question, but the answers there doesn't solve my problem.

I didn't create project by gdxsetup.jar, I just included gdx.jar and gdx-backend-android.jar. I added the libgdx.so to libs/x86, but it stills throws an exception. How should I solve this?

Logcat:

02-16 11:59:45.604: E/AndroidRuntime(14788): FATAL EXCEPTION: main
02-16 11:59:45.604: E/AndroidRuntime(14788): java.lang.ExceptionInInitializerError
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Class.newInstanceImpl(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Class.newInstance(Class.java:1130)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2349)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.access$700(ActivityThread.java:159)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.os.Looper.loop(Looper.java:176)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at android.app.ActivityThread.main(ActivityThread.java:5419)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.reflect.Method.invokeNative(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.reflect.Method.invoke(Method.java:525)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at dalvik.system.NativeStart.main(Native Method)
02-16 11:59:45.604: E/AndroidRuntime(14788): Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load shared library 'gdx' for target: Linux, 32-bit
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:114)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.GdxNativesLoader.load(GdxNativesLoader.java:34)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.backends.android.AndroidApplication.<clinit>(AndroidApplication.java:62)
02-16 11:59:45.604: E/AndroidRuntime(14788):    ... 15 more
02-16 11:59:45.604: E/AndroidRuntime(14788): Caused by: java.lang.UnsatisfiedLinkError: Couldn't load gdx from loader dalvik.system.PathClassLoader[dexPath=/data/app/com.example.gamr-1.apk,libraryPath=/data/app-lib/com.example.gamr-1]: findLibrary returned null
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.Runtime.loadLibrary(Runtime.java:355)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at java.lang.System.loadLibrary(System.java:525)
02-16 11:59:45.604: E/AndroidRuntime(14788):    at com.badlogic.gdx.utils.SharedLibraryLoader.load(SharedLibraryLoader.java:110)
02-16 11:59:45.604: E/AndroidRuntime(14788):    ... 17 more

If it helps, I'm running 32-bit Linux.

Body:
My problem was that I was trying to make my GDX app within a shared library (aka, not the thing that gets compiled into an APK), but hadn't finished setting up all the GDX-including stuff in my lib.

So I had:

MyProject
-->MyMainApp
-->-->build.gradle <-- no updates required, doesn't do anything with GDX
-->MySharedLibraryWhereMyGameEngineIs
-->-->build.gradle <-- this is where the problem was

In the shared lib's build.gradle, I hadn't included the sourceSets parameter.

Adding it fixed my problem.  GDX now starts up successfully.

apply plugin: 'com.android.library'
android {
    ... config stuff ...

    sourceSets {                       // this wasn't here before
        main {                         // this wasn't here before
            jniLibs.srcDirs = ['libs'] // this wasn't here before
        }                              // this wasn't here before
        instrumentTest.setRoot('tests')// this wasn't here before
    }

    ... a bunch of other config stuff ...
}


问:
How to manage configuration for Webpack/Electron app?
I am using Webpack 2 and Electron to build nodejs application on Mac.

In my project in the root I have directory 'data' where I store configuration in a json like data/configurations/files.json (in practices there are different files with dynamic names)

After webpackaing though when I call: fs.readdirSync(remote.app.getAppPath()); to get files in the root I get only these packed: [ "default_app.js", "icon.png", "index.html", "main.js", "package.json", "renderer.js" ]

path.join(remote.app.getAppPath(), 'data/tests/groups.json'); called with FS ReadSync leads to an issue Error: ENOENT, data/tests/groups.json not found in /Users/myuser/myproject/node_modules/electron/dist/Electron.app/Contents/Resources/default_app.asar. So it seems that the whole data folder is not picked up by webpacker.

Webpack config is using json-loader and I did not find any documentation mentioning anything special about including specific files or jsons. Or do I have to reference json files in my code differently as they might be packed under main.js.

What is the best practice for Electron/Webpack for managing JSON config files? Am I doing something wrong when webpacking the project?

My project is based of https://github.com/SimulatedGREG/electron-vue using webpack/electron/vue

答:
Webpack design philosophy is focused around very simple yet powerful concept:

Transform and bundle everything that is actually used by your app.

To achieve that webpack introduces a powerful concept of dependency graph, which is able to manage virtually any kind of dependencies (not only *.js modules) by the means of so-called loaders.

The purpose of a loader is to transform your dependency in a way that makes statement import smth from 'your_dependency' meaningful. For instance, json-loader calls JSON.parse(...) during loading of *.json file and returns configuration object. Therefore, in order to  take advantage of webpack dependency resolution system for managing JSONs, start from installing json-loader:

```<code>$ npm install --save-dev json-loader
</code>```

Then modify your webpack.config.js in the following way:

```<code>module.exports = {
  ...
  module: {
    rules: [
      {test: /\.json$/, use: 'json-loader'}
    ]
  }
  ...
};
</code>```

At this point webpack should be able to resolve your JSON dependencies by their absolute paths, so the following should work (I assume here that you have a subdirectory config of your root context dir, containing file sample.json):

```<code>import sampleCfg from './config/sample.json';
</code>```

But importing physical paths doesn't lead to elegant, robust and maintainable code (think of testability, for example), so it is considered a good practice to add aliases to your webpack.config.js for abstracting away your physical .config/ folder from your import statements

```<code>module.exports = {
  ...
  resolve: {
    alias: {
      cfg: './config'
    }
  }
  ...
}
</code>```

Then you'll be able to import your JSON config like that:

```<code>import sampleCfg from 'cfg/sample.json'
</code>```

Finally, if you use SimulatedGREG/electron-vue Electron project template (as you mentioned in your post), then you have three webpack configuration files:

.electron-vue/webpack.web.config.js - use this config file if you use this template just for ordinary web development (i.e. not for building native Electron projects);

.electron-vue/webpack.main.config.js - use this file to configure webpack module that will run inside Electron's main process;

.electron-vue/webpack.renderer.config.js - use this file for Electron's renderer process.

You can find more information on main and renderer processes in the official Electron documentation.

Body:
Webpack design philosophy is focused around very simple yet powerful concept:

Transform and bundle everything that is actually used by your app.

To achieve that webpack introduces a powerful concept of dependency graph, which is able to manage virtually any kind of dependencies (not only *.js modules) by the means of so-called loaders.

The purpose of a loader is to transform your dependency in a way that makes statement import smth from 'your_dependency' meaningful. For instance, json-loader calls JSON.parse(...) during loading of *.json file and returns configuration object. Therefore, in order to  take advantage of webpack dependency resolution system for managing JSONs, start from installing json-loader:

$ npm install --save-dev json-loader

Then modify your webpack.config.js in the following way:

module.exports = {
  ...
  module: {
    rules: [
      {test: /\.json$/, use: 'json-loader'}
    ]
  }
  ...
};

At this point webpack should be able to resolve your JSON dependencies by their absolute paths, so the following should work (I assume here that you have a subdirectory config of your root context dir, containing file sample.json):

import sampleCfg from './config/sample.json';

But importing physical paths doesn't lead to elegant, robust and maintainable code (think of testability, for example), so it is considered a good practice to add aliases to your webpack.config.js for abstracting away your physical .config/ folder from your import statements

module.exports = {
  ...
  resolve: {
    alias: {
      cfg: './config'
    }
  }
  ...
}

Then you'll be able to import your JSON config like that:

import sampleCfg from 'cfg/sample.json'

Finally, if you use SimulatedGREG/electron-vue Electron project template (as you mentioned in your post), then you have three webpack configuration files:

.electron-vue/webpack.web.config.js - use this config file if you use this template just for ordinary web development (i.e. not for building native Electron projects);

.electron-vue/webpack.main.config.js - use this file to configure webpack module that will run inside Electron's main process;

.electron-vue/webpack.renderer.config.js - use this file for Electron's renderer process.

You can find more information on main and renderer processes in the official Electron documentation.


问:
Pentaho Spoon Simultaneous execution of same Job
We have created a single Job in pentaho. We want to run this same job from .kjb file multiple times passing different parameters from command line. But as the code is a single source file, we are not able to execute in parallel. What is the solution for running single pentaho job in parallel?</p>

答:
1) You can use a wrapper Pentaho job that calls the same .kjb multiple times with different parameters. In this scenario you'd use the "Run Next Entries in Parallel" setting as it's described here: http://wiki.pentaho.com/display/EAI/Launching+job+entries+in+parallel

2) If you're using kitchen to run .kjb from the command line, you can take care about parallel execution in the shell script itself.


答:
The best way to do this is to perform the following algorithm:

Iterate through string 1

For each character, if there is a character in the same position in string 2, replace the original character with both

This can be achieved with the following code:

```<code>function merge(s, t) {
  return s.split("")
          .map(function(v,i) {
              return t[i] ? v + t[i] : v
          })
          .join("")
}
</code>```

or the more Codegolf type answer:

```<code>s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``
</code>```

Title: Merge strings in javascript

Body:
The best way to do this is to perform the following algorithm:

Iterate through string 1

For each character, if there is a character in the same position in string 2, replace the original character with both

This can be achieved with the following code:

function merge(s, t) {
  return s.split("")
          .map(function(v,i) {
              return t[i] ? v + t[i] : v
          })
          .join("")
}

or the more Codegolf type answer:

s=>t=>[...s].map((v,i)=>t[i]?v+t[i]:v).join``


答:
I would use Array.from to generate an array from the strings (unicode conscious).

After that, just add a letter from each string until there's no letters left in each. Please note this solution will combine strings of uneven length (aa+bbbb=ababbb)

var a = "abc"
var b = "def"
var d = "foo  bar mañana mañana"

function combineStrings(a,b){
  var c = "";
  a = Array.from(a);
  b = Array.from(b);
  while(a.length > 0 || b.length > 0){
    if(a.length > 0)
      c += a.splice(0,1);
    if(b.length > 0)
      c += b.splice(0,1);
  }
  return c;
}

var test = combineStrings(a,b);
console.log(test);

var test2 = combineStrings(a,d);
console.log(test2);```

Title: Merge strings in javascript


问:
How can I efficiently translate a large, non-rectangular 2D list to an even larger rectangular 2D array?
I have a 2-D list of shape (300,000, X), where each of the sublists has a different size (X) and contains integers between 0 and 25. In order to convert the data to a Tensor, all of the sublists need to have equal length, but I don't want to lose any data from my sublists in the conversion.

At first glance, I wanted to fill all sublists smaller than the longest sublist with filler (-1) in order to create a rectangular array. For my current dataset, the longest sublist is of length 5037.

My conversion code is below:

for seq in new_format:
        seq.extend([-1] * (length - len(seq)))

However, when there are 300,000 sequences in new_format, and length-len(seq) is generally >4000, the process causes a MemoryError due to its enormous size. Most of the sublists become much longer when extended to size 5037 in order to equalize the sublists. How can I make this more space-efficient or avoid the problem entirely?

答:
My advice? Don't contruct a Python list to initialize the array. That will be too memory heavy. Since your values fall between 0-25, and you want a filler of -1, you can use np.int8:

First, initialize an adequately shaped array with the appropriate filler value:

```<code>>>> arr = np.full((300000, 5037), -1, dtype=np.int8)
</code>```

Then simply loop over your existing data and set the values as needed.

```<code>>>> for i, row in enumerate(data):
...     for j, val in enumerate(row):
...         arr[i, j] = val
...
</code>```

This will give you a nice and compact array of about 1.5 gigs:

```<code>>>> arr.nbytes*1e-9
1.5111
</code>```

Body:
My advice? Don't contruct a Python list to initialize the array. That will be too memory heavy. Since your values fall between 0-25, and you want a filler of -1, you can use np.int8:

First, initialize an adequately shaped array with the appropriate filler value:

>>> arr = np.full((300000, 5037), -1, dtype=np.int8)

Then simply loop over your existing data and set the values as needed.

>>> for i, row in enumerate(data):
...     for j, val in enumerate(row):
...         arr[i, j] = val
...

This will give you a nice and compact array of about 1.5 gigs:

>>> arr.nbytes*1e-9
1.5111


问:
javascript issue
I have  adynamic grid, and the functionality of the data in there needs to work such that I can copy down data in my grid incrementally. Assuming in row 5, I enter 10, the following rows starting from the 6th row should read from 11 etc.

If I go to row one which is blank, and enter 2, the count should increment and auto-correct from that row 3 on where it should read next as 3.

My Issue: Unable to accomplish the above once I am on row 1 or 2 and increament from the number I started with on that row.

Any ideas for this?

答:
You can accomplish this easily by assigning change (onChange) event on each of the row. (You should use event delegation instead of assigning a separate event for each row)

For 1st and second row, you should treat the total so far as zero, so it will not break your code.

ContentLicense: CC BY-SA 2.5

Title: javascript issue


问:
smtp is not working on for loops
I want to send an email to more than 2 people using my own database. So I use for loop to send an email. And it is sent well to a first person(mail_data.Rows[0][0]), but not for the second person.(mail_data.Rows[1][0]) The code stops before smtp.Send(mm). Second person's email is exactly correct. I have no idea why the code stops there.</p>

```<code>    private void Email()
    {
        //get the data from database
        DataTable data = GetData();
        DataTable email_data = GetEmailData();

        data.TableName = "Employee_Data";

                 ....

                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {
                        this.WriteToFile(to);
                        using (SmtpClient smtp = new SmtpClient())
                        {

                            mm.Subject = "Fresh NSO Updated List";

                            mm.AlternateViews.Add(body);
                            mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
                            mm.IsBodyHtml = true;

                            smtp.Host = "smtp.gmail.com";
                            smtp.EnableSsl = true;
                            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                            credentials.UserName = "aa@gmail.com";
                            credentials.Password = "aa";
                            smtp.UseDefaultCredentials = true;
                            smtp.Credentials = credentials;
                            smtp.Port = 587;

                            this.WriteToFile("beforeSend");
                            Thread.Sleep(1000);
          //just stop here on second loop,
                            smtp.Send(mm);
                            this.WriteToFile("Sent!");
                        }

                    }

                }
            }
</code>```

答:
Instead of sending individual emails to each recipient, when they are all the same content, you should use the BCC (blind carbon copy) field to send the same email to multiple recipients and still provide privacy for all of their email addresses.

You can set the to field to your (the sender's) email address so that it is addressed to someone.

This is a more efficient solution and has the same overall result.

Title: smtp is not working on for loops

Body:
I want to send an email to more than 2 people using my own database. So I use for loop to send an email. And it is sent well to a first person(mail_data.Rows[0][0]), but not for the second person.(mail_data.Rows[1][0]) The code stops before smtp.Send(mm). Second person's email is exactly correct. I have no idea why the code stops there.

    private void Email()
    {
        //get the data from database
        DataTable data = GetData();
        DataTable email_data = GetEmailData();

        data.TableName = "Employee_Data";

                 ....

                String from = "aa@gmail.com";

                for (int i = 0; i <= email_data.Rows.Count; i++)
                {
                    String to = email_data.Rows[i][0].ToString();

                    using (MailMessage mm = new MailMessage(from, to))
                    {
                        this.WriteToFile(to);
                        using (SmtpClient smtp = new SmtpClient())
                        {

                            mm.Subject = "Fresh NSO Updated List";

                            mm.AlternateViews.Add(body);
                            mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "NSOList.xlsx"));
                            mm.IsBodyHtml = true;

                            smtp.Host = "smtp.gmail.com";
                            smtp.EnableSsl = true;
                            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential();
                            credentials.UserName = "aa@gmail.com";
                            credentials.Password = "aa";
                            smtp.UseDefaultCredentials = true;
                            smtp.Credentials = credentials;
                            smtp.Port = 587;

                            this.WriteToFile("beforeSend");
                            Thread.Sleep(1000);
          //just stop here on second loop,
                            smtp.Send(mm);
                            this.WriteToFile("Sent!");
                        }

                    }

                }
            }


问:
how can I make a larger array with cubic interpolation and acces all the calculated values?
I am trying to get a cubic interpolation of a data set, e.g y = [0, 100, 200, 300, 400] and x = [0, 28, 54, 78, 100]. With the linear interpolation from the numpy library everything just works fine but I need a smooth data set. In the code sample below the result is a data set that looks like: enter image description here

Instead I want a data set that looks like this:
enter image description here
It is important for me that the interpolation gives me an array which gives me access to the DistanceLong value for every 2 seconds, which is the factor. With the scipy functions I did not got it to work. I hope you guys can give me some help!

```<code>import numpy as np
import matplotlib.pyplot as plt

def interplan(Timestamp, Distance, factor):
    Time = np.zeros(len(Timestamp)-1)
    NewDistance= np.zeros(len(Timestamp)-1)
    TotalTime = 0
    TotalDistance = 0

    for i in range(len(Timestamp)-1):
        TotalTime += Timestamp[i]
        Time[i] = TotalTime
        TotalDistance += Distance[i]
        NewDistance[i] = TotalDistance

    Time =  np.hstack((0,Time))
    NewDistance =  np.hstack((0,NewDistance))

    k = np.array(range((int(TotalTime+1))))
    t = k*factor
    DistanceLong = np.interp(t,Time,NewDistance)

    return DistanceLong

Timestamp = np.array([28, 26, 24, 22,0])
Distance = np.array([100, 100, 100, 100,0])
factor = 2

DistanceLong = interplan(Timestamp, Distance, factor)
BiggestVal = max(DistanceLong)
IndexLastVal = np.where(DistanceLong == BiggestVal)
DistanceLong = DistanceLong[0:IndexLastVal[0][1]]

Speed = np.zeros(len(DistanceLong))
for i in range(len(DistanceLong)-1):
    Speed[i] = ((DistanceLong[i+1]-DistanceLong[i])/2)*3.6

PerfectSpeed = (Distance/Timestamp)*3.6

plt.figure(1)
plt.plot(Speed,linewidth=0.8)

plt.figure(2)
plt.plot(PerfectSpeed,linewidth=0.8)
</code>```

答: For cubic interpolation you can use either splrep/ splev, or, in newer scipy, CubicSpline, or, in still newer scipy, make_interp_spline.

Body:
I am trying to get a cubic interpolation of a data set, e.g y = [0, 100, 200, 300, 400] and x = [0, 28, 54, 78, 100]. With the linear interpolation from the numpy library everything just works fine but I need a smooth data set. In the code sample below the result is a data set that looks like: enter image description here

Instead I want a data set that looks like this:
enter image description here
It is important for me that the interpolation gives me an array which gives me access to the DistanceLong value for every 2 seconds, which is the factor. With the scipy functions I did not got it to work. I hope you guys can give me some help!

import numpy as np
import matplotlib.pyplot as plt

def interplan(Timestamp, Distance, factor):
    Time = np.zeros(len(Timestamp)-1)
    NewDistance= np.zeros(len(Timestamp)-1)
    TotalTime = 0
    TotalDistance = 0

    for i in range(len(Timestamp)-1):
        TotalTime += Timestamp[i]
        Time[i] = TotalTime
        TotalDistance += Distance[i]
        NewDistance[i] = TotalDistance

    Time =  np.hstack((0,Time))
    NewDistance =  np.hstack((0,NewDistance))

    k = np.array(range((int(TotalTime+1))))
    t = k*factor
    DistanceLong = np.interp(t,Time,NewDistance)

    return DistanceLong

Timestamp = np.array([28, 26, 24, 22,0])
Distance = np.array([100, 100, 100, 100,0])
factor = 2

DistanceLong = interplan(Timestamp, Distance, factor)
BiggestVal = max(DistanceLong)
IndexLastVal = np.where(DistanceLong == BiggestVal)
DistanceLong = DistanceLong[0:IndexLastVal[0][1]]

Speed = np.zeros(len(DistanceLong))
for i in range(len(DistanceLong)-1):
    Speed[i] = ((DistanceLong[i+1]-DistanceLong[i])/2)*3.6

PerfectSpeed = (Distance/Timestamp)*3.6

plt.figure(1)
plt.plot(Speed,linewidth=0.8)

plt.figure(2)
plt.plot(PerfectSpeed,linewidth=0.8)


问:
OpenGL: How to design efficient rendering system using vertex arrays with depth sorting?
People constantly tell me to use at least Vertex Arrays. But i think its not a good idea since i'm using glPushMatrix() with glTranslatef/glRotatef to position an object in the 3d world.

So, should i stop using glPushMatrix() and calculate the rotated/moved vertex positions in the world "manually" and then push their vertex data into a vertex array and then render it all at once?

But, all this will get even more messed up when i use different texture surfaces for all the objects on the screen which are also depth sorted.

So:

I would have to store each object with the texture surface ID as well.

I would sort all the visible objects by their Z position (the game is viewed top-down only, and all objects are flat).

I would go through this sorted array:

Create new buffer and copy only the vertex/texcoord/color/normal into this buffer:

Every time the texture surface ID has changed from previous ID, i will bind to the correct texture ID:

Upload the vertex data i collected.

Free the buffer used for temporary vertex array.

Repeat steps 4-7 until i have gone through all the data i sorted at the first place.

Free my sorted array data, and repeat steps 1-9.

Am i doing it right?

Also, how should i design the data structure for the objects i will sort? For example, is it good to use std::vector to store the vertex data for each object? Or is there better alternative? I was thinking that the std::vector to store all this data would look like:

```<code>struct GameObject {
    int TexID;
    float z; // we will sort by this
    vector<VTCNStruct> VertexData; // store each point of the object here (including color/normal/texcoord points).
};

vector<GameObject> GameObjectBuffer; // push all sortable objects here
</code>```

Also, at step 4: is it possible to use the already existing std::vector in this case? I've had the idea i that i must use raw arrays, like new float[100] for sending the vertex array to my GPU, or could i somehow use my already existing sorted std::vector here somehow (efficiently) without creating new buffer every time the texture ID changes?

答:
Please abandon glBegin/glEnd now, it's deprecated and was removed from OpenGL-4. You should definitely use vertex arrays, even better if you use vertex buffer objects.

Using immediate mode (glBegin/glEnd) the OpenGL driver has to build a vertex array from the function calls. As it's not clear how many vertces will arrive, it will eventually re-allocate the memory multiple times (the times in which GPUs directly executed the calls between glBegin/glEnd are long over).

Using a vertex array will never be less performant than immediate mode. It's okay to put multiple object's geometries into a single vertex array, you can separate them through the vertex index lists. Vertex index lists can be stored in buffer objects, too.

Then between drawing the objects adjust the modelview matrix.

Sorting order should be like the followig:

divide into opaque and translucent objects. Sort the opaque

Sort the opqaues by GL objects (texture, shader, materials, etc.) since switching GL objects is most expensive.

For each distinct GL object group sort near to far and draw in that order

Sort translucents far to near and draw in that order

You should not try fiddling around with buffer up-/downloads. Just upload the vertex data one time and then just adjust the index arrays and the order in which those are submitted. There's no need to worry about available OpenGL memory, there's no limit enforced. If your data doesn't fit into GPU RAM the driver is responsible for swapping it to system memory – that's also why you should sort by OpenGL objects first, because every time you switch OpenGL objects (glBindTexture, glBindBuffer, etc.) the driver may need to swap, so you want to keep those swapping operations to a minimum. The amount of data sent to the GPU in form of index arrays will be much less, than what's sent by immediate mode calls at a minimum:

Index array: 16 bit per vertex (16 bit size indices are most performant).

Immediate mode call: 4*32 bit per vertex

Body:
People constantly tell me to use at least Vertex Arrays. But i think its not a good idea since i'm using glPushMatrix() with glTranslatef/glRotatef to position an object in the 3d world.

So, should i stop using glPushMatrix() and calculate the rotated/moved vertex positions in the world "manually" and then push their vertex data into a vertex array and then render it all at once?

But, all this will get even more messed up when i use different texture surfaces for all the objects on the screen which are also depth sorted.

So:

I would have to store each object with the texture surface ID as well.

I would sort all the visible objects by their Z position (the game is viewed top-down only, and all objects are flat).

I would go through this sorted array:

Create new buffer and copy only the vertex/texcoord/color/normal into this buffer:

Every time the texture surface ID has changed from previous ID, i will bind to the correct texture ID:

Upload the vertex data i collected.

Free the buffer used for temporary vertex array.

Repeat steps 4-7 until i have gone through all the data i sorted at the first place.

Free my sorted array data, and repeat steps 1-9.

Am i doing it right?

Also, how should i design the data structure for the objects i will sort? For example, is it good to use std::vector to store the vertex data for each object? Or is there better alternative? I was thinking that the std::vector to store all this data would look like:

struct GameObject {
    int TexID;
    float z; // we will sort by this
    vector<VTCNStruct> VertexData; // store each point of the object here (including color/normal/texcoord points).
};

vector<GameObject> GameObjectBuffer; // push all sortable objects here

Also, at step 4: is it possible to use the already existing std::vector in this case? I've had the idea i that i must use raw arrays, like new float[100] for sending the vertex array to my GPU, or could i somehow use my already existing sorted std::vector here somehow (efficiently) without creating new buffer every time the texture ID changes?

ContentLicense: CC BY-SA 4.0


问:
How to create pages in react
I am creating a really simple app in react. It will have a number of pages with minimum data on it. I am looking for the simplest method to switch between the pages with as little complexities as possible.

This is my current code:

```<code>render() {
    return (
        <div className="App test">
        <nav className="navbar pure-menu pure-menu-horizontal">
          <a href="#" className="pure-menu-heading pure-menu-link">
             Page 1
          </a>
          {
          }<ul className="pure-menu-list">
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 2</a></li>
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 3</a></li>
              <li className="pure-menu-item"><a href="#" className="pure-menu-link">Page 4</a></li>
              </ul>
          }
          </nav>
          <main className="container">
              <div className="pure-g">
                <div className="pure-u-1-1">
                  <p>
                    Page 1 text
                  </p>
                  <p>
                    Page 2 text
                  </p>
                  <p>
                    Page 3 text
                  </p>
                  <p>
                    Page 4 text
                  </p>

                </div>
              </div>
          </main>
        </div>);
  }
}
</code>```

Is there a standard to switch between the content? (Page text 1,2,3,4).

答:
How simple? :). Simplest method possible would be to hold a pageNumber state in your component and only render a particular page when it is that number. Call setPageNumber with a parameter to see the component render different pages.

This is obviously not the best solution or scalable.

```<code>class App extends React.Component {
    constructor() {
        super();

        this.state = {
            pageNumber: 0
        };
    }
    onClickLink = (pageNumber) => {
        this.setState({ pageNumber });
    }
    render() {
        <div className="pure-u-1-1">
            {this.state.pageNumber === 0 ? <p></p> : null}
            {this.state.pageNumber === 1 ? <p></p> : null}
            {this.state.pageNumber === 2 ? <p></p> : null}
            {this.state.pageNumber === 3 ? <p></p> : null}
        </div>
    }
}
</code>```

Title: How to create pages in react

Body:
I am creating a really simple app in react. It will have a number of pages with minimum data on it. I am looking for the simplest method to switch between the pages with as little complexities as possible.

This is my current code:

render() {
    return (

             Page 1

          {
          }

Page 2

Page 3

Page 4

          }

                    Page 1 text

                    Page 2 text

                    Page 3 text

                    Page 4 text

);
  }
}

Is there a standard to switch between the content? (Page text 1,2,3,4).

Body:
How simple? :). Simplest method possible would be to hold a pageNumber state in your component and only render a particular page when it is that number. Call setPageNumber with a parameter to see the component render different pages.

This is obviously not the best solution or scalable.

class App extends React.Component {
    constructor() {
        super();

        this.state = {
            pageNumber: 0
        };
    }
    onClickLink = (pageNumber) => {
        this.setState({ pageNumber });
    }
    render() {
        <div className="pure-u-1-1">
            {this.state.pageNumber === 0 ? <p></p> : null}
            {this.state.pageNumber === 1 ? <p></p> : null}
            {this.state.pageNumber === 2 ? <p></p> : null}
            {this.state.pageNumber === 3 ? <p></p> : null}
        </div>
    }
}


问:
Run bat file from different disk with java
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

```<code>String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);
</code>```

But didn't work, so I tried this

```<code>String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);
</code>```

didnt work either. Tried this too

```<code>Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);
</code>```

Says it cant find the file.

Tried something like this too:

```<code>Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");
</code>```

And nothing. The weird thing is that this command:

```<code>cd /d C:/abc/def/ && coolBat.bat
</code>```

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

```<code>CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\
</code>```

答:
The Java version could work as:</p>

```<code>String[] command = {"cmd.exe", "/C", "Start", "/D", "c:\\abc\\def", "c:\\abc\\def\\coolBat.bat"};

Process process = Runtime.getRuntime().exec(command);

    BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while ((line = input.readLine()) != null) {
      System.out.println(line);
    }
    input.close();

    BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    while ((line = errReader.readLine()) != null) {
        System.out.println(line);
    }

    System.out.flush();
    int retCode = process.waitFor();
    System.out.println("Return code: " + retCode);
</code>```

Body:
Im trying to run a bat from C:/abc/def/coolBat.bat but my java workspace is in D:/

I've tried with :

String cmd = "cmd /c /start C:/abc/def/coolBat.bat";
Runtime.getRuntime().exec(cmd);

But didn't work, so I tried this

String[] command = { "cmd.exe", "/C", "C:/abc/def/coolBat.bat" };
Runtime.getRuntime().exec(cmd);

didnt work either. Tried this too

Executor exec = new DefaultExecutor();
exec.setWorkingDirectory(new File("C:/abc/def"));
CommandLine cl = new CommandLine("coolBat.bat");
int exitvalue = exec.execute(cl);

Says it cant find the file.

Tried something like this too:

Runtime.getRuntime().exec("cmd cd /d C:/abc/def/ && coolBat.bat");

And nothing. The weird thing is that this command:

cd /d C:/abc/def/ && coolBat.bat

Works when i do it in cmd. Its worth saying that the bat file copies some files to another directory, all inside C:/

EDITED N°1

CD C:\abc\def\MN
copy almn + ctmn + bamn C:\abc\def\mn_sf.txt
CD C:\abc\def\ME
copy alme + ctme + bame  C:\abc\def\me_sf.txt
CD C:\abc\def\
if exist MN.txt del MN.txt
if exist ME.txt del ME.txt
if exist JUZ.txt del JUZ.txt
if exist FUNC.txt del FUNC.txt
if exist AHO.txt del AHO.txt
CD C:\

Body:
The Java version could work as:

String[] command = {"cmd.exe", "/C", "Start", "/D", "c:\\abc\\def", "c:\\abc\\def\\coolBat.bat"};

Process process = Runtime.getRuntime().exec(command);

    BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));
    while ((line = input.readLine()) != null) {
      System.out.println(line);
    }
    input.close();

    BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));

    while ((line = errReader.readLine()) != null) {
        System.out.println(line);
    }

    System.out.flush();
    int retCode = process.waitFor();
    System.out.println("Return code: " + retCode);


问:
Why are these regular expressions not working?
I want a regex to match complex mathematical expressions.
However I will ask for an easier regex because it will be the simplest case.

Example input:
1+2+3+4

I want to separate each char:
[('1', '+', '2', '+', '3', '+', '4')]

With a restriction: there has to be at least one operation (i.e. 1+2).

My regex: ([0-9]+)([+])([0-9]+)(([+])([0-9]+))*
or (\d+)(\+)(\d+)((\+)(\d+))*

Output for re.findall('(\d+)(\+)(\d+)((\+)(\d+))*',"1+2+3+4")
:

[('1', '+', '2', '+4', '+', '4')]

Why is this not working? Is Python the problem?

答:
You could go the test route.

See if its valid using re.match

then just get the results with re.findall

Python code

```<code>import re

input = "1+2+3+4";
if re.match(r"^\d+\+\d+(?:\+\d+)*$", input) :
    print ("Matched")
    print (re.findall(r"\+|\d+", input))

else :
    print ("Not valid")
</code>```

Output

```<code>Matched
['1', '+', '2', '+', '3', '+', '4']
</code>```

Body:
You could go the test route.

See if its valid using re.match

then just get the results with re.findall

Python code

import re

input = "1+2+3+4";
if re.match(r"^\d+\+\d+(?:\+\d+)*$", input) :
    print ("Matched")
    print (re.findall(r"\+|\d+", input))

else :
    print ("Not valid")

Output

Matched
['1', '+', '2', '+', '3', '+', '4']


问:
Script to Change Row Color when a cell changes text
I have a Google spreadsheet where I keep a list of bugs  and whenever I fix a bug I change the status from "Not Started" to "Complete". I want to write a script for the Google Docs spreadsheet such that whenever I change the status to "Complete" the entire row gets highlighted in a certain color.

I already know that Google spreadsheet already has "change color on text" but that function only changes the color of the cell and does not change the color of the entire row.

答:
I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

```<code>=and($S1<>"",search("Complete",$S1)>0)
</code>```

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

Body:
I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).


问:
Looping over a huge list, check string equal to true
I have a requirement as below:

```<code>List<User> userList = listOfUsers(); // Morethan 50,000 users
</code>```

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

答:
I would certainly think about using Java 8 Lambda.  I have written an example class:

```<code>package com.chocksaway;

import java.util.ArrayList;
import java.util.List;

/**
* Author milesd on 05/06/2017.
*/

class Name {
    private String name;
    private Boolean status;

    public Name(String name, Boolean status) {
        this.name = name;
        this.status = status;
    }

    public String getName() {
        return name;
    }

    public Boolean getStatus() {
        return status;
    }
}

public class FindFirstInStream {
    public static void main(String[] args) {
        List<Name> userList = new ArrayList<>();

        userList.add(new Name("James", false));
        userList.add(new Name("Eric", true));
        userList.add(new Name("David", false));

        Name firstActiveName = userList.stream()
            .filter(e -> e.getStatus().equals(true))
            .findFirst()
            .get();

        System.out.println(firstActiveName.getName());
    }
}
</code>```

I've created a Name class, with name, and status.

I populate a userList with James, Eric, and David.

I use Java 8 stream to filter, and return the first "active" name (Eric).

This is stored in "firstActiveName".

Body:
I have a requirement as below:

List<User> userList = listOfUsers(); // Morethan 50,000 users

I need to find a user status from the list of users. if any one of the users is active then break the loop.

what is the efficient way to handle this in java ?

Body:
I would certainly think about using Java 8 Lambda.  I have written an example class:

package com.chocksaway;

import java.util.ArrayList;
import java.util.List;

/**
* Author milesd on 05/06/2017.
*/

class Name {
    private String name;
    private Boolean status;

    public Name(String name, Boolean status) {
        this.name = name;
        this.status = status;
    }

    public String getName() {
        return name;
    }

    public Boolean getStatus() {
        return status;
    }
}

public class FindFirstInStream {
    public static void main(String[] args) {
        List<Name> userList = new ArrayList<>();

        userList.add(new Name("James", false));
        userList.add(new Name("Eric", true));
        userList.add(new Name("David", false));

        Name firstActiveName = userList.stream()
            .filter(e -> e.getStatus().equals(true))
            .findFirst()
            .get();

        System.out.println(firstActiveName.getName());
    }
}

I've created a Name class, with name, and status.

I populate a userList with James, Eric, and David.

I use Java 8 stream to filter, and return the first "active" name (Eric).

This is stored in "firstActiveName".


问:
C++: difference between 0. and 0.0?
I am well aware of the difference between 0 and 0.0 (int and double).

But is there any difference between 0. and 0.0 ( please note the . )?

Thanks a lot in advance,

Axel

答:
0 is of type int but can be casted to double and 0.0 is of type double but can be casted to int.

Both casts are implicit.

Title: C++: difference between 0. and 0.0?


问:
How to format a SOAP request
I want to access an online program via the command line within a bash script. I've been told I can run a SOAP request in order to access the software. This is the request I've been told I can use.

```<code>POST /OnlineAnalysis/Service.asmx HTTP/1.1
Host: cydas.org
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.cydas.org/OnlineAnalysis/analyseKaryotype"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <analyseKaryotype xmlns="http://www.cydas.org/OnlineAnalysis/">
      <strKaryotype>string</strKaryotype>
    </analyseKaryotype>
  </soap:Body>
</soap:Envelope>
</code>```

I've never run a SOAP request before but it looks like I'm able to use the curl command based on this question. I've tried to model my curl command according to the link I posted

```<code>curl -X POST -H "POST /OnlineAnalysis/Service.asmx HTTP/1.1" -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction: \"http://www.cydas.org/OnlineAnalysis/analyseKaryotype\"" -H "Host: cydas.org" --data-binary @request.xml
</code>```

And am getting this output

```<code><HTML>
<HEAD>
<TITLE>405 Method Not Allowed</TITLE>
<BASE href="/error_docs/"><!--[if lte IE 6]></BASE><![endif]-->
</HEAD>
<BODY>
<H1>Method Not Allowed</H1>
The HTTP verb used to access this page is not allowed.<P>
<HR>
<ADDRESS>
Web Server at cydas.org
</ADDRESS>
</BODY>
</HTML>

<!--
- Unfortunately, Microsoft has added a clever new
- "feature" to Internet Explorer. If the text of
...
</code>```

These are the contents of my request.xml file below

```<code><?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <analyseKaryotype xmlns="http://www.cydas.org/OnlineAnalysis/">
      <strKaryotype>46,XX,del(3)(p11)</strKaryotype>
    </analyseKaryotype>
  </soap:Body>
</soap:Envelope>
</code>```

I'm not sure what the expected output is supposed to be yet because I can't run the program. I just want to get my SOAP request running properly.

答:
try this:

```<code>curl -v "http://www.cydas.org/OnlineAnalysis/Service.asmx" -H "Content-Type: text/xml;charset=UTF-8" -H "SOAPAction: \"http://www.cydas.org/OnlineAnalysis/analyseKaryotype\"" -H "Connection: Keep-Alive" -H "Host: www.cydas.org" --data @request.xml
</code>```

The server responded with the message: "The Karyotype del(3)(p11) is not valid:
Non-specified error in chromosome count element (del(3)(p11))"

Here's the complete response message:

```<code><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<analyseKaryotypeResponse xmlns="http://www.cydas.org/OnlineAnalysis/">
<analyseKaryotypeResult>
<Original_ISCN_Formula>del(3)(p11)</Original_ISCN_Formula>
<IsPolyClonal>false</IsPolyClonal>
<IsValidKaryotype>false</IsValidKaryotype>
<Corrected_ISCN_Formula/>
<CloneSize>0</CloneSize>
<IsIncompleteKaryotype>false</IsIncompleteKaryotype>
<Ploidy>0</Ploidy>
<ErrorMessages>The Karyotype del(3)(p11) is not valid:
Non-specified error in chromosome count element (del(3)(p11))</ErrorMessages>
</analyseKaryotypeResult>
</analyseKaryotypeResponse>
</soap:Body>
</soap:Envelope>
</code>```

cURL is a great tool, but if you want a nice gui you can try other tools like SoapUI or Postman for testing APIs. SoapUI is a standalone Java application and Postman is a plugin for Chrome. They're both free.

Title: How to format a SOAP request

Body:
I want to access an online program via the command line within a bash script. I've been told I can run a SOAP request in order to access the software. This is the request I've been told I can use.

POST /OnlineAnalysis/Service.asmx HTTP/1.1
Host: cydas.org
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://www.cydas.org/OnlineAnalysis/analyseKaryotype"

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <analyseKaryotype xmlns="http://www.cydas.org/OnlineAnalysis/">
      <strKaryotype>string</strKaryotype>
    </analyseKaryotype>
  </soap:Body>
</soap:Envelope>

I've never run a SOAP request before but it looks like I'm able to use the curl command based on this question. I've tried to model my curl command according to the link I posted

curl -X POST -H "POST /OnlineAnalysis/Service.asmx HTTP/1.1" -H "Content-Type: text/xml; charset=utf-8" -H "SOAPAction: \"http://www.cydas.org/OnlineAnalysis/analyseKaryotype\"" -H "Host: cydas.org" --data-binary @request.xml

And am getting this output

<TITLE>405 Method Not Allowed</TITLE>
<BASE href="/error_docs/">

Method Not Allowed

The HTTP verb used to access this page is not allowed.

<ADDRESS>
Web Server at cydas.org
</ADDRESS>

Body:
try this:

curl -v "http://www.cydas.org/OnlineAnalysis/Service.asmx" -H "Content-Type: text/xml;charset=UTF-8" -H "SOAPAction: \"http://www.cydas.org/OnlineAnalysis/analyseKaryotype\"" -H "Connection: Keep-Alive" -H "Host: www.cydas.org" --data @request.xml

The server responded with the message: "The Karyotype del(3)(p11) is not valid:
Non-specified error in chromosome count element (del(3)(p11))"

Here's the complete response message:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<analyseKaryotypeResponse xmlns="http://www.cydas.org/OnlineAnalysis/">
<analyseKaryotypeResult>
<Original_ISCN_Formula>del(3)(p11)</Original_ISCN_Formula>
<IsPolyClonal>false</IsPolyClonal>
<IsValidKaryotype>false</IsValidKaryotype>
<Corrected_ISCN_Formula/>
<CloneSize>0</CloneSize>
<IsIncompleteKaryotype>false</IsIncompleteKaryotype>
<Ploidy>0</Ploidy>
<ErrorMessages>The Karyotype del(3)(p11) is not valid:
Non-specified error in chromosome count element (del(3)(p11))</ErrorMessages>
</analyseKaryotypeResult>
</analyseKaryotypeResponse>
</soap:Body>
</soap:Envelope>

cURL is a great tool, but if you want a nice gui you can try other tools like SoapUI or Postman for testing APIs. SoapUI is a standalone Java application and Postman is a plugin for Chrome. They're both free.


问:
Paralize numpy.linalg.matrix_power do not increase performance
I need to paralize the function numpy.linalg.matrix_power and I use the following code to test how much fast can be the parallel version

```<code>def aux_matrix_arg3(A):

     aaa=np.linalg.matrix_power(np.random.randn(199,199),100)

return 1

N=10000
processes=4
chunksize=N/processes
poolWorkers=mp.Pool(processes=processes)
ti=t.time()
A=poolWorkers.map(aux_matrix_arg3,range(N),chunksize=chunksize)
print 't_iteration 3',t.time()-ti
</code>```

I have tried with 1 and 4 processes in my laptop. I got very similar performance
4 processes: t_iteration 3 40.7985408306
1 processes: t_iteration 3 40.6538720131

Any clue why I do not get any improvment with paralle processes?

答:
The docs say:

For positive integers n, the power is computed by repeated matrix squarings and matrix multiplications. If n == 0, the identity matrix of the same shape as M is returned. If n < 0, the inverse is computed and then raised to the abs(n).

If your system is set up correctly, BLAS will be used to parallelize matrix-multiplications and LAPACK (maybe SuperLU, the latter probably only in the sparse-case) for solving systems of linear-equations (used to calculate the inverse). So with a very high probability, your naive code is already very very optimized!

Despite that, you should be careful as naive parallelization copies all the data, which can hurt. (Normaly one would use mmap-arrays to share data instead of copying).

Body:
I need to paralize the function numpy.linalg.matrix_power and I use the following code to test how much fast can be the parallel version

def aux_matrix_arg3(A):

     aaa=np.linalg.matrix_power(np.random.randn(199,199),100)

return 1

N=10000
processes=4
chunksize=N/processes
poolWorkers=mp.Pool(processes=processes)
ti=t.time()
A=poolWorkers.map(aux_matrix_arg3,range(N),chunksize=chunksize)
print 't_iteration 3',t.time()-ti

I have tried with 1 and 4 processes in my laptop. I got very similar performance
4 processes: t_iteration 3 40.7985408306
1 processes: t_iteration 3 40.6538720131

Any clue why I do not get any improvment with paralle processes?


问:
Uploaded images to Firebase are all black. How to get rid of it?
The user selects the image from the camera or gallery, so now the image is in an Imageview to show the user the picture. Now the user uploads it to the server, but every picture I upload is black. Why is this happening?
This is the code:

```<code>mUpload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lalala-14247.appspot.com");

        mImageview.setDrawingCacheEnabled(true);
        mImageview.buildDrawingCache();
        Bitmap bitmap = mImageview .getDrawingCache();

        ByteArrayOutputStream baas = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);

        byte[] data = baas.toByteArray();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        UploadTask uploadTask = storageRef.child("Photo").child(timeStamp).putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();

            }
        });

    }

});
</code>```

My dependencies:

```<code>compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
testCompile 'junit:junit:4.12'
</code>```

答:
```<code>final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);
</code>```

this helped me

Body:
The user selects the image from the camera or gallery, so now the image is in an Imageview to show the user the picture. Now the user uploads it to the server, but every picture I upload is black. Why is this happening?
This is the code:

mUpload.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        final StorageReference storageRef = FirebaseStorage.getInstance().getReferenceFromUrl("gs://lalala-14247.appspot.com");

        mImageview.setDrawingCacheEnabled(true);
        mImageview.buildDrawingCache();
        Bitmap bitmap = mImageview .getDrawingCache();

        ByteArrayOutputStream baas = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baas);

        byte[] data = baas.toByteArray();
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

        UploadTask uploadTask = storageRef.child("Photo").child(timeStamp).putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Toast.makeText(MainActivity.this, "Picture upload failed", Toast.LENGTH_LONG).show();
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(MainActivity.this, "Upload done", Toast.LENGTH_LONG).show();

            }
        });

    }

});

My dependencies:

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.google.firebase:firebase-storage:10.0.1'
compile 'com.google.firebase:firebase-auth:10.0.1'
compile 'com.google.firebase:firebase-database:10.0.1'
testCompile 'junit:junit:4.12'

Body:
final int backgroundPreviousColor = view.getDrawingCacheBackgroundColor();
view.setDrawingCacheEnabled(true);
view.setDrawingCacheBackgroundColor(0xfffafafa);
final Bitmap bitmap = view.getDrawingCache();
view.setDrawingCacheBackgroundColor(backgroundPreviousColor);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
view.setDrawingCacheEnabled(cachePreviousState);

this helped me