text:
Q: Check if function within another function is called with jest and enzyme I have a test that needs to check for a function being called within another function attached to a button with jest and enzyme. I have both functions mocked out, but don't know how to attach one to another.
My component looks like the following:
class MyComponent extends React.Component {
    handleButton () {
        console.warn('Clicked!')
        this.context.anotherFunction()
    }

    render () {
        return (
            <div>
                My Component
                <button class='my-button' onClick={handleButton}>My Button</button>
            </div>
        )
    }

}

I want to check that both onClick and this.context.anotherFunction are called when the button is clicked. This is what my current test looks like:
  test.only('should test MyComponent button', () => {
    const wrapper = shallow(<MyComponent {...props} />)
    const anotherFunction = jest.fn()
    wrapper.instance().context = { anotherFunction }

    wrapper.instance().handleButton = () => {
      jest.fn()
      // How to simulate a call to anotherFunction???
      // wrapper.instance().context.anotherFunction()
    }
    wrapper.find('.my-button').simulate('click')
    expect(wrapper.instance().showCancelModal).toHaveBeenCalled() // Passes
    expect(wrapper.instance().context.showModal).toHaveBeenCalled() // Fails
  })

How can I mock the call of anotherFunction in the mocked version of handleButton?

A: What you probably want is jest.spyOn()
That allows you to monitor calls to a function without actually mocking it. So what will be able to do is:
 test.only('should test MyComponent button', () => {
    const wrapper = shallow(<MyComponent {...props} />)
    const anotherFunction = jest.fn()
    wrapper.instance().context = { anotherFunction }

    const handleButton = jest.spyOn(wrapper.instance(), 'handleButton');

    wrapper.find('.my-button').simulate('click')
    // your tests:
    expect(handleButton).toHaveBeenCalled() // Passes
    // Instead of checking "wrapper.instance().context.anotherFunction"
    // you can directly check if anotherFunction was called
    expect(anotherFunction).toHaveBeenCalled() // Fails
  })


text:
Q: Perl XS: Memory management I am absolutely new to Perl XS.
My simple testfunction gets a string and appends something.
In Perl is is a scalar-string in and one out.
In the function I have a malloc. Whats the correct way to free the mem?
SV *foo (str)
   SV *str
CODE:
    unsigned char *strbuf;
    size_t strlen;
    strbuf = (unsigned char *) SvPV (str, strlen);

    int n = strlen + 10;
    unsigned char *buf = malloc (n);

    strncpy (buf, strbuf, strlen);
    strncat (buf, "0123456789", 10);

    RETVAL = newSVpv (buf, n);
OUTPUT:
    RETVAL

thanks!
Chris

A: newSVpv creates an internal copy of the string, so you can simply free the memory by calling free after assigning to RETVAL.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use get keyword as a class instance method name? I know that get is one of the keywords in Dart, but I wanna wrap an HTTP client class with an instance method named get in my flutter app, it's semantic。 How can I do this?

A: Works for me:
void main() {
  Http().get('');
}

class Http {
  String get(String list) {
    print('get called');
  }
}

A: Maybe this will help
class HttpClient {
  HttpClient.get() {
    ...
  }
}


text:
Q: Right Continuous Adapted Processes without right-continuous Filtration. Let $\mathscr{F}$ be a filtration and $\mathscr{F}^+$ be the right continuous version. ($\mathscr{F} = \{\mathscr{F}_t\}_{t\in [0,T]})$
Suppose $X$ is right-continuous $\mathscr{F}$-adapted process.

Claim X is $\mathscr{F}^+$-progressively measurable.

If I do not misunderstood, it follows by discretize time and approximate $X$ as a limit of left-continuous simple functions as follows,
\begin{equation}
X_n(s,w) = \sum_{k=0}^{2^n} X\left(t_k, w\right)\mathbb{1}\left\{t_{k-1}< s \leq t_k\right\}
\end{equation}
where $t_k = kT/2^n$. ($n$ implicit).
Each $X_n$ is $(\mathscr{B}([0,T])\times \mathscr{F}_T, \mathscr{B}(\mathbb{R}))$-measurable, hence $X = \lim_n X_n$ is measurable too.
Question I couldn't figure out why we require right-continuity of filtration.
For $B \in \mathscr{B}(\mathbb{R})$,
\begin{equation}
\{X_n(s,w) \in B\} = \cup_{k=0}^{2^n} \left\{(t_{k-1}, t_k)\times w : X(t_k, w) \in B \right\}
\end{equation}
Hence $\{X_n \in B\} \in (\mathscr{B}([0,T])\times \cup_k\mathscr{F}_{t_k})$ because $X$ is adapted.


text:
Q: Could Somone Explain this Code What actually happening here Could Someone explain what really happening in the below mentioned array. I have no idea what really the statement inside the for-loop does.Could someone Explain
#include<iostream>
using namespace std;

    int main(){

        int m=3,n=2;

        int *arr[m];

        for(int i=0;i<m;i++){
            arr[i]=new int[n];
        }

        return 0;
    }

A: arr is an array of pointers to int. So in the for-loop, you're creating an array of n int whose the first element is pointed by arr[i].


text:
Q: expectation of a standard normal within the CDF I was wondering if there is a way to compute the following expectation analytically?
$
\mathbb{E}\left[e^{cZ}\Phi\left(a+bZ\right)\right]
$
where $Z$ is  a standard normal random variable and $\Phi$ is the CDF of the standard normal.
Thanks in advance.

A: If $Z\sim N\left(0,1\right)$ and $f$ is a 'neat' function then:
$$\mathbb{E}\left[e^{cZ}f\left(Z\right)\right]=e^{\frac{1}{2}c^{2}}\mathbb{E}f\left(Z+c\right)$$
We start with:
$\mathbb{E}\left[e^{cZ}f\left(Z\right)\right]=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{cz-\frac{1}{2}z^{2}}f\left(z\right)dz$.
Applying $v=z-c$ and we find:
$\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{cz-\frac{1}{2}z^{2}}f\left(z\right)dz=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{cv-\frac{1}{2}\left(v+c\right)^{2}}f\left(v+c\right)dv=\frac{e^{-\frac{1}{2}c^{2}}}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{-\frac{1}{2}v^{2}}f\left(v+c\right)dv=e^{-\frac{1}{2}c^{2}}\mathbb{E}\left[f\left(Z+c\right)\right]$
Next to that we have: $$\mathbb{E}\Phi\left(a+bZ\right)=\Phi\left(\frac{a}{\sqrt{1+b^{2}}}\right)$$
$\mathbb{E}\Phi\left(a+bZ\right)$can be recognized as $P\left(V\leq a+bZ\right)$
where $Z,V\sim N\left(0,1\right)$ are independent.
So $\mathbb{E}\Phi\left(a+bZ\right)=P\left(W\leq a\right)$ where
$W=V-bZ$.
Here $W\sim N\left(0,1+b^{2}\right)$ so $W'=\frac{W}{\sqrt{1+b^{2}}}\sim N\left(0,1\right)$.
This leads to $\mathbb{E}\Phi\left(a+bZ\right)=P\left(W\leq a\right)=P\left(W'\leq\frac{a}{\sqrt{1+b^{2}}}\right)=\Phi\left(\frac{a}{\sqrt{1+b^{2}}}\right)$.
Applying these facts we find:

$$\mathbb{E}e^{cZ}\Phi\left(a+bZ\right)=e^{\frac{1}{2}c^{2}}\mathbb{E}\Phi\left(a+bc+bZ\right)=e^{\frac{1}{2}c^{2}}\Phi\left(\frac{a+bc}{\sqrt{1+b^{2}}}\right)$$


text:
Q: Is there a way to computed again class variable when create class? I have some classes as below
from random import randint

class A:
    def __init__(self, name, value):
        self.name = name
        self.value = value

class B:
    var_1 = A('a', randint(10, 20))

I want to every create instance from class B, var_1 have different value.
ex:
B().var_1.value != B().var_1.value

I know that if I move var_1 from class variable to instance variable I will have different.

A: You have to change var_1 to an instance variable for your requirement that different instances of class B have different values stored in var_1. A class variable's value is by definition shared between instances, which isn't what you want.
Here is a modified version of your program:
#!/usr/bin/env python3

class A:
    def __init__(self, name, value):
        self.name = name
        self.value = value

class B:
    __value = 0
    def __init__(self):
        B.__value += 1
        self.var_1 = A('a', B.__value)

print(B().var_1.value != B().var_1.value)

It always prints True.
Each time B is instantiated, its class variable __value is incremented by 1, and its value is stored in the instance variable var_1. This guarantees that the value is always different, as opposed to your code where there is a chance that two instances share the same number since the value is randomly generated.


text:
Q: Python XML Parsing Children and grand children attributes I have been trying this on and off for the last two weeks and going over python's documents for XML parsing. I still can figure out if it's an Xpath thing or not. If anyone can provide some help I would greatly appreciate it.
My XML file has many children and I am using the root.findall() to get the attribute for myAccessPoints and then three children below it I have an element with several attributes I want to extract. However, so far, I'm only able to do this with 2 for loops.
import xml.etree.ElementTree as ET

def apData():

    tree = ET.parse("project.xml")

    root = tree.getroot()
    for topLevels in root.findall("./myAccessPoints//*[@id]"):
        myApId = topLevels.get('id')
        print("AP:%s" % myApId)
        print()
        #return myApId

    for radio in root.findall("./accessPoints/accessPoint/radio/*"):
        rChannel = radio.get('primaryNumber')
        rMac = radio.get('mac')
        rSsid = radio.get('primaryNumber')
        print(rChannel, rMac, rSsid)
        #return rChannel, rMac, rSsid

Here is an example of the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<project>
  <maps>
    <map id="0" name="floorplan" pixelsPerMeter="47.808212118953044" type="fspl"/>
  </maps>
  <accessPoints>
    <accessPoint id="0" userDefinedPosition="false">
      <radio type="measured">
        <accessPointMeasurement mac="a0:63:91:21:c4:f8" ssid="Eggs" primaryNumber="7" primaryFrequencyMhz="2442" centerNumber="7" bandwidthMhz="20" security="WPA2" informationElements="000445676773010882840b162430486c0301072a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1afc181fffff0000000000000000000000000000000000000000003d16070017000000000000000000000000000000000000004a0e14000a002c01c8001400050019007f0101dd890050f204104a0001101044000102103b00010310470010177b8b3ae292d7c44b93d4616ff30e7e1021000d4e4554474541522c20496e632e1023000a574e44523334303076331024000a574e44523334303076331042000230311054000800060050f20400011011000a574e4452333430307633100800020004103c0001031049000600372a000120dd090010180204f0040000dd180050f2020101800003a4000027a4000042435e0062322f00">
          <technologies>
            <technology band="802.11g"/>
            <technology band="802.11b"/>
            <technology band="802.11n"/>
          </technologies>
        </accessPointMeasurement>
      </radio>
    </accessPoint>
    <accessPoint id="1" userDefinedPosition="false">

Eventually I would take the access point element attributes like so -->
accessPoint id
accessPointMeasurement mac, ssid, primaryNumber
technology band
technology band
technology band
Some accessPoint elements have 2 sets of radios so I would have to get accessPointMeasurement attributes twice.
I imagine I'll have to create a class and within the class I'd have to make lists or dictionaries within themselves.
I'm not asking anyone to do anything for me other than to understand how I can get each access point and it's attributes in one for loop (If it's even possible).
Thanks for your help.

A: I expanded your XML to include more accessPoints and radios and used the lxml library to get access to its xpath features. Nested loops.
from lxml import etree

tree = etree.parse('temp.xml')
accessPoints = tree.xpath('.//accessPoint')

for accessPoint in accessPoints:
    print ('accessPoint id:', accessPoint.attrib['id'])
    radios = accessPoint.xpath('radio')
    for radio in radios:
        accessPointMeasurement = radio.xpath('accessPointMeasurement')
        print ('\taccessPointMeasurement: ', accessPointMeasurement[0].attrib)
        technologies = radio.xpath('.//technology')
        for technology in technologies:
            print ('\t\ttechnology: ', technology.attrib)

Results are these:
accessPoint id: 0
    accessPointMeasurement:  {'security': 'WPA2', 'informationElements': '000445676773010882840b162430486c0301072a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1afc181fffff0000000000000000000000000000000000000000003d16070017000000000000000000000000000000000000004a0e14000a002c01c8001400050019007f0101dd890050f204104a0001101044000102103b00010310470010177b8b3ae292d7c44b93d4616ff30e7e1021000d4e4554474541522c20496e632e1023000a574e44523334303076331024000a574e44523334303076331042000230311054000800060050f20400011011000a574e4452333430307633100800020004103c0001031049000600372a000120dd090010180204f0040000dd180050f2020101800003a4000027a4000042435e0062322f00', 'bandwidthMhz': '20', 'centerNumber': '7', 'mac': 'a0:63:91:21:c4:f8', 'ssid': 'Eggs', 'primaryFrequencyMhz': '2442', 'primaryNumber': '7'}
        technology:  {'band': '802.11g'}
        technology:  {'band': '802.11b'}
        technology:  {'band': '802.11n'}
accessPoint id: 2
    accessPointMeasurement:  {'security': 'WPA2', 'informationElements': '000445676773010882840b162430486c0301072a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1afc181fffff0000000000000000000000000000000000000000003d16070017000000000000000000000000000000000000004a0e14000a002c01c8001400050019007f0101dd890050f204104a0001101044000102103b00010310470010177b8b3ae292d7c44b93d4616ff30e7e1021000d4e4554474541522c20496e632e1023000a574e44523334303076331024000a574e44523334303076331042000230311054000800060050f20400011011000a574e4452333430307633100800020004103c0001031049000600372a000120dd090010180204f0040000dd180050f2020101800003a4000027a4000042435e0062322f00', 'bandwidthMhz': '20', 'centerNumber': '7', 'mac': 'a0:63:91:21:c4:f8', 'ssid': 'Eggs', 'primaryFrequencyMhz': '2442', 'primaryNumber': '7'}
        technology:  {'band': '802.11g'}
        technology:  {'band': '802.11b'}
        technology:  {'band': '802.11n'}
    accessPointMeasurement:  {'security': 'WPA2', 'informationElements': '000445676773010882840b162430486c0301072a01042f010430140100000fac040100000fac040100000fac020c0032040c1218602d1afc181fffff0000000000000000000000000000000000000000003d16070017000000000000000000000000000000000000004a0e14000a002c01c8001400050019007f0101dd890050f204104a0001101044000102103b00010310470010177b8b3ae292d7c44b93d4616ff30e7e1021000d4e4554474541522c20496e632e1023000a574e44523334303076331024000a574e44523334303076331042000230311054000800060050f20400011011000a574e4452333430307633100800020004103c0001031049000600372a000120dd090010180204f0040000dd180050f2020101800003a4000027a4000042435e0062322f00', 'bandwidthMhz': '20', 'centerNumber': '7', 'mac': 'a0:63:91:21:c4:f8', 'ssid': 'Eggs', 'primaryFrequencyMhz': '2442', 'primaryNumber': '7'}
        technology:  {'band': '802.11g'}
        technology:  {'band': '802.11b'}
        technology:  {'band': '802.11n'}


text:
Q: Using checkpassword-pam from Java I'd like to use checkpassword-pam in a java application. It's a very simple executable that reads a username and password from fd 3 and then verifies it.
The protocol is described here.
In a shell you'd use it like this:
# echo -e "username\0password\0timestamp\0" \
| checkpassword-pam -s SERVICE \
--debug --stdout -- /usr/bin/id 3<&0

How would I do this from a java application ?
I'm sure it can't be done through standard Java, but perhaps accessing posix api via jna...

A: In order to do what you want you can use the Runtime class, using Runtime.getRuntime(), and the exec method of the runtime to run a command from inside your Java program. From this, you can use the Process class to control the standard input and output of that shell command, essentially simulating that the user typed in the command from their console. You can look here for more help

A: To answer my own question: a simple shell command can redirect fd 3 to stdin.
    try {
        Process p = new ProcessBuilder("/bin/sh", "-c" , "exec /usr/bin/checkpassword-pam -s sshd 3<&0 /usr/bin/id").redirectErrorStream(true).start();
        OutputStream os = p.getOutputStream();
        os.write(userName.getBytes(Charset.defaultCharset()));
        os.write(0);
        os.write(password.getBytes(Charset.defaultCharset()));
        os.write(0);
        os.close();
        p.waitFor(10, TimeUnit.SECONDS);
        if (p.exitValue() == 0) {
            logger.info("authenticated user {}", IOUtils.read(p.getInputStream()).trim());
            result = true;
        } else {
            logger.info("authenticated failed for user {}", userName);
            result = false;
        }
    } catch (IOException | InterruptedException e) {
        logger.error("failed to authenticate user {}",  userName, e);
        result = false;
    }


text:
Q: Gulp: How to set up multiple sources and destinations in one task? I'm using gulp-imagemin to minify images in my images folder. The output of the task should be streamed into dist/images directory. However, the source images folder has a subfolder images/headers whose compressed contents should be streamed to dist/images/headers. So this is the source folder structure:
-images
  -headers

whose contents should be streamed to:
-dist
  -images (contents of `images`)
    -headers (contents of `images/headers`)

Currently my task definition looks like this:
gulp.task('compress', function () {
    return gulp.src('images/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('dist/images'));
});

My question is how I can tell Gulp to stream images/headers into dist/images/headers without writing a separate task for it.
I know that I can pass array of sources, but then ho can I tell Gulp where to output processed contents of each destination so that each source has a different destination?

A: You should use a recursive glob. Now you're only watching for changes directly in the images folder. Instead of using gulp.src('images/*') you should use gulp.src('images/')**.
Your new task will look like:
gulp.task('compress', function () {
    return gulp.src('images/**')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngquant()]
        }))
        .pipe(gulp.dest('dist/images'));
});

This will process every image located in the images folder and below to the dist/images folder.


text:
Q: how do I change the size of a drawable that is on mapview in android? Hi I have managed to create a drawable from a path as show here:
Drawable drawable = Drawable.createFromPath(path);

but the image that shows up on the map is very large because it is taken from the camera and stored in the SD card is there a way to make the image smaller when viewed on the map?

A: Is your purpose to just put an image on the Mapview. If that is the case, why don't you use the BitmapFactory to create a Bitmap from the FileInputStream which you open to your image file.
Then on the Bitmap created by BitmapFactory, you could use the createScaledBitmap method to scale the image and then put it on MapView.
EDIT: Create a BitmapDrawable from the scaled Bitmap.


text:
Q: Get Job id OR Job name from within executing job I have a central DB that I write job outcomes on all my servers back to. I pass 3 parameters via powershell in a SQL job back to a sp on the central server that verifies the job should be running at that time, etc. The info is then exposed via SSRS so we can see an job failures / long running jobs / & jobs that haven't run but should have(or if someone messed with a schedule).
To do this, I have 2 job steps added into each job on every server and I would like to reduce the script down to just 1 step added to each job..possibly even call it from a network share..
But my issue is one of the 3 parameters I pass. I need to get the executing jobid or job name from within the executing job so I don't have to hardcode the name parameter.
The 3 parameters I pass are jobid, status(success/fail), errormsg. The powershell script I wrote is pretty straightforward.
Invoke-sqlcmd -ServerInstance "MYRemoteSYSTEM" -Database remoteDB -Query "exec dbo.JOB_LOG  'JOBNAME/ID','Success/FAIL','BAD MESSAGE HERE'"
This writes what I need to the table. I've looked at
msdb.dbo.sp_help_job /
msdb.dbo.sp_get_composite_job_info /
dbo.xp_sqlagent_enum_jobs /
but none of these will guarantee I get the ID or name of the correct executing job in the event that there are more than 1 jobs executing at the same time.
I've even tried looked at sys.sysprocesses but I think since the agent job is a powershell script, it shows as ".Net SqlClient Data Provider" so I can't trim the binary JOBID off the jobs that show as "SQLAgent - TSQL JobStep (Job 0xF1800243164745429C30474FFD5C990C : Step 1)"
---this I learned from Denny cherry's post - thanks denny-
Any ideas on how to grab the executing jobid would be greatly appreciated.
Thanks,
Chris

A: You will have to use tokens in your job steps to get your own job id. Details here: Using Tokens in Job Steps.
At the end of the article there's one example with jobid:
SELECT * FROM msdb.dbo.sysjobs
WHERE @JobID = CONVERT(uniqueidentifier, $(ESCAPE_NONE(JOBID))) ;

A: To get this to work, I was using the invoke-sqlcmd cmdlet in powershell though the sql agent. Using the information I received above, this what I came up with that worked:
$var = Invoke-sqlcmd -Server "Server\Instance" -Query "select name from msdb.dbo.sysjobs WHERE job_id = CONVERT(uniqueidentifier, $(ESCAPE_SQUOTE(JOBID)))" -- This gives me the job name at runtime

$varname = $var.name -- here i have to put just the name into a variable

Invoke-sqlcmd -Server "server\instance" -Database "remote database" -Query "exec dbo.JOB_LOG $varname,'JOB STATUS HERE','LOG MESSAGE HERE';"
--here I pass that to the remote system

The one part that got me was that I had to add this line
$varname = $var.name

because if I did not add this, the initial variable $var would pass in the system.data.datatable header long with the column name of the job, so it was causing the variable to mess the query up at run time.
Hope this can help someone else down the road.

A: Check this:
DECLARE @jobId BINARY(16)

SELECT @jobId = CONVERT(uniqueidentifier, job_id) FROM msdb.dbo.sysjobs
WHERE name = 'Your_Job_Name'

A: DECLARE @jobname sysname, @jobid uniqueidentifier

SELECT @jobname=b.name,@jobid=b.job_id
FROM sys.dm_exec_sessions a,msdb.dbo.sysjobs b
WHERE a.session_id=@@spid
AND
(SUBSTRING(MASTER.dbo.FN_VARBINTOHEXSTR(CONVERT(VARBINARY(16), b.JOB_ID)),1,10)) = SUBSTRING(a.PROGRAM_NAME,30,10)


text:
Q: How do I get Gatling reports to show URLs instead of request_0 etc? I'm new to Gatling, apologies if this is a complete noob question.
The "Details" tab of my Gatling report looks like this:

The left-hand menu contains all the requests that were made. My problem is that, in all but a few rare cases, they're just labelled "request_x" instead of the URL or filename. So where there is a bottleneck I can't tell what page or resource was causing it.
I found that if I manually edit the .scala file before running the scan, I can change each one by hand, e.g. if I change...
    .exec(http("request_0")
        .get(uri01)
        .headers(headers_0)
        .resources(http("request_1")
        .get(uri02)
        .headers(headers_1)))

...to..
    .exec(http(uri01)
        .get(uri01)
        .headers(headers_0)
        .resources(http(uri02)
        .get(uri02)
        .headers(headers_1)))

...it seems to have the desired effect. But I don't want to have to change hundreds of these by hand every time I have a new test to run.
Surely there's a better way?
FWIW I'm generating this scala file using Gatling's "recorder" with an HAR file exported from Chrome, as opposed to running the recorder as a proxy. But I have tried the proxy option and got the same end result.


text:
Q: sed: How to delete second match in a file I have a file that's looking like this (pseudocode):
---
foo: bar
bar: baz
---
baz: quz
---
Some text
Some text
Some text

I need to delete the second --- row, and only that. I know that sed can do this, but I have never been able to make heads nor tails out of any sed documentation I could find...

A: With sed the easiest way would be to first read the whole file into the pattern space and work on that:
sed ':a $!{N; ba}; s/\(^\|\n\)---\n/\n/2' filename

This does
:a                       # jump label for looping
$!{                      # if the end of input is not reached
  N                      # fetch the next line, append it to the pattern space
  ba                     # go back to :a
}                        # after this, the whole file is in the pattern space.
s/\(^\|\n\)---\n/\n/2    # then: remove the second occurrence of a line that
                         # consists only of ---

@mklement0 points out that the \| only works with GNU sed. A way to work around that, since the \| is only necessary to catch --- in the first line, would be
sed ':a $!{ N; ba; }; s/^/\n/; s/\n---\n/\n/2; s/^\n//' filename

This does:
:a $!{ N; ba; }  # read file into the pattern space
s/^/\n/          # insert a newline before the first line
s/\n---\n/\n/2   # replace the second occurrence of \n---\n with \n
s/\n//           # remove the newline we put in at the beginning.

This way, the first line is no longer a special case.
Without reading the whole file into a buffer, you'll have to construct a counter from characters:
sed '/^---$/ { x; s/.*/&_/; /^__$/ { x; d; }; x; }' filename

That is:
/^---$/ {    # if a line is ---
  x          # exchange pattern space and hold buffer
  s/.*/&_/   # append a _ to what was the hold buffer
  /^__$/ {   # if there are exactly two in them
    x        # swap back
    d        # delete the line
  }
  x          # otherwise just swap back.
}

...or just use awk:
awk '!/^---$/ || ++ctr != 2' filename

A: sed is for simple substitutions on a single line. For anything else you should just use awk:
$ awk '!(/^---$/ && ++cnt==2)' file
---
foo: bar
bar: baz
baz: quz
---
Some text
Some text
Some text

A: Here's some spaghetti sed code (uses goto)
sed '/^---/ {:a;n;/^---/{d;bb};ba;:b}' file

with commentary
sed '/^---/ {      # at the first match
    :a             # label "a"
    n              # get the next line of input
    /^---/{d;bb}   # if it matches, delete the line and goto "b"
    ba             # branch to "a" (goto)
    :b             # label "b"
}' file

But I'll add my opinion that using sed for anything  complicated leads to unmaintainable code. Use awk or perl. Thanks for the opportunity to show off though ;)

A: This might work for you (GNU sed):
sed '/^---/{x;s/^/n/;/^n\{2\}$/{x;d};x}' file

Make a counter in the hold space. Every time you encounter a line beginning --- add one to the counter and if the counter is 2 delete the current line.

A: See Sed replace every nth occurrence
The solution uses awk rather than sed, but "use the right tool for the job". It may or may not be possible to do in sed but, even if it is, it will be a lot easier in a tool like awk or perl.


text:
Q: add_subplot() not working if fig = plt.figure() is in another cell in Ipython Notebook I ran into a weird problem using matplotlib in Ipython Notebook. Here is the code:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(np.random.randn(10), 'k--')
ax2 = fig.add_subplot(212)
ax2.plot(np.random.randn(10), 'r--')

This works fine and generates an inline figure with two subplots. However, if I put the same code into two cells like this:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()

ax1 = fig.add_subplot(211)
ax1.plot(np.random.randn(10), 'k--')
ax2 = fig.add_subplot(212)
ax2.plot(np.random.randn(10), 'r--')

Then there is no inline images generated at all.

A: By default, the inline backend closes a figure after a cell has been fully executed.
You're best approach is to merge those cells.


text:
Q: Ruby: Dynamically Linked Arrays I'm having some confusion about populating a new array with an existing array. It seems like if I set one array equal to the other, they become dynamically linked for the rest of the code. Is this a compiler attribute or am I not using the correct functions to store the values of one array in another? I hope this isn't an extremely basic question.
main_arr = [1, 2, 3, 4, 5]
temp_arr = main_arr
puts "Main: " + main_arr.to_s
puts "Temp: " + temp_arr.to_s

main_arr.clear
puts "Main: " + main_arr.to_s
puts "Temp: " + temp_arr.to_s

Output:
Main: [1, 2, 3, 4, 5]
Temp: [1, 2, 3, 4, 5]
Main: []
Temp: []

A: It's true, in your second line you are making temp_array point to the array object pointed by main_arr. If you want to make a copy of that array you can do
b = a.dup

A: when you do this: temp_arr = main_arr it means that temp_arr is pointing to main_arr address. use temp_arr = main_arr.dup to copy it instead.
main_arr = [1, 2, 3, 4, 5]
temp_arr = main_arr **means** temp_arr -> [1, 2, 3, 4, 5]

so, when you do this main_arr.clear -> [] and also temp_arr -> []

A: Try doing:
main_arr = [1,2,3,4,5]
temp_arr = main_arr.dup

main_arr.clear
puts main_arr # => []
puts temp_arr # => [1,2,3,4,5]


text:
Q: Webpart interaction Although I've been doing a lot of sharepoint 2010 branding lately, programming webparts is something completely new for me.

*

*I need to put together three webparts.

*I want to create a Webpart1 (Dropdownlist), Webpart2 (Checkbox) and Webpart3 (GridView)

*My grid in webpart3 should display data based on filter values from the other two webparts.
Do I have to implement connectable webparts to do this?
Ie:
http://www.c-sharpcorner.com/UploadFile/DipalChoksi/4035/
http://msdn.microsoft.com/en-us/library/dd584164(office.11).aspx
Many thanks,
KS

A: Yes, you should make the Web Parts connectable - if you really want them as three Web Parts.
Why can't you make one Web Part containing all three controls?


text:
Q: How to install CodeLite on Ubuntu? I would like to install CodeLite on my Ubuntu system, but when I try to install it using the Software Center, it gives me an error:
codelite: Depends: libgcc1 (>= 1:4.1.1) but 1:4.8.1-2ubuntu1~12.04 is to be installed
          Depends: libjpeg8 (>= 8c) but 8c-2ubuntu7 is to be installed
          Depends: zlib1g (>= 1:1.1.4) but 1:1.2.3.4.dfsg-3ubuntu4 is to be installed

If I try to install these packages trough the console it basically tells me they are already installed:
Command: sudo apt-get install libgcc1
Reading package lists... Done
Building dependency tree
Reading state information... Done
libgcc1 is already the newest version.
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

A: Per the codelite documentation, if you have an older version of codelite installed, remove it first, like so:

*

*sudo apt-get purge codelite codelite-plugins

The following commands will install the latest codelite on Ubuntu:
sudo apt-key adv --fetch-keys http://repos.codelite.org/CodeLite.asc
sudo apt-add-repository "deb http://repos.codelite.org/ubuntu/ $(lsb_release -sc) universe"
sudo apt-get update
sudo apt-get install codelite wxcrafter

The codelite PPA supports the latest stable versions of Ubuntu, and a few EOL releases, see: Supported Distributions.

Note: Trusty currently sports the 2.8v, which crashes when trying to close it.

Screenshots
14.04, with latest codelite

14.04

12.04

13.04

13.10

Reference:

*

*Howto install the latest codelite in Ubuntu - EuroBytes

*CodeLite, an open source, cross platform C/C++ IDE | LiteEditor / Repositories


text:
Q: ClojureScript extern 'on' event I'm trying to use Twitter Bootstrap's modal dialog jQuery plugin with ClojureScript, which works fine without advanced optimizations, but when Google Closure munges method names, the on method becomes za.
I've been trying to protect on from being munged by using an externs file, but so far no luck creating a definition that fixes this. Tips?

A: What finally worked was:
var jQuery;
jQuery.fn = {
  on: function() {}
};

A: with advanced you can either use goog.exportSymbol or window['object']['on'] = object['on']


text:
Q: How would one replicate this scrolling effect? https://medium.com/message/81e5f33a24e1
When you scroll down past individual sections, the background fades out as you scroll past a certain marker and the header text fades in. I assumed this was some sort of CSS transition, but I found it difficult to navigate the css on that particular site.

A: A javascript is watching the scroll:
window.onscroll = function(){
    var scroll = window.pageYOffset;
    //do smth (like if you've reached the div, add a class to it)
}

and when reaching the div to transform, you add a class to it (or you remove it upon scrolling upward). The transformations brought by this class (.reachedByScroll in my example) are then defined in css:
div.reachedByScroll .background{
    filter: blur(10px);
}
div.reachedByScroll .text{
    opacity: 1;
}

for smoothness, you can also add a transition in the css.
This answer details how things appear with scroll but not how the scrolling is slowed down. That is not what was asked.


text:
Q: Pyzmq SUB doesn't receive messages unless I use bind I have 3 processes, let's call them host and worker1 and worker2. I want worker1 and worker2 to be able to communicate with each other directly via PUB/SUB sockets (with host interjecting intermittently), so I have the following setup:
# host
socket = ctx.Socket(zmq.PUB)
socket.bind('ipc:///tmp/comms')

# worker1
socket = ctx.Socket(zmq.PUB)
socket.connect('ipc:///tmp/comms')
socket.send(b'worker1')

# worker2
socket = ctx.Socket(zmq.SUB)
socket.connect('ipc:///tmp/comms')
socket.setsockopt(zmq.SUBSCRIBE, b'worker1')
socket.recv()

As of now, this setup doesn't work. worker1 sends fine, but worker2 never seems to receive the message. However, if I now change the setup to this:
# host
socket = ctx.Socket(zmq.PUB)
socket.connect('ipc:///tmp/comms')

# worker1
socket = ctx.Socket(zmq.PUB)
socket.connect('ipc:///tmp/comms')
socket.connect(b'worker1')

# worker2
socket = ctx.Socket(zmq.SUB)
socket.bind('ipc:///tmp/comms')
socket.setsockopt(zmq.SUBSCRIBE, b'worker1')
socket.recv()

It works just fine. However, if I also bind in host, it stops working again.
Why is this? What happens if I now have workerN which also needs to subscribe to worker1, how can I bind from all the processes? What are these bind/connect semantics? Isn't host, being the long-lived process, doing the right thing by binding, and if so, why is worker2 failing to receive when it is connecting?

MWE: https://gist.github.com/ooblahman/f8f9724b9995b9646ebdb79d26afd68a
import zmq
import time
from multiprocessing import Process

addr = 'ipc:///tmp/test_zmq'

def worker1():
    ctx = zmq.Context()
    sock = ctx.socket(zmq.PUB)
    sock.connect(addr)
    while True:
        sock.send(b'worker1')
        print('worker1 sent')
        time.sleep(1)

def worker2():
    ctx = zmq.Context()
    sock = ctx.socket(zmq.SUB)
    sock.connect(addr) # Change this to bind
    sock.setsockopt(zmq.SUBSCRIBE, b'worker1')
    while True:
        sock.recv()
        print('worker2 heard')

def main():
    ctx = zmq.Context()
    sock = ctx.socket(zmq.PUB)
    sock.bind(addr) # Change this to connect (or remove entirely)

    p1 = Process(target=worker1)
    p2 = Process(target=worker2)
    p1.start()
    p2.start()

    p1.join()

if __name__ == '__main__':
    main()

A:
Q : "Isn't host, being the long-lived process, doing the right thing by binding,...?"

Well, no one can tell.There is no supporting evidence for any such claim ( "being the long-lived process" ), the less for any such deducted assumption ( "... and if so, why is worker2 failing to receive when it is connecting?" )
What we can tell is,that worker2 may try to use either of the methods, be it a { .bind() | .connect() }, successfully, yet still gets no warranty ever ( a wonderful Zen-of-Zero ) whether it will or will not POSACK on receive. That depends on many other factors, the more in distributed-computing systems:

*

*if / when / how was the TOPIC-list managed ( using and the order of call(s) to the .setsockopt( zmq.SUBSCRIBE, ... ) method ),

*if PUB-side agents did ever send any such message that was actually matching to any topic actively subscribed to or not,

*if default and / or configured resources were actually all in a state, which was sufficient for accepting any such potentially deliverable message for a transport on a .send()-er side, having all necessary means of transport from sender-side Context()-instance to the hands of the intended receiving-side Context()-instance and, finally, for a local delivery thereof via a .recv()-method on any intended receiver-side(s) or not,
so indeed not easy to say in general. Your code suffers from several principal collisions:

The worker1, in a PUB-side role will actually never deliver a bit in the first example above.

Q : "Why is this?"

Asking a PUB to setup a transport-link towards another PUB is not a legitimate ZeroMQ Formal Communication Archetype pattern - such a call to .connect()-method, responsible for asking for such a setup, ought get inspected for returning an error and the rest of the story is like observing two people, a PUB-in-host and a PUB-in-worker1, both trying to shout as much a each can into to their microphone, yet no one ever listening to a speaker, so never hearing a bit from anyone else.
Doable, yet not functional, is it?

Q : "What happens if I now have workerN which also needs to subscribe to worker1, how can I bind from all the processes?"

We need not .bind(), unless we want to.
If workerN wants to subscribe to worker1, it may .bind(), yet worker1 has no clue there has appeared any new workerN ( to which it might want to .connect() ), does it? So the .connect() is often let for the dynamically changing SUB-side N-ary cohort of the 1:N-setup ( actually being M:N, in principle ) - having the PUB-side on a known transport-class(es ... yes, can have more than one AccessPoints using more than one, ... yes, multiple transport-classes - all may get used from the one and the very same PUB-agent for communication with one or many remote SUB-agents - isn't that cool? ) - as the .bind()-(s) established a know point of access for the dynamic cohort of N-agents trying to .connect() at some unknown time in the future.


text:
Q: Why does execution continue, even after catching exception? Why does this method called via ajax continue to execute after catching an exception ?
Here's an example:
try{
    $this->save_order(); //for testing purposed, guaranteed to throw exception
    $this->set_order_number();
    $this->set_plan_id();  //WHY DOES THIS STILL EXECUTE?
}catch(Exception $e){
    header('Internal Server Error', true, 500)
    echo json_encode(array('msg'=>$e->getMessage());
    exit();
 }

The save_order method:
public function save_order()
{
     if(1==1){
       throw new exception('caught exception');
     }
}

Jquery if anyone wants to have a look at it:
$.ajax({
        'url': '/admin/payment_plan/ajax_finish_order',
        'type': 'POST',
        'dataType': 'JSON',
        'data':{'some_data': some_var},
        'success':function(status){
                  //do stuff
                 },
         'error':function(error){
                 //do stuff
                 }


text:
Q: Как задать определенную последовательность свойств в массиве объектов? Есть массив объектов следующего формата:
var arr = [
  { key: 'title', value['front end', 'back end'] }
  { key: 'location', value['london'] }
  { key: 'type', value['full-time'] }
]

Каким образом можно установить определенную очередность следования свойств в таком массиве? Например, чтобы type был первым, title - вторым, а location - третьим.

A:

var arr = [
  { key: 'title', value: ['front end', 'back end'] },
  { key: 'location', value: ['london'] },
  { key: 'type', value: ['full-time'] }
];

var keyOrder = ['type', 'title', 'location'];

arr.sort((a,b) => keyOrder.indexOf(a.key) - keyOrder.indexOf(b.key));

console.log(arr);

A: Назначить по индексу:
var arr = [];
arr[0] = {type: "bla bla"}
arr[2] = {location: "blabla"}

arr выглядит так:
[{type: "bla bla"}, empty, {location: "blabla"}]


text:
Q: How to Sort a List of Tuples based on the item order of another List I have a list: l = ['orange', 'banana', 'apple', 'pear']
I also have a list of tuples, and within each tuple the first item matches the values from prior list: list_tuples = [('pear',value),('apple',value),('orange',value),('banana',value)]
Is there any way to re-order the tuples in list_tuples based on the ordering of list l? So that the expected output of list_tuples would be [('orange',value),('banana',value),('apple',value),('pear',value)]?

A: You can write a custom key-function for sorted which consider the index (position) in the list:
>>> l = ["orange", "banana", "apple", "pear"]
>>> list_tuples = [("pear","value"),("apple","value"),("orange","value"),("banana","value")]
>>> sorted(list_tuples, key=lambda x: l.index(x[0]))
[('orange', 'value'), ('banana', 'value'), ('apple', 'value'), ('pear', 'value')]

A: You could use a for loop. But I would recommend using .sort function for a performance reasons. It also makes your code look clean.
Anyways, here is a code that does what you want.
I used a custom key to access the element's index on the first list and then use that to sort the second list. Just be aware that this only works if there are no duplicates on the first list. if there are, then you should use a for loop.
first_list = ['orange', 'banana', 'apple', 'pear']

value = 0 # value doesn't matter here.

def custom_sort(element):
    return first_list.index(element[0])

second_list = [('pear',value),('apple',value),('orange',value),('banana',value)]

second_list.sort(key=custom_sort)

print(second_list)


text:
Q: Remove only y-axis line from chat drawn using chart.js 1.0.2 How to remove only y-axis from chart,
I am using Chart.js version 1.0.2 and trying to remove using following code.
var ctx = document.getElementById("canvas").getContext("2d");
        window.myLine = new Chart(ctx).Line(lineChartData, {
            scales: {
               yAxes: [{
                   display: false
               }]},
            responsive: true
        });
Using above code not able to remove / hide it.
Is there any way to remove / hide only y-axis

A: You should create the options hash before render your chart. Check the example bellow:
var options = {
    scales: {
      yAxes: [{
        display: false
      }]
    }

var ctx = document.getElementById("canvas");
var myLineChart = new Chart(ctx, { type: 'line', data: data, options: options});

more about x and y axis cfg: http://www.chartjs.org/docs/


text:
Q: A comparison question for non-positively curved disks Let $A$ and $B$ be two closed, 2-dimensional, non-positively-curved Riemannian disks (not necessarily with convex boundary). Suppose that their boundaries $\partial A$ and $\partial B$ have the same length, and identify $\partial A$ with $\partial B$ with a length-preserving diffeomorphism of circles.  Suppose also that for every pair of points $p,q \in \partial A = \partial B$, there is a distance inequality $d_A(p,q) \le d_B(p,q)$.  Does it follow that the area of $A$ is less than or equal to the area of $B$, with equality only when $A$ and $B$ are isometric?
This is a variation of a question that arose in a joint paper that I am trying to finish.  Another version which is more relevant to the paper is about $\mathrm{CAT}(0)$ disks which are tiled by Euclidean unit equilateral triangles.

A: You could check a recent paper by Burago and Ivanov, arXiv:1011.1570: Area minimizers and boundary rigidity of almost hyperbolic metrics. They prove the statement you want when $A$ is close to being hyperbolic (but in any dimension). See their Thm 1.6. They proved earlier the same statement if A is close to being Euclidean. Actually they prove a stronger rigidity statement: if the boundary distances are equal then the interior metrics are equal, not only the areas. (Somehow this stronger rigidity statement follows from the strict minimality of the area.)
Their proof is quite involved, but in the 2d case it's possible that some elementary arguments can work, for instance using the Santalo formula which they recall in their introduction.

A: For your equality question, look at
MR1057248 (91i:53054)
Otal, Jean-Pierre(F-PARIS11)
Sur les longueurs des géodésiques d'une métrique à courbure négative dans le disque. (French) [On the lengths of the geodesics of a metric of negative curvature in the disk]
Comment. Math. Helv. 65 (1990), no. 2, 334–347.
which is a beautifully written paper, and it is quite likely that the Crofton formula which he uses there can be used to prove the sort of inequality you want. I am pretty sure that for any such result, the curvature should be strictly negative, but I could be wrong.
There are many related results proved by Chris Croke (so you might want to ask him whether what you conjecture is true), and for convex disk by Gunther Uhlmann et al (but those results, which are heavily analytic, are probably not useful to you).

A: The answer is yes. Moreover you don't need to assume that $B$ is nonpostively curved. (And, if you are not interested in the equality case or can afford a convex boundary, the nonpositive curvature of $A$ can be replaced by a weaker assumption that the geodesics in $A$ have no conjugate points).
This follows from a filling inequality that I have proved some time ago (and quite proud of it) and boundary rigidity results of Croke, Otal, or Pestov-Uhlmann.
Inequality.
There are two papers covering it:
1) S.Ivanov, On two-dimensional minimal fillings. Algebra i Analiz 13 (2001), no. 1, 26-38 (Russian); English translation in St. Petersburg Math. J., 13 (2002), no.1, 17-25. A preprint is here. In this paper the inequality $area(A)\le area(B)$ is proved under the assumptions that $A$ is free of conjugate points and has convex boundary (sorry;)) and for arbitrary $B$ such that $d_A(p,q)\le d_B(p,q)$ for all $p,q$ on the boundary.
2) S.Ivanov, Filling minimality of Finslerian 2-discs. arXiv:0910.2257, to appear in Trudy Mat. Inst. Steklov (= Proc. Steklov Inst. Math). In this paper the same thing is proved for Finslerian metrics $A$ and $B$ and without convex boundary assumptins. This is the maximum generality I can imagine. But the paper is harder to digest if you don't like Finsler metrics.
The equality of areas implies that the boundary distances of $A$ and $B$ coincide, and then you can apply boundary rigidity results mentioned below.
Rigidity.
The case you are asking for is covered by C.Croke, Rigidity for surfaces of nonpositive curvature, Comment. Math. Helv. 65 (1990), no. 1, 150–169. He proves that if $A$ is a nonpositively curved and $B$ is arbitrary Riemannian such that $d_A(p,q)=d_B(p,q)$ for all $p,q$ on the boundary, then $A$ and $B$ are isometric. He carefully works through the details of non-convex boundaries.
I have not read J.-P. Otal's paper mentioned by Igor Rivin, but from mathscinet review it seems that he assumes that both $A$ and $B$ are strictly negatively curved.
For the same result without curvature assumptions but with convex boundary, see L.Pestov and G.Uhlmann, Two dimensional compact simple Riemannian manifolds are boundary distance rigid. Ann. of Math. (2) 161 (2005), no. 2, 1093–1110.


text:
Q: how to remove a specific character from a JSON file? I have a json file where a key is a list but it has Double-quote before the square bracket and the other at the end of the square bracket. Basically it makes the list a string. I want to write a program that can remove those specific double quotes so that I can use it as a List. Here is an example of that json file.
{
   "attempts":[{
                 "image_dump":"[ {"x":247,"y":16}, {"x":248,"y":16} ]"
              }]
}

I need to remove the double quotes for the value of key 'image_dump'. So that I can use that list. I tried using the replace() method but it replaces every double quote.
How do I do it using python?

A: You can replace the specific combination of "quote following by bracket" with just a bracket by using regular expression (see https://docs.python.org/3/library/re.html). Assuming you have imported the text to sample
import re
# Replace text combination of `"[` with `[`
sample = re.sub("\"\[", "[", sample)
# Replace text combination of `]"` with `]`
sample = re.sub("\]\"", "]", sample)
# Try to read json text
json.loads(sample)


text:
Q: How to apply shadow at end corner of the circular path in flutter I need to apply the shadow for the end of the circular path like the below image. I have used the canvas.drawPath to render the path. I have tried using canvas.drawShadow but using this, the shadow gets applied whole path instead of end corner of the path.

A: Apply shadow like that and addjust this from the offset i mention below example to do this
boxShadow: [
      BoxShadow(
        color: Colors.grey[200],
        blurRadius: 2.0, // has the effect of softening the shadow
        spreadRadius: 2.0, // has the effect of extending the shadow
        offset: Offset(
          5.0, // horizontal, move right 10
          5.0, // vertical, move down 10
        ),
      )
    ],


text:
Q: STM32F072RB does not receive/send data over SPI in slave mode I am using the
STM32F072RB
uC to receive and transmit data over SPI2 in slave mode with the following configuration:
CR1 = 0x0078
CR2 = 0x0700
AFRH = 0x55353500
MODER = 0xa2a0556a

The register APB1ENR is also properly configured.
The current program just checks the RXNE flag, reads the received data from DR and sends a random value writing to DR.
The status register when I receive data has the following value:
SR = 0x1403

The master sends data properly and I checked the signals at the slave pins (clock phase and polarity are identical on both sides and the NSS signal is cleared before sending SCK and data over MOSI).
I even configured the pins as inputs and I know I could read any digital signal the master could send.
With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.
I have tried different configurations (software/hardware NSS, different data sizes, etc.) but I always get 0x00.
Moreover, the random value I send after reading DR is not sent to the outputs.
This is my current function, which is called continuously:
unsigned char spi_rx_slave(unsigned char spiPort, unsigned char *receiveBuffer)
{
    uint8_t temp;
    static unsigned long sr;
    if (!spi_isOpen(spiPort))
    {
        sendDebug("%s() Error: spiPort not in use!\r\n",__func__);
        return false;
    }
    if (spiDescriptor[spiPort]->powerdown == true)
    {
        sendDebug("%s() Error: spiPort in powerdown!\r\n",__func__);
        return false;
    }
    /* wait till spi is not busy anymore */
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(1)\r\n");
        vTaskDelay(2);
    }
    sendDebug("CR1 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR1);
    sendDebug("CR2 = 0x%04x, ", spiDescriptor[spiPort]->spiBase->CR2);
    sendDebug("AFRH address = 0x%08x, AFRH value = %08x, ", (unsigned long*)(GPIOB_BASE+0x24), *(unsigned long*)(GPIOB_BASE+0x24));
    sendDebug("MODER address = 0x%08x, MODER value = %08x\r\n", (unsigned long*)(GPIOB_BASE), *(unsigned long*)(GPIOB_BASE));
    sr = spiDescriptor[spiPort]->spiBase->SR;
    while(sr & SPI_SR_RXNE)
    {
        /* get RX byte */
        temp = *(uint8_t *)&(spiDescriptor[spiPort]->spiBase->DR);
        spiDescriptor[spiPort]->spiBase->DR = 0x53;
        sendDebug("-------->DR address = 0x%08x, data received: 0x%02x\r\n", &spiDescriptor[spiPort]->spiBase->DR, temp);
        sendDebug("SR = 0x%04x\r\n", sr);
        vTaskDelay(1);
        sr = spiDescriptor[spiPort]->spiBase->SR;
    }
    while((spiDescriptor[spiPort]->spiBase->SR) & SPI_SR_BSY)
    {
        sendDebug("SPI is busy(2)\r\n");
        vTaskDelay(2);
    }
    return true;
}

What am I doing wrong?
Is there anything I did not configure properly?
Thanks in advance.
Regards,
Javier
Edit:
I switched to software NSS and copied the register values from a STM32CubeMX example I found online. I cannot use those libraries for this project but I would like to have the same behaviour.
The new values are:
CR1 = 0x0278

which means

*

*fPCLK/256 (the proper one for the communication speed),

*SPI enabled and

*SSM = 1 (software NSS).

CR2 = 0x1700

which means

*

*8-bit data and

*RXNE event is generated if the FIFO level is greater than or equal to 1/4 (8-bit).

AFRH = 0x55303500
MODER = 0xa8a1556a

which means

*

*MISO, MOSI and SCK alternate function 5 (SPI2)

*NSS is not configured because now it is in software mode (slave is always selected).

I am still getting the same results and the eval kit with those libraries works fine using SPI1 instead.
Therefore there must be another issue that has nothing to do with the register values.
Might there be any clock issue e.g. the pins need to get some clock?
Thanks!

A: The question points to a couple of mistakes which may explain why no receive has been observed:

*

*GPIO configuration points to some wrong Alternate Functions / Modes:
The question didn't state it precisely, but I assume that

AFRH = 0x55303500
MODER = 0xa8a1556a

refers to GPIOB (otherwise, it wouldn't make sense with SPI2).
This corresponds to the following pin configuration (see the
Reference Manual,
sec. 8.4.1, 8.4.10 and the
Datasheet,
Table 16):
PB15 - Alternate Function - AF5 = [INVALID]
PB14 - Alternate Function - AF5 = [I2C2_SDA]
PB13 - Alternate Function - AF3 = [TSC_G6_IO3]
PB12 - GP Input (reset state)
PB11 - Alternate Function - AF3 = [TIM_CH4]
PB10 - Alternate Function - AF5 = [SPI2_SCK / I2S2_CK]
PB09 - GP Input (reset state)
PB08 - GP Output
PB07 - Alternate Function - (unknown which, see register AFRL)
PB06 - GP Output
PB05 - Alternate Function - (unknown which, see register AFRL)
PB04 - GP Output
PB03 - GP Output
PB02 - Alternate Function - (unknown which, see register AFRL)
PB01 - Alternate Function - (unknown which, see register AFRL)
PB00 - Alternate Function - (unknown which, see register AFRL)

This is obviously not what the software is required to do.
Solution: Make sure to configure PB15=>AF0, PB14=>AF0, either PB13=>AF0 or PB10=>AF0, depending on your hardware.
In order to avoid mistakes in doing so, you should follow the hint of @P__J__ and use speaking macros for constants assigned to MODER, AFRH etc.
Using the HAL library provided by ST is a truly controversial subject among SO users, but one should really consider to use at least a header like stm32f072xb.h with macros like GPIO_AFRH_AFSEL15.
If one represents all configuration register values as (bitwise) ORs of such macros, it is easier to re-check configuration against datasheets, and the famous
rubber duck
will directly know what an unhappy developer is talking about.

*Other clock activations might be missing:
The question confirms that

The register APB1ENR is also properly configured.

This is correct (as long as bit 14 is set).
Additionally, GPIOB must be powered, i. e., bit 18 of RCC_AHBENR must be set.
See again the
Reference Manual,
sec. 6.4.8 and 6.4.6.

*GPIO pins may be in wrong mode during debugging:

I even configured the pins as inputs and I know I could read any digital signal the master could send. With the current configuration it seems the slave receives something because the RXNE is set when the master sends data but the read value is always 0x00.

Please note that for every GPIO pin, a unique mode is selected through the MODER register. If this is set to "Input" (0b00), the Alternate Function is disconnected and won't work with external signals.


text:
Q: ideas on machine-learning algorithms to classify products I have a list of products, including variables such as the product name (as it appears on the receipt) and the merchant where the product was bought.
I have a good deal of them manually classified into a fixed group of categories (e.g. alcoholic drinks, vegetables, meat, etc.).
The data are, as always, noisy. In this case, particularly noisy because it comes from scanned receipts and OCR on not so good scans is usually very noisy.
I want to play around with algorithms to classify new data, using the two variables above.
There are several major sources of variation here:

*

*The OCR, which means a product (e.g. chicken) can be found with many different but relatively similar spelling (e.g. chiken, hicken, chicen, ...).

*The same product can have different names, according to the merchant who sold the product. In this case, the names can be either similar or completely different across merchants, but rather similar within every merchant.

*The same product can have very different names within the same merchant (e.g. branded products whose name on the receipt is the brand name, vs. generic names;  soft drink vs. coca cola).

I've tried some (kind of naive) classifier, using for example the distance between strings (which tackles mostly the first main source of variation mentioned above), but I am not very happy with the results.
So I wanted to reach out here to ask for ideas on how to tackle this problem. I guess many people have "solved" or at least worked much longer in this kind of problem than I did (a few hours) so I would really appreciate any guidance here.
By the way, I use mostly R, so R-based solutions would be greatly appreciated.

A: Addressing your issues one by one:
1) OCR: This is probably the easiest of your problems as there are many algorithms that perform well in this task. As a reference, in the best known handwritten digit dataset, MNIST, several algorithms have achieved over 99.5% accuracy (the state-of-the-art being Convolutional Neural Networks). You can also find many out-of-the-box solutions to your problem; it helps a lot if your data is in English, as the tools there are more advanced.
If your scans are noisy you may try denoising them first.
2) You need to do some preprocessing for this issue. First I would suggest, if possible, creating a bag of words, i.e. a list of all unique words in your "corpus". Verify that all these words are correct and perform a string distance comparison (e.g. hamming distance) to correct 1-2 letter typos. Another thing I would do would be to calculate the occurrences of each term in your bag and remove the least frequent ones (e.g. terms that occur less than N times in your corpus are probably typos, or remove least frequent M% of your terms). That should significantly reduce the noise in your dataset.
3) In order to solve this issue you need to perform some sort of semantic labelling. If you are familiar with ontologies, their hierarchical structure can help here a lot. You can create rules like "coca-cola" is a "soft drink" which is a type of beverage, etc.
I don't have experience in R, but I'm sure you can find tools to perform all the above quite easily.

A: It seems that you should define similarity among the entities.
You have plenty of sources for similarity. You mentioned distance on the names (edit distance) and membership in groups. Note that you can extend the similarity by groups to many group and many similarity types. Groups can be belonging to the same recipe, sold by the same merchant, belonging to the same category, etc. Similarity types might be plane belonging to the same group, weight with inverse ratio to the group size, etc. On all of the use can use transitivity. For examples, you can find similar product of a different names by using the fact that they will be used with the same products (e.g., spice X` and spice X`` will both be used with chicken).
Very soon you will have plenty of similarity relations and you will wonder how to combine them. Here come to help the labeling you already done. Take these as positive pairs of associated products. Generate sets of distinct products (not in the positives pairs) as negative pairs. Build a dataset in which the positivity is the concept and the similarities are the pairs. Now you can use supervised learning algorithm to get a model that combines the similarities into a single prediction. You can use this model to predict the association between new pair. As a bonus you will be able to evaluate the performance of the model on the dataset (e.g., accuracy, precision,...) and have more certainty in it.


text:
Q: Searching large CSV with .txt file keywords Looking for a solution to the following:
I have 1 large CSV (data.csv) file that contains:
first name | last name | phone number | email address etc
I then have a .txt file with a list of names. Text file would be formatted line by line
smith
johnson
jones

I am looking to search the large CSV, and export every full line with that contains that keyword to another CSV (Results.csv)
Example:
in Data.csv Searching "Smith, Johnson, Jones" (from keyword.txt) would export the full row (if last name matches) to results.csv.
John Smith, 1234 Main St, 1800-800-8800, etc
John Johnson, 4321 South St...

etc
Searching here, i put together a portion of what i am looking for but still need to figure out how to match the entire row based off a keyword then export it to CSV
import re

searchlist = []
with open("keyword.txt") as g:
    for line in g:
        searchlist.append(line.strip())

pattern = re.compile("|".join(searchlist))
with open("data.csv") as f:
    for line in f:

A: If you don't have a specific need for regular expressions, you can do so with:
searchlist = []
with open("keyword.txt") as g:
    for line in g:
        searchlist.append(line.strip())

with open("data.csv") as f:
    for line in f:
        if any(s in line for s in searchlist):
            print(line, end='')

case insensitive find:
        if any(s.upper() in line.upper() for s in searchlist):
            print(line, end='')

you can save a few extra cpu cycles by filling searchlist with upper() keywords as you fill it to begin with.


text:
Q: Как удалить из базы данных авторизованного пользователя? На странице имеется кнопка "Удалить аккаунт", которая ведет на страницу delete_account.php. Нужно чтобы при нажатии на нее авторизованный пользователь удалял свою строку из таблицы. Целый день мучаюсь с этой проблемой. Не подскажите как решить?
Часть кода страницы delete_account.php
    $host = 'localhost';
    $user = 'root';
    $pass = 'root';
    $db_name = 'diploma';

    $link = mysqli_connect($host, $user, $pass, $db_name);
    mysqli_query($link, "SET NAMES 'utf8'");

    if (isset($_GET['user'])) {
        $user = $_GET ['user'];
        $query = "DELETE FROM `username` WHERE `name` = 'user'";
        mysqli_query($link, $query);
    }

Не кидайтесь палками, я всего лишь прошу дать совет, я не такой опытный)
Заранее спасибо!

A: Попробуйте:
$query = "DELETE FROM `username` WHERE `name` = '$user'";

Но я бы для начала удостоверился в следующих пунктах:

*

*Подключились ли вы к базе данных вообще?

*Действительно ли в GET параметре name находится имя пользователя

*Действительно ли таблица называется username

Еще вам не мешало бы обернуть входной параметр в mysql_escape_string
$query = "DELETE FROM username WHERE name = '". mysql_escape_string($user) ."'"

Это необходимо для предотвращения SQL инъекций. Чтоб понять зачем это нужно, попробуйте без mysql_escape_string попробовать удалить юзера с именем ' or True or '(именно так, имя должно начинаться и заканчиваться с одинарной кавычки) и посмотрите, что случится в базе данных


text:
Q: NullPointerException when using getSupportActionBar I am trying to implement a simple navigation drawer in my Android app but I am not able to solve a certain bug.
Attempting to run an app throws a NullPointerException:
Process: com.emertonalex.whiskynotes04, PID: 22225
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.emertonalex.whiskynotes04/com.emertonalex.whiskynotes04.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
                  at com.emertonalex.whiskynotes04.MainActivity.setupToolbar(MainActivity.java:320)
                  at com.emertonalex.whiskynotes04.MainActivity.onCreate(MainActivity.java:97)
                  at android.app.Activity.performCreate(Activity.java:6999)
                  at android.app.Activity.performCreate(Activity.java:6990)
                  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
                  at android.app.ActivityThread.-wrap11(Unknown Source:0)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:164)
                  at android.app.ActivityThread.main(ActivityThread.java:6494)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

As far as I see it the getSupportActionBar() function call that messes stuff up. I tried covering the call with the "assert" in setupToolbar() and it seems like it passes that stage and fails at the
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
The pieces of code themselves that call the getSupportActionBar() are these:
In MainActivity
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.add_notes);
   ...
   setupToolbar();

   getSupportActionBar().setDisplayHomeAsUpEnabled(false);
   getSupportActionBar().setHomeButtonEnabled(true);
   ...
}

And
void setupToolbar(){
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

I am new to Android/Java dev and would be very appreciative of any help.
Also, it would be great if you tell me why this error appears, to begin with, so I can avoid it in the future.
Thank you

A: Changing from Support Action Bar to ActionBar should fix the issue:
getActionBar().setDisplayHomeAsUpEnabled(true);


text:
Q: HTTPS SOAP request outputs junk characters in response headers To make SOAP HTTPS call I write this method in jRuby.
def run host, port, path, soap_request_file,password,protocol = "HTTP"

    soapMsg = ""
    request = ""

    soap_request_file = Expertus::TestDataFile::get_file_relative_to_script(soap_request_file)

    soapMsg = IO.read(soap_request_file)

    request = "POST #{path} #{protocol}/1.1\r\n"
    request = request + "Content-Type: text/xml;charset=UTF-8\r\n"
    request = request + "Accept-Encoding: gzip,deflate\r\n"
    request = request + "Content-Type: application/soap+xml\r\n" if soapMsg.downcase.include?("soap-envelope")
    request = request + "Content-Length: #{soapMsg.length}\r\n"

    request = request + "Authorization: Basic #{password}\r\n"
    request = request + "\r\n"
    request = request + soapMsg
    request = request + "\r\n"

    log.debug("Trying to connect to SOAP service on #{host}:#{port}")
    # Sending request
    socket = TCPSocket.open(host,port)
    log.debug("Sending request to SOAP service")
    log.debug("#{request}")
    socket.send(request, 0)

    # Reading response
    log.debug("Reading SOAP service response")
    response = socket.read
    headers,body = response.split("\r\n\r\n", 2)
    log.debug("Received SOAP service response headers #{headers}")
    log.debug("Received SOAP service response body #{body}")
    log.debug("Closing SOAP service connection")
    socket.close
    log.debug("Connection with SOAP service closed")

    return headers,body
  end

When I make HTTP call, I get correct response back : Received SOAP service response headers HTTP/1.1 200 OK
but when I make HTTPS call, I get "Received SOAP service response headers §♥♥ ☻☻P".
Am I missing something ?


text:
Q: pandas groupby and update with min value My Dataframe:
dfd = pd.DataFrame({'A': ['Apple','Apple', 'Apple','Orange','Orange','Orange','Pears','Pears'],
                    'B': [1,2,9,6,4,3,2,1]
                   })
       A    B
0   Apple   1
1   Apple   2
2   Apple   9
3   Orange  6
4   Orange  4
5   Orange  3
6   Pears   2
7   Pears   1

Expected:
   A    new_B   old_B
0   Apple   1   1
1   Apple   1   2
2   Apple   1   9
3   Orange  3   6
4   Orange  3   4
5   Orange  3   3
6   Pears   1   2
7   Pears   1   1

The Expected dataframe: the new_values contains the minimum value of that group, For Apple the min column B value is 1 so all new values for Apple is 1 and similarly for Orange min value for column B is 3 which is replaced in new_b column.
2nd Expected Output:
Once above Expected output is achieved, I have to create sql statement for each group and write to file:
basically, iterate each row and write sql query:
sql_query= "update test_tbl "\
    "set id =  {0}"\
    "where id = {1}"\
    "and A = '{2}' ".format(new_b,old_b,A)

print(sql_query, file=open("output.sql", "a"))

A: Use GroupBy.transform for Series with same size as original df:
dfd['new_B'] = dfd.groupby('A')['B'].transform('min')
print (dfd)
        A  B  new_B
0   Apple  1      1
1   Apple  2      1
2   Apple  9      1
3  Orange  6      3
4  Orange  4      3
5  Orange  3      3
6   Pears  2      1
7   Pears  1      1

If order of columns is important use insert and rename:
dfd.insert(1, 'new_B', dfd.groupby('A')['B'].transform('min'))
dfd = dfd.rename(columns={'B':'old_B'})
print (dfd)
        A  new_B  old_B
0   Apple      1      1
1   Apple      1      2
2   Apple      1      9
3  Orange      3      6
4  Orange      3      4
5  Orange      3      3
6   Pears      1      2
7   Pears      1      1

If transform is not possible use here is alternative solution:
#aggregate by min
s = dfd.groupby('A')['B'].min()
print (s)
A
Apple     1
Orange    3
Pears     1
Name: B, dtype: int64

#insert and map
dfd.insert(1, 'new_B', dfd['A'].map(s))
dfd = dfd.rename(columns={'B':'old_B'})
print (dfd)
        A  new_B  old_B
0   Apple      1      1
1   Apple      1      2
2   Apple      1      9
3  Orange      3      6
4  Orange      3      4
5  Orange      3      3
6   Pears      1      2
7   Pears      1      1

A: I think below script work for it
import pandas as pd

dfd = pd.DataFrame({'A': ['Apple','Apple', 'Apple','Orange','Orange','Orange','Pears','Pears'],
                    'B': [1,2,9,6,4,3,2,1]
                   })

dfd_1 = dfd.groupby(['A'], as_index=False).agg({'B': 'min'})

dfd = pd.merge(dfd_1, dfd, how='left', left_on=['A'], right_on=['A'])

dfd.columns = ['A', 'new_B','old_B']


text:
Q: datestr returns multiple column char matrix instead of one column I have the following simple code:
conn = yahoo('http://download.finance.yahoo.com');
IBM = fetch(conn,{'IBM'},{'Adj Close'}, '2012-01-01','2015-08-01','d');
MO = fetch(conn,{'MO'},{'Adj Close'}, '2012-01-01','2015-08-01','d');

%IBM = [datestr(IBM(:,1),2) IBM(:,2)]
%MO = [datestr(MO(:,1),2) MO(:,2)]

The last two lines give me an error. datestr is returning a char matrix with 8 columns! 1 column per number of the date, [0,1,0,1,2,0,0,1]! How do I get the output to be 1 column?

A: I guess you want a cell array instead of a char matrix, so just use cellstr for the conversion.
IBM = cellstr([datestr(IBM(:,1),2)])
MO = cellstr([datestr(MO(:,1),2)])

respectively:
IBM = {cellstr([datestr(IBM(:,1),2)]) IBM(:,2)}
MO = {cellstr([datestr(MO(:,1),2)]) MO(:,2)}

Maybe a table is what you want:
T = table( datestr(IBM(:,1),2), IBM(:,2), datestr(MO(:,1),2), MO(:,2),...
           'VariableNames', {'IBM_T','IBM_VAL','MO_T','MO_VAL'})

T =

     IBM_T      IBM_VAL      MO_T      MO_VAL
    ________    _______    ________    ______

    07/31/15    161.99     07/31/15     54.38
    07/30/15    160.96     07/30/15      54.2
    07/29/15    161.09     07/29/15      54.4
    07/28/15    160.05     07/28/15     55.25
    07/27/15    159.07     07/27/15     53.95
    07/24/15    159.75     07/24/15     53.79
    07/23/15    161.73     07/23/15     53.82
    07/22/15    160.35     07/22/15     53.96
    07/21/15    163.07     07/21/15     53.55
    07/20/15    173.22     07/20/15     53.71
    07/17/15    172.51     07/17/15     53.22
    ...

This video about Using Tables for Financial Data may is also interesting for you.


text:
Q: Download and autorun software trials via Flash? as a software developer, I offer free trial versions of my software for download. I can see from my stats that many that download the trials don't run them. My main target user is PC novices, so I think many of them doesn't realize they have to run the downloaded installer.
Question:
Would it be possible to write a small download client in Flash, that starts when the user clicks a download button, automatically downloads my .exe file and runs it when downloaded?

A: No, that's not possible, and will be a very dangerous security flaw. You should make instructions clearer, somewhere around the download button, for your users to realize it.

A: I don't believe Flash allows any way to get such access; Adobe Air will allow you to run Flash based applications on the desktop but I do not believe it runs in the browser.  However, I do know that Java applets can allow you to do such. The user will need the Java plug-in installed. By signing your applet, you can get access if the user allows it (it will ask them Yes or No). Here is a good tutorial on how. Hope that helps!


text:
Q: Ошибка 0 rows update when that should have been 1 Используется
HeidiSQL.
MySql 5,7 х64
При добавлении(обновлении) записи в поле TINYINT (или INT).
Добавляются числа: 100, 150..
Появляется ошибка "0 rows update when that should have been 1"
CREATE TABLE `tst_001_tb_00` (
    `id` INT(11) NOT NULL,
    `pl_1_txt` TEXT NULL,
    `update_pl_2` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `pl_2_enum` ENUM('Y','N') NULL DEFAULT NULL,
    `update_pl_3` DATETIME NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `pl_3_txt` TEXT NULL,
    `pl_tinyint` TINYINT(4) NULL DEFAULT NULL,
    `pl_int` INT(11) NULL DEFAULT NULL,
    INDEX `id` (`id`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
;

Вопрос.
В чём проблема?
Скрин

A: Большинство сред разработки не могут обновлять данные в таблице, если не могут понять как уникально идентифицировать запись. В вашей таблице отсутствует первичный ключ (primary key) из за этого обновление и не проходит.


text:
Q: KNN and SVM GridsearchCV for Iris Dataset I am stuck in an issue with the query below which is supposed to plot best parameter for KNN and different types of SVMs: Linear, Rbf, Poly.
So far I wrote the query below:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn import datasets
from sklearn.model_selection import GridSearchCV
from matplotlib.colors import ListedColormap

iris = datasets.load_iris()
X = iris.data[:, :2]
y = iris.target

iris_data = iris["data"]
iris_target = iris["target"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.30, random_state=0)

param_poly = {'coef0': [0, 1], 'degree': [0, 1, 5, 7, 10], 'C': [0.1, 1, 5, 10, 100]}

# KNN
KNN = GridSearchCV(KNeighborsClassifier(),{'n_neighbors': [1, 5, 7, 10]},cv=5).fit(X_train, y_train)
# LinearSVC (linear kernel)
SVM_lin = GridSearchCV(SVC(kernel='linear'), {'C': [0.1, 1, 5, 10]},cv=5).fit(X_train, y_train)
# SVC with RBF kernel
SVM_rbf = GridSearchCV(SVC(kernel='rbf'), {'C': [0.1, 1, 5, 10]}, cv=5).fit(X_train, y_train)

# SVC with polynomial (degree 3) kernel
SVM_poly = GridSearchCV(SVC(kernel='poly'),param_poly, cv=5).fit(X_train, y_train)

# title for the plots
titles = ['KNN Plot',
          'LinearSVC (linear kernel)',
          'SVC with polynomial kernel', 'SVC with RBF kernel']

for i, clf in enumerate(KNN, SVM_lin, SVM_poly, SVM_rbf):
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, x_max]x[y_min, y_max].
    plt.subplot(2, 2, i + 1)
    plt.subplots_adjust(wspace=0.4, hspace=0.4)
    plt.title(titles[i])

def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
    # setup marker generator and color map
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])

    # plot the decision surface
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = clf.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim(xx2.min(), xx2.max())

    # Plot also the training points
    X_test, y_test = X[test_idx, :], y[test_idx]
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1],
                    alpha=0.8, c=cmap(idx),
                    marker=markers[idx], label=cl)
    # highlight test samples
    if test_idx:
        X_test, y_test = X[test_idx, :], y[test_idx]
        plt.scatter(X_test[:, 0], X_test[:, 1], c='',
                    alpha=1.0, linewidth=1, marker='o',
                    s=55, label='test set')

X_combined_std = np.vstack((X_train, X_test))
y_combined = np.hstack((y_train, y_test))
plot_decision_regions(X_combined_std,
                      y_combined, classifier=clf,
                      test_idx=range(105, 150))
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=plt.cm.coolwarm)
plt.scatter(x=iris_data[iris_target == 0][:, 0], y=iris_data[iris_target == 0][:, 1], color="tab:blue",
            label="iris_setosa")
plt.scatter(x=iris_data[iris_target == 1][:, 0], y=iris_data[iris_target == 1][:, 1], color="tab:orange",
            label="iris_versicolor")
plt.scatter(x=iris_data[iris_target == 2][:, 0], y=iris_data[iris_target == 2][:, 1], color="tab:green",
            label="iris_virginica")
plt.xticks(())
plt.yticks(())
plt.legend()

plt.show()

Please help me plot like the results shown in the figure, the code also takes time to execute maybe could be done faster.


text:
Q: Elasticsearch bulk update with script very slow I am sending 1000 at a time to Elasticsearch Bulk API
I have a scenario where i want to update a field inside a document which is equivalent to the multiplication of two fields in the same document. Here is how i am building my query via PHP client
{ "update" : { "_id" : "0", "_type" : "type1", "_index" : "index1"} }
{ "script" : { "inline": "ctx._source.x=ctx._source.y*ctx._source.z"} }

I am using PHP client for this which sends 1000 at one go.
For total of 185000 records its taking 30 mins. Is there any way that i can optimize it ?

A: If yours script is different from document to document only by factor/parameter then you can create appropriate stored script and then  use it in partial update with unique parameter value for each document. This way elastic won't bother with script recompile for each document and byte payload of bulk request will be significantly smaller.


text:
Q: Format LT datetimepicker : always returns today's date I've to use the bootstrap datetimepicker for a legacy project.
With "LT" format, I've an issue, even if I set a default date, it returns the current date. (today).
check it on
codepen
$(function () {
  $('#datetimepicker3').datetimepicker( {
    defaultDate: moment("15/05/1992","DD/MM/YYYY"),
    format: 'LT'
  });

  $('#datetimepicker3').on('dp.change',function(){
    console.log('-');
    console.log($('#datetimepicker3').data('DateTimePicker').date());
    console.log($('#datetimepicker3').data('DateTimePicker').date().format('DD/MM/YYYY HH:mm'));
    console.log('-');
  });
});

I need to receive the date I set by default in datetimepicker.
Thanks.

A: I think the problem is exactly because you are using 'LT'. LT is a format of TIME-ONLY, so the information about the date is lost. That way, when it transform the "only time" information to a date or moment object, it uses the current date.
The defaultDate is to set the initial date/time for the component and not to define the date that will be used when dealing with time-only information.
My suggestion: take the value from the component (as you did), extract the time and then set the desired date for that time.
I hope it helps.


text:
Q: 'Sliding cards' using ScrollMagic See here: https://jsfiddle.net/xqxur32w/
I am trying to achieve a 'sliding card' effect where one card will slide up as you scroll down, while the others don't move. As soon as the sliding card hits the top of the view, the following card will start moving. In code, I am using scrollmagic to pin all cards initially, pin the first moving card as soon as it reaches the top, and then unpin the following one as soon as the previous one reaches the top (sorry if this sounds confusing, happy to clarify). There is a 'jumping effect', however, and it breaks the effect. Any idea what could be going wrong here?
Thanks!
$(function() {
  // get all cards
  var cards = document.querySelectorAll(".card");
  //init controller
  var controller = new ScrollMagic.Controller({
    globalSceneOptions: {
      triggerHook: 'onLeave'
    }
  });
  //pin the 0th card as soon as it reaches the top
  new ScrollMagic.Scene({
      triggerElement: cards[0]
    })
    .setPin(cards[0])
    .addTo(controller);
  //pin all others
  new ScrollMagic.Scene({})
    .setPin(cards[1])
    .addTo(controller);
  new ScrollMagic.Scene({})
    .setPin(cards[2])
    .addTo(controller);
  new ScrollMagic.Scene({})
    .setPin(cards[3])
    .addTo(controller);
  new ScrollMagic.Scene({})
    .setPin(cards[4])
    .addTo(controller);

  //unpin the first card when the 0th card reaches the top
  new ScrollMagic.Scene({
      triggerElement: cards[0],
    })
    .setPin(cards[1])
    .addTo(controller);
});


text:
Q: How can I pass a UserControl from a Plugin to my main window using MVVM? I have a plugin based application where I am discovering plugins using Mono.Addin.  Each plugin has its own View and ViewModel and I am not sure the best method to pass the View down to the MainView.  At the moment my MainView is binding to an object type on my MainViewModel, but this requires me to have UI specific logic in my plugin ViewModel.  I am not entirely comfortable doing this but cant think of a better way.
My MainViewModel has this
public object Content

and my PluginViewModel does this
this.MainViewModel.Content = ViewLocator.Current.ResolveView(this);

A: If you're using MVVM then the usual way of creating a view from a view model is via data templating, and in order for that to work both the view and data template need to be merged into the application's global ResourceDirectory. There's another answer here that shows to do that with the MEF plugin architecture but it shouldn't be too difficult to adapt to others.


text:
Q: Can servos be powered in series? Can two 6V servos be connected in series to a 12V source, or do servos behave differently than regular motors when it comes to voltage?

A: I assume you mean RC servos, with a three-wire connection consisting of power, ground, and a PWM signal.

Can two 6V servos be connected in series to a 12V source,

Not if you want them to work.  First, the "top" servo in the string will have its signal line referenced to the "bottom" servo's power line; unless you make a special interface, the PWM signal will be wrong.
Even if you did make such an interface, servos expect constant voltage, and take as much current as they need to go to their commanded position.  As soon as one servo needs more current than the other, it'll pull its own voltage way down and fail to work.  At the same time (since the voltage is shared) the other servo will see too much voltage, and would probably suffer damage from overvoltage.

or do servos behave differently than regular motors

Yes, they do.  Servos are a motor, geartrain and control electronics all in one package.  They act considerably different than simple DC motors.

when it comes to voltage?

Who says that regular DC motors work "right" when connected in series?  There are some applications where they may work "right", but others where they'll be "wrong".
Two DC motors connected in series will tend to have the same output torque, and the sum of their speeds will tend to be fairly constant.  If you're trying to drive a pair of loads that have a strongly positive torque vs. speed reaction (i.e., each motor driving a propeller or centrifugal pump) then the motors would tend to settle out at the same speed.  But if you're trying to drive a pair of loads that have constant torque, or a negative torque vs. speed reaction, then one motor will start up and "steal" all the voltage from the other motor, which will never start.


text:
Q: React Axios get call doesn't work with authorization header I am working on a Axios get in the react which need authorization.
Before I add the authorization, it worked well, and after I add the authorization header in the backend and frontend, it has CORS error. I tried the get call in the postman and it works very. So I think it shall be Axios get code in the frontend.
Here is Axios get code:
async sendGetRequest(variable) {
        return new Promise((resolve, reject) => {
            let AuthStr = 'token';
            console.log(typeof(AuthStr)); => the type is String
            Axios.get(`url/${variable}`,{
                header:{
                    'Authorization': AuthStr
                }
            })
                .then(res => {
                    resolve(res.data)
                }
                );
        })
    }

I am not sure it's wrong, looks good for me.
Here is my postman result.(I hide the url)

A: I closed this post by myself.
Because I made a typo mistake
it  shall be
headers:{
          'Authorization': AuthStr
      }

Hope it will be helpful for others.


text:
Q: How to generate new line character in telegram message? When I send the data I read from mysql database to telegram user, the user gets underline and etc instead of new line character. So this way I can't format message text correctly.
How can I format a telegram message that is a question with 4 or more possible answers?
What else is going to be changed that I don't expect? By the way I'm sending non-english characters.
$qsBody = $rowQuestion['body']; // This is what I read from database that contains some new line characters
$strReply = $qsBody;
$strSendMethod = "SendMessage?chat_id=$ChatId&text='$strReply'";
file_get_contents( BOT_TARGET_ADDRESS . $strSendMethod );
// The message received by user contains _ instead of new line.

A: Well, it was very easy! I just had to encode message in url.
$qsBody = $rowQuestion['body']; // This is what I read from database that contains some new line characters
$strReply = $qsBody;
$strReply = urlencode($strReply ); // encode message
$strSendMethod = "SendMessage?chat_id=$ChatId&text='$strReply'";
file_get_contents( BOT_TARGET_ADDRESS . $strSendMethod );
// The message received by user contains _ instead of new line.

A: you can use some code like this:
$text = 'hi-how are you?_im fine.lets go';
$text = str_replace(array('_', '-', '.'), chr(10), $text);

the code, replace underline _, - and . character with line break.

A: sendMessage is with "s" lowercase.
 $qsBody = $rowQuestion['body']; // This is what I read from database that contains some new line characters
    $strReply = $qsBody; // set here your message with \n where you want a new line
    $strSendMethod = "sendMessage?chat_id=$ChatId&text='$strReply'";
    file_get_contents( BOT_TARGET_ADDRESS . $strSendMethod );

try here https://telegram-bot-sdk.readme.io/docs/sendmessage


text:
Q: soapui 5.x script assertion not implemented for json error since upgrading to the latest soapUI pro version (5.1.2) I have noticed that I cannot right click on a node in the outline response mode and use the 'Add Assertion -> for Existence with Script' feature. This feature works in the older versions of soapUI. I need this because I need to get the correct namespace setting for the node I want to assert.
Does anyone know if this is a limitation of the newer version or soapUI ? or do I need to tweak the configuration somewhere?


text:
Q: Angular location.onPopState is not triggering sometimes when the browser back button is pressed I am using CanDeactivateGuard in my Angular application where i have handled the browser back button using location.onPopState to show an alert.
But when i click the browser button first and cancel the alert box which is shown and click the browser button it doesn't shows the alert back when i put logs for the location.onPopState it calls the location.onPopState but it doesn't calls the canDeactivateGuard
@Injectable()
export class CanDeactivateGuard implements CanDeactivate<CanComponentDeactivate> {
  backButtonClicked = false;
  constructor(public location: LocationStrategy) {
    location.onPopState(() => {
      console.log('location popstate got called', location);
      this.backButtonClicked = true;
    });
  }

  canDeactivate(component: CanComponentDeactivate) {
    console.log('canDeactive called', this.backButtonClicked);
    if (this.backButtonClicked) {
      this.backButtonClicked = false;
      history.pushState(null, null, location.href);
    }
    return component.canDeactivate ? component.canDeactivate() : true;
  }
}

I have used a custom navigation service which listens for the router events but when the location.onPopState is called and then the canDeactivate is not triggered then at the same time the router events are also not called.
@Injectable({ providedIn: 'root' })
export class NavigationService {
  private history: string[] = [];
  private goingBack = false;

  constructor(private router: Router, private location: Location) {
    this.router.events.subscribe((event) => {
      console.log('event is', event);
      if (event instanceof NavigationStart && event.navigationTrigger === 'popstate') {
        this.back();
      } else if (event instanceof NavigationCancel) {
        this.goingBack = false;
        console.log('history in cancel', this.history);
      } else if (event instanceof NavigationEnd) {
        this.historyPop(event);
      }
    });
  }

  historyPop(event): void {
    console.log('event in history pop is', event);
    if (this.goingBack) {
      this.history.pop();
      this.history.pop();
    }
    this.goingBack = false;
    this.history.push(event.urlAfterRedirects);
    console.log('history is', this.history);
  }

  back(): void {
    const urlToback = this.history[this.history.length - 2];
    this.goingBack = true;
    if (urlToback) {
      this.router.navigateByUrl(urlToback);
    } else {
      this.router.navigateByUrl('/');
    }
    console.log('history in back is', this.history);

  }

  replaceState(url: string): void {
    this.history[this.history.length - 1] = url;
    this.location.replaceState(url);
  }
}


text:
Q: Creating a column for a View from two different tables (SQL Server) I have three tables A, B and C in a SQL Server, B and C share the same foreign key (AgencyID) from A, and they also share one same column name: AgencyName
Table A: AgencyID, AgencyDate,
Table B: AgencyID, AgencyNumber, AgencyName
Table C: AgencyID, AgencyInvoiceNumber, AgencyName
To help you understand the relationship, basically these 3 tables are generated with Entity Framework, where B and C each extends A.
Now I am trying to create one View from these three tables in the following way:
CREATE VIEW [rdo].[Agencies] AS
SELECT
    A_1.AgencyID, A_1.AgencyDate,
    dbo.B.AgencyNumber, dbo.B.AgencyName,
    dbo.C.AgencyInvoiceNumber, dbo.C.AgencyName
FROM dbo.A AS A_1 LEFT OUTER JOIN
        dbo.B ON A_1.AgencyID = dbo.B.AgencyID LEFT OUTER JOIN
        dbo.C ON A_1.AgencyID = dbo.C.AgencyID

Now, apparently the script errors about AgencyName that column name in a view should be unique :( How would I go about this so that both AgencyName values from B and C are merged into one view?
Note: I know the example isn't perfect as one could just move the column to table A, but it's just a simplified example, in reality I really cannot simply move the column :(

Reason for having to have duplicated columns in B and C:
Here's the relationships:
            A
           / \
          A1  A2
         /      \
        B        C

A1 and A2 extends A, B and C extends A1 and A2 respectively. AgencyName is an unique attribute that only B and C has. I know a refactoring could be done here to try to get rid of this weird hierarchy, but this legacy project has already grown too big and I cannot afford the cost atm.

A: Give different names to those columns in the view whose name are same in your tables like below
CREATE VIEW [rdo].[Agencies] AS
SELECT
    A_1.AgencyID, A_1.AgencyDate,
    dbo.B.AgencyNumber, dbo.B.AgencyName AS AgencyName_B,
    dbo.C.AgencyInvoiceNumber, dbo.C.AgencyName AS AgencyName_C
FROM dbo.A AS A_1 LEFT OUTER JOIN
        dbo.B ON A_1.AgencyID = dbo.B.AgencyID LEFT OUTER JOIN
        dbo.C ON A_1.AgencyID = dbo.C.AgencyID

A: CREATE VIEW [rdo].[Agencies] AS
SELECT
    A_1.AgencyID, A_1.AgencyDate,
    dbo.B.AgencyNumber, dbo.B.AgencyName as AgencyNameB,
    dbo.C.AgencyInvoiceNumber, dbo.C.AgencyName as AgencyNameC,
FROM dbo.A AS A_1 LEFT OUTER JOIN
        dbo.B ON A_1.AgencyID = dbo.B.AgencyID LEFT OUTER JOIN
        dbo.C ON A_1.AgencyID = dbo.C.AgencyID

give alice name  to AgencyName column.
In your case the table dbo.table.AgencyName will have a column called 'AgencyName' for Tables B and C . That is the problem. Give alicename to any one of the column or both.

A: Try using COALESCE to pick the first non null AgencyName:
CREATE VIEW [rdo].[Agencies] AS
SELECT
    A_1.AgencyID, A_1.AgencyDate,
    dbo.B.AgencyNumber,
    COALESCE(dbo.B.AgencyName, dbo.C.AgencyName) As AgencyName,
    dbo.C.AgencyInvoiceNumber
FROM dbo.A AS A_1 LEFT OUTER JOIN
        dbo.B ON A_1.AgencyID = dbo.B.AgencyID LEFT OUTER JOIN
        dbo.C ON A_1.AgencyID = dbo.C.AgencyID

You may face the issue where AgencyName is different in B & C in which case you will need a set of rules to follow.
My recommendation is to only have AgencyName in one of the tables (Table A?) otherwise you face potential update discrepancies.


text:
Q: Java Generics? with identifier exception This is a code Snippet from an old exam. Can someone provide me the answer and tell me why.
import java.util.*;
abstract class A {
  abstract void tu();
}
class P extends A {
  char c = 'c';
  P(char c){ this.c = c; }
  P(){ new P('p'); }
  public void tu (){ System.out.printf("P.tu->%c\n", c); }
}
class K extends P {
 char c = 'c';
 K(char c){ this.c = c; }
 K(){ new K('k'); }
 public void tu (){ System.out.printf("K.tu->%c\n", c); }
}
 class E extends K {
 char c = 'c';
 E(char c){ this.c = c; }
 E(){ new E('e'); }
 public void tu (){ System.out.printf("E.tu->%c\n", c); }
}
class G extends E {
 char c = 'c';
 G(char c){ this.c = c; }
 G(){ new G('g'); }
 public void tu (){ System.out.printf("G.tu->%c\n", c); }
}

public class Question {

  static void magic( Queue< ? super … > q ){ ← which class is allowed and why?
   q.add( new E('?') );
  }

  public static void main( String[] args ){
    Queue<K> q = new LinkedList<K>();
    magic(q);
    while ( ! q.isEmpty() ) { q.poll().tu(); }
  }
}

I copied it in BlueJ and did it like:
 static void magic( Queue<? super K > q );
  q.add(new E('?') );
 }

but then i get an identifier exception..
Thanks in advance!!!
Hans

A: This is the Lower Bounded Wildcards: https://docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html.
For the question: which class is allowed and why?
The Answer: A, because A is the parent of all theses classes. And we can use it for reference to all of them.