问:
How to calculate the average of class fields
Given that you have five input values and "average" method, calculate the average value for the five input values inside the average method and return it.
Note: average is the total summation of the values divided by its count</p>

```<code>public class MyCalculator {

    int input1 = 10;
    int input2 = 20;
    int input3 = 30;
    int input4 = 40;
    int input5 = 50;

    public float average() {

             return 0;
    }
}
</code>```

答:
I recommend you to use this function to calculate average :</p>

```<code>public float avg(int ...a)
{
    int sum = 0;

    for(int i=0 ; i<a.length ; i++)
    {
        sum += a[i];
    }

    return (sum/a.length) ;
}
</code>```

Body:
Given that you have five input values and "average" method, calculate the average value for the five input values inside the average method and return it.
Note: average is the total summation of the values divided by its count

public class MyCalculator {

    int input1 = 10;
    int input2 = 20;
    int input3 = 30;
    int input4 = 40;
    int input5 = 50;

    public float average() {

             return 0;
    }
}

Body:
I recommend you to use this function to calculate average :

public float avg(int ...a)
{
    int sum = 0;

    for(int i=0 ; i<a.length ; i++)
    {
        sum += a[i];
    }

    return (sum/a.length) ;
}


来源: stackexchange

问:
Binding derived class method in C++ to be called from separated std::function variable, outside the scope of the instance
Consider having a base class that is inherited by multiple sub-classes.

Is it possible to bind some of its methods to create function that can be called directly and not from the inherited class instance.

The following example should emphasis the case :

```<code>
class A {
    virtual void method(int a, int b) { ... }
};

class B : public A {
    virtual void method(int a, int b) { ... }
};
class C : public A {
    virtual void method(int a, int b) { ... }
};

void main () {

    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = std::bind(&A::method, &a);
    std::function<void(int,int)> f2 = std::bind(&A::method, &aa);

    f(1,2);
    f(2,3);
    ...
}

</code>```

however, it doesn't compile due to the following error :

No viable conversion from '__bind<void (A::*)(int, int), A **>' to 'std::function<void (int, int)>'

Perhaps anybody can help me fix it ?

答:
You need to use placeholders for your arguments. I would also remove the reference from the second argument as you've a pointer already and passing a reference to a pointer would pass in the address of pointer which is not what you want.

```<code>std::function<void(int,int)> f1 = std::bind(&A::method, a, std::placeholders::_1, std::placeholders::_2);
</code>```

Hope this helps.

ContentLicense: CC BY-SA 4.0

Body:
Consider having a base class that is inherited by multiple sub-classes.

Is it possible to bind some of its methods to create function that can be called directly and not from the inherited class instance.

The following example should emphasis the case :

class A {
    virtual void method(int a, int b) { ... }
};

class B : public A {
    virtual void method(int a, int b) { ... }
};
class C : public A {
    virtual void method(int a, int b) { ... }
};

void main () {

    A * a = new B();
    A * aa= new C();

    std::function<void(int,int)> f1 = std::bind(&A::method, &a);
    std::function<void(int,int)> f2 = std::bind(&A::method, &aa);

    f(1,2);
    f(2,3);
    ...
}

however, it doesn't compile due to the following error :

No viable conversion from '__bind<void (A::*)(int, int), A **>' to 'std::function<void (int, int)>'

Perhaps anybody can help me fix it ?

Body:
You need to use placeholders for your arguments. I would also remove the reference from the second argument as you've a pointer already and passing a reference to a pointer would pass in the address of pointer which is not what you want.

std::function<void(int,int)> f1 = std::bind(&A::method, a, std::placeholders::_1, std::placeholders::_2);

Hope this helps.


问:
PHP class that sorts an ordered integer array with the help of sort() function
I have written down the following for the above question

```<code><?php

class sortClass{

  public function __construct(array $arrayPassed){
    return sort($arrayPassed);
    }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted);

?>
</code>```

And the output is 'sortClass Object()' , I'd like some help to understand why it would not print out the sorted array , When we instantiate a class - the constructor will automatically execute and return what ever it returns right? so why isn;t printing $sorted object printing whats returned in the constructor?

答:
https://www.php.net/manual/en/language.oop5.basic.php

You misunderstood OOP, you need to learn about it before write code.
I give a workaround just for the idea:

```<code>class sortClass
{
    public $sorted;

    public function __construct(array $arrayPassed)
    {
        sort($arrayPassed);
        $this->sorted = $arrayPassed;
    }
}

$newarray = array(11, -2, 4, 35, 0, 8, -9);
$sorted = new sortClass($newarray);
var_dump($sorted->sorted);
</code>```

Body:
I have written down the following for the above question

<?php

class sortClass{

  public function __construct(array $arrayPassed){
    return sort($arrayPassed);
    }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted);

?>

And the output is 'sortClass Object()' , I'd like some help to understand why it would not print out the sorted array , When we instantiate a class - the constructor will automatically execute and return what ever it returns right? so why isn;t printing $sorted object printing whats returned in the constructor?

Body:
https://www.php.net/manual/en/language.oop5.basic.php

You misunderstood OOP, you need to learn about it before write code.
I give a workaround just for the idea:

class sortClass
{
    public $sorted;

    public function __construct(array $arrayPassed)
    {
        sort($arrayPassed);
        $this->sorted = $arrayPassed;
    }
}

$newarray = array(11, -2, 4, 35, 0, 8, -9);
$sorted = new sortClass($newarray);
var_dump($sorted->sorted);


问:
regex with 'Named Capture Group' to catch a pattern or an alternate one
I try to catch with one unique regex

```<code>either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic
</code>```

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

```<code>import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""
</code>```

So we get:

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>
</code>```

or

```<code>>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>
</code>```

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

```<code>PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).
</code>```

If I try the @the-fourth-bird regex I get:

```<code>In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:
</code>```

答:
Given the limited example of yours, I can't see why the following is not enough:

```<code>r'\sPIC\s((?:(?:[SV]\d|X))?\((?:\d+)\))+( COMP-3)?\.'
</code>```

There's no need, for instance, to use \s+ if there's always only 1 space as in your example.

Similarly there's no reason not to use the literal COMP-3 in the regex, if you don't tell us how that bit can vary (e.g. It's COMP- followed by an integer number of any number of digits? Ok, fine, use COMP-\d+).

Body:
I try to catch with one unique regex

either: ' PIC S9(17).'            # with 'S9(17)'      in Named Capture Group pic
either: ' PIC S9(13)V9(2).'       # with 'S9(13)V9(2)' in Named Capture Group pic
either: ' PIC S9(9)V9(2) COMP-3.' # with 'S9(9)V9(2)'  in Named Capture Group pic
either: ' PIC X(16).'             # with 'X(16)'       in Named Capture Group pic

with r'\s*PIC\s+(?P<pic>\S+)'
  I catch all but ' PIC S9(9)V9(2) COMP-3.'

with r'\s*PIC\s+(?P<pic>\S+) COMP-3'
  I catch only ' PIC S9(9)V9(2) COMP-3.'

This is my Python code:

import re
def get_pics(data, pic):
    base = r'^(?P<level>\d{2})\s+(?P<name>\S+)'
    end = r'\.$'
    pformat = "({})?"
    pattern = re.compile(base + pformat.format(pic) + end)

    for row in data.strip().split('\n'):
        re_match = pattern.match(row.strip())
        if not re_match:
            print(' => NOP:\n    ', row)
        else:
            match = re_match.groupdict()
            print('ok:', match)

data = """
   12 M-AR03-MONTANT-RDJ                 PIC S9(17).
   12 M-AR03-COMPTE-RDJ                  PIC X(8).
  09 M-N014-INC-CHARG-AMT-FSOL           PIC S9(9)V9(2) COMP-3.
  09 M-N014-CHARGE-TYPE-FSOL             PIC X(5).
"""

So we get:

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+)')
ok: {'level': '12', 'name': 'M-AR03-MONTANT-RDJ', 'pic': 'S9(17)'}
ok: {'level': '12', 'name': 'M-AR03-COMPTE-RDJ', 'pic': 'X(8)'}
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL  PIC S9(9)V9(2) COMP-3.
ok: {'level': '09', 'name': 'M-N014-CHARGE-TYPE-FSOL', 'pic': 'X(5)'}
>>>

or

>>> get_pics(data, r'\s*PIC\s+(?P<pic>\S+) COMP-3')
 => NOP:
     12 M-AR03-MONTANT-RDJ         PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ       PIC X(8).
ok: {'level': '09', 'name': 'M-N014-INC-CHARG-AMT-FSOL', 'pic': 'S9(9)V9(2)'}
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL  PIC X(5).
>>>

What is strange is that in https://regex101.com/ the '\s*PIC\s+(?P<pic>\S+)'
match for all 4 lines:

PIC S9(17).
PIC S9(13)V9(2).
PIC S9(9)V9(2) COMP-3.
PIC X(16).

If I try the @the-fourth-bird regex I get:

In [2]: get_pics(data, r'\bPIC (?P<pic>(?:[A-Z]\d*\(\d+\))+)[^.\r\n]*\.')
   ...:
 => NOP:
     12 M-AR03-MONTANT-RDJ          PIC S9(17).
 => NOP:
        12 M-AR03-COMPTE-RDJ           PIC X(8).
 => NOP:
       09 M-N014-INC-CHARG-AMT-FSOL    PIC S9(9)V9(2) COMP-3.
 => NOP:
       09 M-N014-CHARGE-TYPE-FSOL      PIC X(5).

In [3]:

Body:
Given the limited example of yours, I can't see why the following is not enough:

r'\sPIC\s((?:(?:[SV]\d|X))?\((?:\d+)\))+( COMP-3)?\.'

There's no need, for instance, to use \s+ if there's always only 1 space as in your example.

Similarly there's no reason not to use the literal COMP-3 in the regex, if you don't tell us how that bit can vary (e.g. It's COMP- followed by an integer number of any number of digits? Ok, fine, use COMP-\d+).


问:
ImportError: libopencv_hdf.so.3.1: cannot open shared object file: No such file or directory
I am trying to run my test cases in Bitbucket-pipeline but it is showing
an error message.

Screenshot of Bitbucket-pipeline.yml

```<code>_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>   import cv2
E   ImportError: libopencv_hdf.so.3.1: cannot open shared object file: No such file or directory

**ImportError**
</code>```

答:
that's because you might have pasted another cv2.so file which is overlapping go ahead and open a terminal and type

```<code>cd /lib/python3/dist-packages
and then
ls
</code>```

you will see cv2.so , copy it on desktop as a backup so incase if i am wrong you won't lose it

type :

```<code>cp cv2.so /home/ubuntu/cv2.so
</code>```

and then type this to delete it

```<code>rm cv2.so
</code>```

now type

```<code>python3
import cv2
</code>```

and you're done ...

a proof of concept :

check here the image

and after deleting it :

last one after importing

Body:
I am trying to run my test cases in Bitbucket-pipeline but it is showing
an error message.

Screenshot of Bitbucket-pipeline.yml

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
>   import cv2
E   ImportError: libopencv_hdf.so.3.1: cannot open shared object file: No such file or directory

**ImportError**

Body:
that's because you might have pasted another cv2.so file which is overlapping go ahead and open a terminal and type

cd /lib/python3/dist-packages
and then
ls

you will see cv2.so , copy it on desktop as a backup so incase if i am wrong you won't lose it

type :

cp cv2.so /home/ubuntu/cv2.so

and then type this to delete it

rm cv2.so

now type

python3
import cv2

and you're done ...

a proof of concept :

check here the image

and after deleting it :

last one after importing


问:
How to remove WP sidebar widget header regardless of theme
I would like to create WP sidebar widget similar to this
one:

As you can see its fully graphic and I want it to keep style regardless of WP theme installed.

How can I do that within WP ?

I mean to remove H tags or other unneeded tags for this particular widget ?

答:
Start here: http://justintadlock.com/archives/2009/05/26/the-complete-guide-to-creating-widgets-in-wordpress-28

Next: http://divitodesign.com/css/style-wordpress-widgets-with-css/

In order the have the widget's style be theme neutral, you'll need to set or load the css within the widget function, so your specific selectors and graphics would be universally applied.

ContentLicense: CC BY-SA 3.0


问:
Extract complete url from a text in android
I want to extract complete url from a large text such that the complete url incuding the parameters are needed to be extraxted.

It should support all url format...

Eg of urls

www.facebook.com/mainhoon/jikii/50

http://www.alphabet.com?user=50&tyn=40

m.gmail.com
etc

Eg of text:

hi hello howe are you look at my code http://www.stackoverflow.com?adiadajda here we got the answer also check this url www.myspace.in that gives bla bla bla

答:
Extract single url via Kotlin</p>

```<code>private fun extractUrl(input: String) =
        input
            .split(" ")
            .firstOrNull { Patterns.WEB_URL.matcher(it).find() }
</code>```

Body:
Extract single url via Kotlin

private fun extractUrl(input: String) =
        input
            .split(" ")
            .firstOrNull { Patterns.WEB_URL.matcher(it).find() }


问:
Javascript - Create a currying function returning the list of parameters
I'm trying to create a currying function returning the list of parameters but I don't how to make it.
This is my code :

const getParameters = arg => {
  const parameters = [];

  const innerFunction = arg => {
    parameters.push(arg);
    return innerFunction;
  };
  return innerFunction(arg);
};

getParameters(1)(2)(5); // => expected value [1,2,5]
getParameters(1)(2)(5)(20); // => expected value [1,2,5,20]
```

答:
UPDATE: Support unlimited arguments.
PS: only limitation is when you need to end the call, you have pass last call as null or undefined or empty as shown below.

const getParameters = a => {
  const parameters = [a];
  const innerFunction = b => {
    if (b) {
      parameters.push(b);
      return innerFunction;
    }
    return parameters;
  };
  return innerFunction;
};

console.log(getParameters(1)(2)(5)());
console.log(getParameters(1)(2)(5)(9)(20)(22)());```


答:
AS Nigel Ren explain you can't return from a constructor method. You need a new method to return the sorted the value. Check my code

```<code>class sortClass{
  private $sortedArray;

  public function __construct(array $arrayPassed){
    $this->sortedArray = asort($arrayPassed);
    }

  public function  getSortedArray(){
     return $this->sortedArray;
  }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted->getSortedArray());
</code>```

Title: PHP class that sorts an ordered integer array with the help of sort() function

Body:
AS Nigel Ren explain you can't return from a constructor method. You need a new method to return the sorted the value. Check my code

class sortClass{
  private $sortedArray;

  public function __construct(array $arrayPassed){
    $this->sortedArray = asort($arrayPassed);
    }

  public function  getSortedArray(){
     return $this->sortedArray;
  }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted->getSortedArray());


问:
Missing argument self when scheduling method
I'd like to schedule a method using the schedule module but it doesn't work.

The error message is as follows:

Warning: Missing Argument 'self'.

Here is my code:

```<code>def p_b(self):
    do
    print('hello')
    do
    do

schedule.every().minute.do(p_b)

while True:
    schedule.run_pending()  # error comes out.
    time.sleep(1)
</code>```

答:
As the error indicates, you added "self" to the method. Self represent an instance of a class that is passed automatically when you make a call, see here fore more info.

So try to remove the self parameter and it should just work:

```<code>import schedule
import time

def p_b():
    print('hello')

schedule.every().minute.do(p_b)

while True:
    schedule.run_pending()
    time.sleep(1)
</code>```

Edit

If you do have that method inside a class and you have the scheduler outside, you need to call it from an instance of the class e.g.:

```<code>import schedule
import time

class SomeClass:
    def p_b(self):
        print('hello')

if __name__=='__main__':
    some_class = SomeClass()

    schedule.every().minute.do(some_class.p_b)

    while True:
        schedule.run_pending()
        time.sleep(1)
</code>```

Body:
I'd like to schedule a method using the schedule module but it doesn't work.

The error message is as follows:

Warning: Missing Argument 'self'.

Here is my code:

def p_b(self):
    do
    print('hello')
    do
    do

schedule.every().minute.do(p_b)

while True:
    schedule.run_pending()  # error comes out.
    time.sleep(1)

Body:
As the error indicates, you added "self" to the method. Self represent an instance of a class that is passed automatically when you make a call, see here fore more info.

So try to remove the self parameter and it should just work:

import schedule
import time

def p_b():
    print('hello')

schedule.every().minute.do(p_b)

while True:
    schedule.run_pending()
    time.sleep(1)

Edit

If you do have that method inside a class and you have the scheduler outside, you need to call it from an instance of the class e.g.:

import schedule
import time

class SomeClass:
    def p_b(self):
        print('hello')

if __name__=='__main__':
    some_class = SomeClass()

    schedule.every().minute.do(some_class.p_b)

    while True:
        schedule.run_pending()
        time.sleep(1)


问:
How do I return a tuple of tuples in python? i.e. ((((1, 8), (4, 5)), ((2, 7), (3, 6))),) It keeps returning None
I'm working on a recursive algorithm in Python 3 that produces a list containing a tuple of tuples. When I try to return the list, I get none. Can anyone spot what I'm missing?
Here is what I have:</p>

```<code>def plan_nba_playoff(num_teams):
    games =list(range(1, num_teams+1))
    return plan_nba_helper(games)

def plan_nba_helper(teams):
    newGames = []
    c = len(teams) - 1
    for i in range(len(teams)//2):
        game = teams[i], teams[c],
        newGames.append(game)
        c -= 1
        if i == c and len(newGames) == 1:
            print(newGames)
            return newGames
        elif i == c:
            plan_nba_helper(newGames) #((((1, 8), (4, 5)), ((2, 7), (3, 6))),)

print(plan_nba_playoff(8)) #((((1, 8), (4, 5)), ((2, 7), (3, 6))),)
</code>```

答: You forgot to make your function plan_nba_helper return anything. I think you want it to return newGames and also maybe the in the elif statement you may want to return plan_nba_helper(newGames).

Body:
I'm working on a recursive algorithm in Python 3 that produces a list containing a tuple of tuples. When I try to return the list, I get none. Can anyone spot what I'm missing?
Here is what I have:

def plan_nba_playoff(num_teams):
    games =list(range(1, num_teams+1))
    return plan_nba_helper(games)

def plan_nba_helper(teams):
    newGames = []
    c = len(teams) - 1
    for i in range(len(teams)//2):
        game = teams[i], teams[c],
        newGames.append(game)
        c -= 1
        if i == c and len(newGames) == 1:
            print(newGames)
            return newGames
        elif i == c:
            plan_nba_helper(newGames) #((((1, 8), (4, 5)), ((2, 7), (3, 6))),)

print(plan_nba_playoff(8)) #((((1, 8), (4, 5)), ((2, 7), (3, 6))),)


问:
Regex for find multiline form data (php)
I try (without success) to make a regex for find a  submit button even if button code is in one two or more lines.

I use now this patter

/<(button|input)(.*type=['\"](submit|button)['\"].*)?>/i

and works fine if the button code is in one line

<input type="submit" name="mybutton" class="button_class" value="Submit" title="Click Me" />

I want to make it work if my button code look like

<input type="submit" name="mybutton"

class="button_class" value="Submit"

title="Click Me" />

Thanks

答:
Add /s to the end of the regular expression to make . match any character, including newlines.

It's also a good idea to change greedy .* to lazy .*? in order to stop it matching whole chunks of the HTML.

It's still not recommended to use regex for parsing HTML.


问:
How to run long running synchronous operation in nodejs
I am writing payroll management web application in nodejs for my organisation. In many cases application shall involve cpu intensive mathematical calculation for calculating the figures and that too with many users trying to do this simulatenously.

If i plainly write the logic (setting aside the fact that i already did my best from algorithm and data structure point of view to contain the complexity) it will run synchronously blocking the event loop and make request, response slow.

How to resolve this scenario? What are the possible options to do this asynchronously? I also want to mention that this calculation stuff can be let to run in the background and later i can choose to tell user via notification about the status. I have searched for the solution all over this places and i found some solutions but only in theory & i haven't tested them all by implementing. Mentioning below:

Clustering the node server

Use worker threads

Use an alternate server and do some load balancing.

Use a message queue and couple it with worker thread to do backgound tasks.

Can someone suggest me some tried and battle tested advice on this scenario? and also some tutorial links associated with that.

答:
You might wanna try web workers,easy to use and documented.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers</p>


问:
Java Insert button with MySQL add to database and table
I cant see why it doesn't work.
Its Java Insert button. Error is in InputStream line. 2 imports added. Stream import java.io.FileInputStream; import java.io.InputStream;

InputStream img = new FileInputStream(new File(ImgPath)); error unreported exception FileNotFoundException; must be caught or declared

```<code>    private void Btn_InsertActionPerformed(java.awt.event.ActionEvent evt) {

        if (checkInputs() && ImgPath != null) {
            try {
                Connection con = getConnection();
                PreparedStatement ps = con.prepareStatement("INSERT INTO products(name,price,add_date,image"
                        + "value(?,?,?,?) ");
                ps.setString(1, "txt_name.getText()");
                ps.setString(2, "txt_price.getText()");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String addDate = dateFormat.format("txt_AddDate.getDate()");
                ps.setString(3, addDate);

                InputStream img = new FileInputStream(new File(ImgPath));
                ps.setBlob(4, img);
                ps.executeUpdate();
                JOptionPane.showMessageDialog(null, "Data ");

            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }

        }
        else {
        JOptionPane.showMessageDialog(null, "One or More Filed Are Empty");
        }
    }
</code>```

答:
Update the catch block to this :</p>

```<code>catch (SQLException | FileNotFoundException ex) {
   JOptionPane.showMessageDialog(null, ex.getMessage());
}
</code>```

Body:
I cant see why it doesn't work.
Its Java Insert button. Error is in InputStream line. 2 imports added. Stream import java.io.FileInputStream; import java.io.InputStream;

InputStream img = new FileInputStream(new File(ImgPath)); error unreported exception FileNotFoundException; must be caught or declared

    private void Btn_InsertActionPerformed(java.awt.event.ActionEvent evt) {

        if (checkInputs() && ImgPath != null) {
            try {
                Connection con = getConnection();
                PreparedStatement ps = con.prepareStatement("INSERT INTO products(name,price,add_date,image"
                        + "value(?,?,?,?) ");
                ps.setString(1, "txt_name.getText()");
                ps.setString(2, "txt_price.getText()");
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                String addDate = dateFormat.format("txt_AddDate.getDate()");
                ps.setString(3, addDate);

                InputStream img = new FileInputStream(new File(ImgPath));
                ps.setBlob(4, img);
                ps.executeUpdate();
                JOptionPane.showMessageDialog(null, "Data ");

            } catch (SQLException ex) {
                JOptionPane.showMessageDialog(null, ex.getMessage());
            }

        }
        else {
        JOptionPane.showMessageDialog(null, "One or More Filed Are Empty");
        }
    }

Body:
Update the catch block to this :

catch (SQLException | FileNotFoundException ex) {
   JOptionPane.showMessageDialog(null, ex.getMessage());
}


问:
Reshaping Data from an XML converted table
I have got a data-frame converted from XML to csv. Now the problem is I need to make an excel sheet out of this data but the data is a complete mess. I was wondering if you could help to find the R codes to solve the problem.

I explain the problem in detail. Imagine if the dataset is something like that:

```<code>student.data <- data.frame(id = c(1:17),
                       student_id = c(1111,"","","","","","","","","2222","","","","","","",""),
                       exam_id =c("",10,10,20,20,20,30,40,40,"",10,10,10,20,30,40,40),
                       status = c("","AAA","BBB","CCC","DDD","FFF","GGG","AAA","GGG","","BBB","HHH","MMM","FFF","DDD","GGG","GGG"))
</code>```

the result must be:

I know for a fact that it is a bit complicated but thanks for your help in advance.

答:
We can convert the blank (""). elements in 'student_id' to NA (na_if), then use fill to replace the NA elements with the adjacent non-NA element, grouped by 'student_id', 'exam_id', get the unique elements of 'status' that are not a blank ("") and paste it to a single string (toString), filter out any rows where there are blanks and reshape the output to 'wide' format with pivot_wider

```<code>library(dplyr)
library(tidyr)
library(purrr)
student.data %>%
  mutate(student_id = na_if(student_id, "")) %>%
 fill(student_id) %>%
 group_by(student_id, exam_id) %>%
 summarise(status  =  toString(unique(status[status!= '']))) %>%
 filter_at(vars(exam_id, status), any_vars(. != '')) %>%
 pivot_wider(names_from = exam_id, values_from = status)
# A tibble: 2 x 5
# Groups:   student_id [3]
#  student_id `10`          `20`          `30`  `40`
#  <fct>      <chr>         <chr>         <chr> <chr>
#1 1111       AAA, BBB      CCC, DDD, FFF GGG   AAA, GGG
#2 2222       BBB, HHH, MMM FFF           DDD   GGG
</code>```

Body:
I have got a data-frame converted from XML to csv. Now the problem is I need to make an excel sheet out of this data but the data is a complete mess. I was wondering if you could help to find the R codes to solve the problem.

I explain the problem in detail. Imagine if the dataset is something like that:

student.data <- data.frame(id = c(1:17),
                       student_id = c(1111,"","","","","","","","","2222","","","","","","",""),
                       exam_id =c("",10,10,20,20,20,30,40,40,"",10,10,10,20,30,40,40),
                       status = c("","AAA","BBB","CCC","DDD","FFF","GGG","AAA","GGG","","BBB","HHH","MMM","FFF","DDD","GGG","GGG"))

the result must be:

I know for a fact that it is a bit complicated but thanks for your help in advance.

Body:
We can convert the blank (""). elements in 'student_id' to NA (na_if), then use fill to replace the NA elements with the adjacent non-NA element, grouped by 'student_id', 'exam_id', get the unique elements of 'status' that are not a blank ("") and paste it to a single string (toString), filter out any rows where there are blanks and reshape the output to 'wide' format with pivot_wider

library(dplyr)
library(tidyr)
library(purrr)
student.data %>%
  mutate(student_id = na_if(student_id, "")) %>%
 fill(student_id) %>%
 group_by(student_id, exam_id) %>%
 summarise(status  =  toString(unique(status[status!= '']))) %>%
 filter_at(vars(exam_id, status), any_vars(. != '')) %>%
 pivot_wider(names_from = exam_id, values_from = status)
# A tibble: 2 x 5
# Groups:   student_id [3]
#  student_id `10`          `20`          `30`  `40`
#  <fct>      <chr>         <chr>         <chr> <chr>
#1 1111       AAA, BBB      CCC, DDD, FFF GGG   AAA, GGG
#2 2222       BBB, HHH, MMM FFF           DDD   GGG


问:
How to Add a custom Login module to WebLogic application?
I have an webservice that valide the user and return the roles and I write an custom Jaas Login Module for it.
How can I use this module in Weblogic(and webcenter)? </p>

答:
Well, I figured it out, if anyone has the same problem must take into account:

The Principals in the JaaS must extend WLSUser or use WLSUserImp

You must create a mbeantype, and put it in server/lib/mbeantypes

Configure the authentication provider
in the Weblogic console.


问:
React useEffect is not triggering on route change
I expect that console.log('Refresh') runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?

index.js:

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));
</code>```

App.js:

```<code>import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';

const App = () => {

  useEffect( () => console.log('Refresh'));

  return (
        [<Switch>
            <Route                            component = {Nav}/>
        </Switch>,
        <Switch>
            <Route exact path = '/component1' component = {Component1}/>
            <Route exact path = '/component2' component = {Component2}/>
        </Switch>]
  );
}

export default App;
</code>```

Nav.js:

```<code>import React from 'react';
import { Link } from 'react-router-dom';

const  Nav = () => {
  return (
    <div>
        <Link to = '/component1'>Component 1</Link>
        <Link to = '/component2'>Component 2</Link>
    </div>
  );
}

export default Nav;
</code>```

Component1.js:

```<code>import React from 'react';

const  Component1 = () => {

  return (
    <div>
        <p>Hi</p>
    </div>
  );
}

export default Component1;
</code>```

Component2.js:

```<code>import React from 'react';

const  Component2 = () => {
  return (
    <div>
        <p>Bye</p>
    </div>
  );
}

export default Component2;
</code>```

答:
use the key attribute so everytime we render new component (different key)</p>

```<code><Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />
</code>```

Body:
I expect that console.log('Refresh') runs every time the route changes (switching from Component1 to Component2). But it's only triggering on first render. Why?

index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>, document.getElementById('root'));

App.js:

import React, { useEffect } from 'react';
import { Switch, Route } from 'react-router-dom';
import Nav from './Nav';
import Component1 from './Component1';
import Component2 from './Component2';

const App = () => {

  useEffect( () => console.log('Refresh'));

  return (
        [<Switch>
            <Route                            component = {Nav}/>
        </Switch>,
        <Switch>
            <Route exact path = '/component1' component = {Component1}/>
            <Route exact path = '/component2' component = {Component2}/>
        </Switch>]
  );
}

export default App;

Nav.js:

import React from 'react';
import { Link } from 'react-router-dom';

const  Nav = () => {
  return (

        <Link to = '/component1'>Component 1</Link>
        <Link to = '/component2'>Component 2</Link>

  );
}

export default Nav;

Component1.js:

import React from 'react';

const  Component1 = () => {

  return (

Hi

  );
}

export default Component1;

Component2.js:

import React from 'react';

const  Component2 = () => {
  return (

Bye

  );
}

export default Component2;

Body:
use the key attribute so everytime we render new component (different key)

<Route path='/mypath/:username' exact render= {routeProps =><MyCompo {...routeProps} key={document.location.href} />} />


问:
i want to fetch data full in a single Textview from firebase database
I have created a barcode scanner app and it reads the barcode id and needed the output as voice output. in order to read all the things i need to fetch all data together in one single TextView. I did my level best to add the query from database. but it only shows in TextView as com.google.firebase.database.Query@9fc9e4d and my app TTS engine reads it clearly. But i need to set it as all data under a single TextView from database to speak out. please help me???? here only i attached the result handling method.

```<code>@Override
public void handleResult(Result result) { final String scanResult = result.getText();

    databasefetch = FirebaseDatabase.getInstance().getReference("save");
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            setContentView(R.layout.activity_second);
            TextView text = (TextView) findViewById(R.id.textView3);
            String tst = databasefetch.child("save").orderByChild("id").equalTo(scanResult).toString();
            text.setText(tst);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

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

答:
Try something like this</p>

```<code>@Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
            YourModelClass object = postSnapshot.getValue(YourModelClass.class);
            text.setText(object.getId().equalsIgnoreCase(scanResult) ? object.getDescription() : "");
        }
    }
</code>```

Body:
I have created a barcode scanner app and it reads the barcode id and needed the output as voice output. in order to read all the things i need to fetch all data together in one single TextView. I did my level best to add the query from database. but it only shows in TextView as com.google.firebase.database.Query@9fc9e4d and my app TTS engine reads it clearly. But i need to set it as all data under a single TextView from database to speak out. please help me???? here only i attached the result handling method.

@Override
public void handleResult(Result result) { final String scanResult = result.getText();

    databasefetch = FirebaseDatabase.getInstance().getReference("save");
    databasefetch.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            setContentView(R.layout.activity_second);
            TextView text = (TextView) findViewById(R.id.textView3);
            String tst = databasefetch.child("save").orderByChild("id").equalTo(scanResult).toString();
            text.setText(tst);

            //text to speech
            String  toSpeak=text.getText().toString();
            //Toast.makeText(getApplicationContext(),toSpeak,Toast.LENGTH_SHORT).show();
            txt.speak(toSpeak,TextToSpeech.QUEUE_FLUSH,null);

        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

Body:
Try something like this

@Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
            // TODO: handle the post
            YourModelClass object = postSnapshot.getValue(YourModelClass.class);
            text.setText(object.getId().equalsIgnoreCase(scanResult) ? object.getDescription() : "");
        }
    }


问:
What should I know about C# before walking into an interview for a .NET job?
Sure, we all have written tons of C# code. So walking into an interview for a .NET job should be a no-brainer, right? And then you read some stackoverflow posts and it hits you: You don't know squat!

Remember that site with the cram sessions to go through, before taking an exam? I think stackoverflow could be used to make a sorted (voting) list of topics to know about.

Please only put one topic per post.
Please also add some information about the topic. Links, reference material etc.

EDIT: I guess some of you misunderstood the reason for the post - I'm hoping to generate a list of stuff to know about .NET, a sort of cram session that can be reviewed by everyone on the planet to regularly review. This should help us all remember arcane stuff we never really use.

答:
Generics, why generic lists are prefered rather then arraylist or hashtable. Performance issues and strongly typed added by the way.

Bonus: benefits of generic non-collection types. Why would one use these? How?

OwnerDisplayName: Daren Thomas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Daren Thomas

OwnerDisplayName: ScarletGarden

LastEditorDisplayName: siz


问:
How to json_encode complex data structures in PHP?
I've got a data structure which at the top level is a dictionary, and contains lists.  A typical example might be:

```<code>array('foo' => array(1, 2, 3),
      'bar' => array(4, 5, 6));
</code>```

The top-level dictionary might have no attributes, and the inner lists might be empty.

These structures need to be JSON-encoded.  The problem is that PHP doesn't differentiate between an empty dictionary and an empty list, so it doesn't know if array() should be rendered as '{}' or '[]'.  I can force '{}' by doing

```<code>json_encode($object, JSON_FORCE_OBJECT);
</code>```

but that renders

```<code>array('foo' => array());
</code>```

as '{"foo": {}}', when it should be '{"foo": []}'.  If I leave out the JSON_FORCE_OBJECT, then

```<code>array();
</code>```

gets rendered as '[]', when it should be '{}'.  What's the solution, other than chucking PHP and writing this in a sane language?

答:
Iterate through your data and replace all the array()s that should be objects with

```<code>$objectItem = new stdClass();
</code>```

or do

```<code>$objectItem = (object)$objectItem;
</code>```

Alternatively, you can just use objects from the start for those items instead of arrays.

Body:
I've got a data structure which at the top level is a dictionary, and contains lists.  A typical example might be:

array('foo' => array(1, 2, 3),
      'bar' => array(4, 5, 6));

The top-level dictionary might have no attributes, and the inner lists might be empty.

These structures need to be JSON-encoded.  The problem is that PHP doesn't differentiate between an empty dictionary and an empty list, so it doesn't know if array() should be rendered as '{}' or '[]'.  I can force '{}' by doing

json_encode($object, JSON_FORCE_OBJECT);

but that renders

array('foo' => array());

as '{"foo": {}}', when it should be '{"foo": []}'.  If I leave out the JSON_FORCE_OBJECT, then

array();

gets rendered as '[]', when it should be '{}'.  What's the solution, other than chucking PHP and writing this in a sane language?

Body:
Iterate through your data and replace all the array()s that should be objects with

$objectItem = new stdClass();

or do

$objectItem = (object)$objectItem;

Alternatively, you can just use objects from the start for those items instead of arrays.


问:
Entering data into multiple dataframes
I have two loops, the first looks at a specific protein then the second looks at specific cells. In addition I have 16 tables (all named the protein then "_table"). If I specify the cell type I can get the data to enter into the correct row but if I try paste0(temp_TSPAN, "_table") I get the error incorrect number of subscripts on matrix

Any ideas how I can get my loop to specify the correct table?

Here is the second loop which codes for putting data into the tables:

```<code>    temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    paste0(temp_TSPAN, "_table")[temp_cell,] <- temp_means
    temp_means <- c()
  }
</code>```

The entire code

```<code>library(dplyr)
library(RColorBrewer)
RNA_seq <- read.table("RNASeq2Norm_expr_BCRA.txt", stringsAsFactors = F)
xCell <- read.table("..../xCell_ES_RNAseq.txt", stringsAsFactors = F)
PAM50 <- read.table("..../PAM50_subtypes.txt", stringsAsFactors = F)
TSPANS <- read.table("..../TSPANS.txt", stringsAsFactors = F)
len_TSPAN <- length(TSPANS$V1)
col <- brewer.pal(4, "Pastel1")

xCell_cells <- rownames(xCell)
#Create table for quartile means to be entered
for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  assign(as.character((temp_TSPAN)), value = data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                                                      Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                                                      Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                                                      Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                                                      Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                                                      Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                                                      Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                                                      Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                                                      Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                                                      Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67),
                                                      row.names = xCell_cells))
  }

temp_TSPAN <- c()
temp_cell <- c()
#Determine which samples belong to each quartile
for (T in seq(1,len_TSPAN)) {
  temp_TSPAN <- TSPANS$V1[T]
  print(temp_TSPAN)
  Lum_A <- RNA_seq[temp_TSPAN, PAM50$subtype == "LumA"]
  Lum_A_Quartiles <- quantile(Lum_A[temp_TSPAN,])
  Q1_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`25%`]
  Q2_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`25%`]
  Q2_Lum_A <- Q2_Lum_A[,(Q2_Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`50%`]
  Q3_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`50%`]
  Q3_Lum_A <- Q3_Lum_A[,(Q3_Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`75%`]
  Q4_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`75%`]

  Lum_B <- RNA_seq[temp_TSPAN, PAM50$subtype == "LumB"]
  Lum_B_Quartiles <- quantile(Lum_B[temp_TSPAN,])
  Q1_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`25%`]
  Q2_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`25%`]
  Q2_Lum_B <- Q2_Lum_B[,(Q2_Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`50%`]
  Q3_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`50%`]
  Q3_Lum_B <- Q3_Lum_B[,(Q3_Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`75%`]
  Q4_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`75%`]

  Her_2 <- RNA_seq[temp_TSPAN, PAM50$subtype == "Her2"]
  Her_2_Quartiles <- quantile(Her_2[temp_TSPAN,])
  Q1_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`25%`]
  Q2_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`25%`]
  Q2_Her_2 <- Q2_Her_2[,(Q2_Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`50%`]
  Q3_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`50%`]
  Q3_Her_2 <- Q3_Her_2[,(Q3_Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`75%`]
  Q4_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`75%`]

  Basal <- RNA_seq[temp_TSPAN, PAM50$subtype == "Basal"]
  Basal_Quartiles <- quantile(Basal[temp_TSPAN,])
  Q1_Basal <- Basal[,(Basal[temp_TSPAN,]) <= Basal_Quartiles$`25%`]
  Q2_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`25%`]
  Q2_Basal <- Q2_Basal[,(Q2_Basal[temp_TSPAN,]) <= Basal_Quartiles$`50%`]
  Q3_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`50%`]
  Q3_Basal <- Q3_Basal[,(Q3_Basal[temp_TSPAN,]) <= Basal_Quartiles$`75%`]
  Q4_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`75%`]

  Normal <- RNA_seq[temp_TSPAN, PAM50$subtype == "Normal"]
  Normal_Quartiles <- quantile(Normal[temp_TSPAN,])
  Q1_Normal <- Normal[,(Normal[temp_TSPAN,]) <= Normal_Quartiles$`25%`]
  Q2_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`25%`]
  Q2_Normal <- Q2_Normal[,(Q2_Normal[temp_TSPAN,]) <= Normal_Quartiles$`50%`]
  Q3_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`50%`]
  Q3_Normal <- Q3_Normal[,(Q3_Normal[temp_TSPAN,]) <= Normal_Quartiles$`75%`]
  Q4_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`75%`]

  Lum_A_Q1_samples <- colnames(Q1_Lum_A)
  Lum_A_Q2_samples <- colnames(Q2_Lum_A)
  Lum_A_Q3_samples <- colnames(Q3_Lum_A)
  Lum_A_Q4_samples <- colnames(Q4_Lum_A)

  Lum_B_Q1_samples <- colnames(Q1_Lum_B)
  Lum_B_Q2_samples <- colnames(Q2_Lum_B)
  Lum_B_Q3_samples <- colnames(Q3_Lum_B)
  Lum_B_Q4_samples <- colnames(Q4_Lum_B)

  Her_2_Q1_samples <- colnames(Q1_Her_2)
  Her_2_Q2_samples <- colnames(Q2_Her_2)
  Her_2_Q3_samples <- colnames(Q3_Her_2)
  Her_2_Q4_samples <- colnames(Q4_Her_2)

  Basal_Q1_samples <- colnames(Q1_Basal)
  Basal_Q2_samples <- colnames(Q2_Basal)
  Basal_Q3_samples <- colnames(Q3_Basal)
  Basal_Q4_samples <- colnames(Q4_Basal)

  Normal_Q1_samples <- colnames(Q1_Normal)
  Normal_Q2_samples <- colnames(Q2_Normal)
  Normal_Q3_samples <- colnames(Q3_Normal)
  Normal_Q4_samples <- colnames(Q4_Normal)

  #Finding enrichment scores for the samples in each quartile
  xCell_Lum_A_Q1 <- t(xCell[,Lum_A_Q1_samples])
  xCell_Lum_A_Q2 <- t(xCell[,Lum_A_Q2_samples])
  xCell_Lum_A_Q3 <- t(xCell[,Lum_A_Q3_samples])
  xCell_Lum_A_Q4 <- t(xCell[,Lum_A_Q4_samples])

  xCell_Lum_B_Q1 <- t(xCell[,Lum_B_Q1_samples])
  xCell_Lum_B_Q2 <- t(xCell[,Lum_B_Q2_samples])
  xCell_Lum_B_Q3 <- t(xCell[,Lum_B_Q3_samples])
  xCell_Lum_B_Q4 <- t(xCell[,Lum_B_Q4_samples])

  xCell_Her_2_Q1 <- t(xCell[,Her_2_Q1_samples])
  xCell_Her_2_Q2 <- t(xCell[,Her_2_Q2_samples])
  xCell_Her_2_Q3 <- t(xCell[,Her_2_Q3_samples])
  xCell_Her_2_Q4 <- t(xCell[,Her_2_Q4_samples])

  xCell_Basal_Q1 <- t(xCell[,Basal_Q1_samples])
  xCell_Basal_Q2 <- t(xCell[,Basal_Q2_samples])
  xCell_Basal_Q3 <- t(xCell[,Basal_Q3_samples])
  xCell_Basal_Q4 <- t(xCell[,Basal_Q4_samples])

  xCell_Normal_Q1 <- t(xCell[,Normal_Q1_samples])
  xCell_Normal_Q2 <- t(xCell[,Normal_Q2_samples])
  xCell_Normal_Q3 <- t(xCell[,Normal_Q3_samples])
  xCell_Normal_Q4 <- t(xCell[,Normal_Q4_samples])

  len_xCell <- length(xCell_cells)
  temp_means <- c()
  for (i in seq(1, len_xCell)){
    temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    nm1 <- temp_TSPAN, "_table")
    assign(nm1, `[<-`(get(nm1), get(nm1)[temp_cell,], temp_means))
    temp_means <- c()
  }
}
</code>```

Sample data

```<code>> dput(head(TSPANS))
structure(list(V1 = c("TSPAN1", "TSPAN3", "TSPAN4", "TSPAN6",
"TSPAN8", "TSPAN9")), row.names = c(NA, 6L), class = "data.frame")

> dput(head(PAM50))
structure(list(Sample_ID = c("TCGA.3C.AAAU.01A.11R.A41B.07",
"TCGA.3C.AALI.01A.11R.A41B.07", "TCGA.3C.AALJ.01A.31R.A41B.07",
"TCGA.3C.AALK.01A.11R.A41B.07", "TCGA.4H.AAAK.01A.12R.A41B.07",
"TCGA.5L.AAT0.01A.12R.A41B.07"), subtype = c("LumB", "Her2",
"LumB", "Her2", "LumB", "LumA")), row.names = c("1", "2", "3",
"4", "5", "6"), class = "data.frame")

> dput(xCell[1:5, 1:5])
structure(list(TCGA.3C.AAAU.01A.11R.A41B.07 = c(0.0182278777214451,
0, 0, 0.00312390016077943, 0.136068543973221), TCGA.3C.AALI.01A.11R.A41B.07 = c(0.282595778602895,
0, 0.0600603500818251, 0.0589537608635649, 0.205506668589802),
    TCGA.3C.AALJ.01A.31R.A41B.07 = c(0.18283171431184, 0.0941680866198556,
    0.146150110122777, 0.0304405814585031, 8.9658687089931e-20
    ), TCGA.3C.AALK.01A.11R.A41B.07 = c(0.134145304728982, 0.032112973032126,
    0.154386799682783, 0, 4.17812708486922e-20), TCGA.4H.AAAK.01A.12R.A41B.07 = c(0.106111324096064,
    0.0121130054841642, 0.191944288358642, 0, 0.125099426066817
    )), row.names = c("aDC", "Adipocytes", "Astrocytes", "B-cells",
"Basophils"), class = "data.frame")

> dput(RNA_seq[1:5, 1:5])
structure(list(TCGA.3C.AAAU.01A.11R.A41B.07 = c(197.0897, 0,
0, 102.9634, 1.3786), TCGA.3C.AALI.01A.11R.A41B.07 = c(237.3844,
0, 0, 70.8646, 4.3502), TCGA.3C.AALJ.01A.31R.A41B.07 = c(423.2366,
0.9066, 0, 161.2602, 0), TCGA.3C.AALK.01A.11R.A41B.07 = c(191.0178,
0, 0, 62.5072, 1.6549), TCGA.4H.AAAK.01A.12R.A41B.07 = c(268.8809,
0.4255, 3.8298, 154.3702, 3.4043)), row.names = c("A1BG", "A1CF",
"A2BP1", "A2LD1", "A2ML1"), class = "data.frame")

> dput(head(TSPAN1_table))
structure(list(Lum_A_Q1_means = c(NA, NA, NA, NA, NA, NA), Lum_A_Q2_means = c(NA,
NA, NA, NA, NA, NA), Lum_A_Q3_means = c(NA, NA, NA, NA, NA, NA
), Lum_A_Q4_means = c(NA, NA, NA, NA, NA, NA), Lum_B_Q1_means = c(NA,
NA, NA, NA, NA, NA), Lum_B_Q2_means = c(NA, NA, NA, NA, NA, NA
), Lum_B_Q3_means = c(NA, NA, NA, NA, NA, NA), Lum_B_Q4_means = c(NA,
NA, NA, NA, NA, NA), Her_2_Q1_means = c(NA, NA, NA, NA, NA, NA
), Her_2_Q2_means = c(NA, NA, NA, NA, NA, NA), Her_2_Q3_means = c(NA,
NA, NA, NA, NA, NA), Her_2_Q4_means = c(NA, NA, NA, NA, NA, NA
), Basal_Q1_means = c(NA, NA, NA, NA, NA, NA), Basal_Q2_means = c(NA,
NA, NA, NA, NA, NA), Basal_Q3_means = c(NA, NA, NA, NA, NA, NA
), Basal_Q4_means = c(NA, NA, NA, NA, NA, NA), Normal_Q1_means = c(NA,
NA, NA, NA, NA, NA), Normal_Q2_means = c(NA, NA, NA, NA, NA,
NA), Normal_Q3_means = c(NA, NA, NA, NA, NA, NA), Normal_Q4_means = c(NA,
NA, NA, NA, NA, NA)), row.names = c("aDC", "Adipocytes", "Astrocytes",
"B-cells", "Basophils", "CD4+ memory T-cells"), class = "data.frame")
</code>```

答:
We need to get the value with get an assign using assign

```<code>   temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    nm1 <- temp_TSPAN, "_table")
    assign(nm1, `[<-`(get(nm1), get(nm1)[temp_cell,], temp_means))

    temp_means <- c()
  }
</code>```

May be the OP is looking for simplified version with

```<code>lapply(split(RNA_seq, setNames(PAM50$subtype, PAM50$Sample_ID)[colnames(RNA_seq)]),
      function(dat) apply(dat, 1, function(x) {
         qnt <- quantile(x)
         data.frame(val = names(x), grp = names(qnt)[findInterval(x, qnt)])
         apply(xCell[, names(x)], 2, function(y) tapply(y, names(x), FUN = mean))
       }))
</code>```

Title: Entering data into multiple dataframes

Body:
I have two loops, the first looks at a specific protein then the second looks at specific cells. In addition I have 16 tables (all named the protein then "_table"). If I specify the cell type I can get the data to enter into the correct row but if I try paste0(temp_TSPAN, "_table") I get the error incorrect number of subscripts on matrix

Any ideas how I can get my loop to specify the correct table?

Here is the second loop which codes for putting data into the tables:

    temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    paste0(temp_TSPAN, "_table")[temp_cell,] <- temp_means
    temp_means <- c()
  }

The entire code

library(dplyr)
library(RColorBrewer)
RNA_seq <- read.table("RNASeq2Norm_expr_BCRA.txt", stringsAsFactors = F)
xCell <- read.table("..../xCell_ES_RNAseq.txt", stringsAsFactors = F)
PAM50 <- read.table("..../PAM50_subtypes.txt", stringsAsFactors = F)
TSPANS <- read.table("..../TSPANS.txt", stringsAsFactors = F)
len_TSPAN <- length(TSPANS$V1)
col <- brewer.pal(4, "Pastel1")

xCell_cells <- rownames(xCell)
#Create table for quartile means to be entered
for (i in seq(1,len_TSPAN)){
  temp_TSPAN <- TSPANS$V1[i]
  print(temp_TSPAN)
  assign(as.character((temp_TSPAN)), value = data.frame(Lum_A_Q1_means = rep(NA, 67), Lum_A_Q2_means = rep(NA,67),
                                                      Lum_A_Q3_means = rep(NA, 67), Lum_A_Q4_means = rep(NA,67),
                                                      Lum_B_Q1_means = rep(NA, 67), Lum_B_Q2_means = rep(NA,67),
                                                      Lum_B_Q3_means = rep(NA, 67), Lum_B_Q4_means = rep(NA,67),
                                                      Her_2_Q1_means = rep(NA, 67), Her_2_Q2_means = rep(NA,67),
                                                      Her_2_Q3_means = rep(NA, 67), Her_2_Q4_means = rep(NA,67),
                                                      Basal_Q1_means = rep(NA, 67), Basal_Q2_means = rep(NA,67),
                                                      Basal_Q3_means = rep(NA, 67), Basal_Q4_means = rep(NA,67),
                                                      Normal_Q1_means = rep(NA, 67), Normal_Q2_means = rep(NA,67),
                                                      Normal_Q3_means = rep(NA, 67), Normal_Q4_means = rep(NA,67),
                                                      row.names = xCell_cells))
  }

temp_TSPAN <- c()
temp_cell <- c()
#Determine which samples belong to each quartile
for (T in seq(1,len_TSPAN)) {
  temp_TSPAN <- TSPANS$V1[T]
  print(temp_TSPAN)
  Lum_A <- RNA_seq[temp_TSPAN, PAM50$subtype == "LumA"]
  Lum_A_Quartiles <- quantile(Lum_A[temp_TSPAN,])
  Q1_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`25%`]
  Q2_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`25%`]
  Q2_Lum_A <- Q2_Lum_A[,(Q2_Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`50%`]
  Q3_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`50%`]
  Q3_Lum_A <- Q3_Lum_A[,(Q3_Lum_A[temp_TSPAN,]) <= Lum_A_Quartiles$`75%`]
  Q4_Lum_A <- Lum_A[,(Lum_A[temp_TSPAN,]) > Lum_A_Quartiles$`75%`]

  Lum_B <- RNA_seq[temp_TSPAN, PAM50$subtype == "LumB"]
  Lum_B_Quartiles <- quantile(Lum_B[temp_TSPAN,])
  Q1_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`25%`]
  Q2_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`25%`]
  Q2_Lum_B <- Q2_Lum_B[,(Q2_Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`50%`]
  Q3_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`50%`]
  Q3_Lum_B <- Q3_Lum_B[,(Q3_Lum_B[temp_TSPAN,]) <= Lum_B_Quartiles$`75%`]
  Q4_Lum_B <- Lum_B[,(Lum_B[temp_TSPAN,]) > Lum_B_Quartiles$`75%`]

  Her_2 <- RNA_seq[temp_TSPAN, PAM50$subtype == "Her2"]
  Her_2_Quartiles <- quantile(Her_2[temp_TSPAN,])
  Q1_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`25%`]
  Q2_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`25%`]
  Q2_Her_2 <- Q2_Her_2[,(Q2_Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`50%`]
  Q3_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`50%`]
  Q3_Her_2 <- Q3_Her_2[,(Q3_Her_2[temp_TSPAN,]) <= Her_2_Quartiles$`75%`]
  Q4_Her_2 <- Her_2[,(Her_2[temp_TSPAN,]) > Her_2_Quartiles$`75%`]

  Basal <- RNA_seq[temp_TSPAN, PAM50$subtype == "Basal"]
  Basal_Quartiles <- quantile(Basal[temp_TSPAN,])
  Q1_Basal <- Basal[,(Basal[temp_TSPAN,]) <= Basal_Quartiles$`25%`]
  Q2_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`25%`]
  Q2_Basal <- Q2_Basal[,(Q2_Basal[temp_TSPAN,]) <= Basal_Quartiles$`50%`]
  Q3_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`50%`]
  Q3_Basal <- Q3_Basal[,(Q3_Basal[temp_TSPAN,]) <= Basal_Quartiles$`75%`]
  Q4_Basal <- Basal[,(Basal[temp_TSPAN,]) > Basal_Quartiles$`75%`]

  Normal <- RNA_seq[temp_TSPAN, PAM50$subtype == "Normal"]
  Normal_Quartiles <- quantile(Normal[temp_TSPAN,])
  Q1_Normal <- Normal[,(Normal[temp_TSPAN,]) <= Normal_Quartiles$`25%`]
  Q2_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`25%`]
  Q2_Normal <- Q2_Normal[,(Q2_Normal[temp_TSPAN,]) <= Normal_Quartiles$`50%`]
  Q3_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`50%`]
  Q3_Normal <- Q3_Normal[,(Q3_Normal[temp_TSPAN,]) <= Normal_Quartiles$`75%`]
  Q4_Normal <- Normal[,(Normal[temp_TSPAN,]) > Normal_Quartiles$`75%`]

  Lum_A_Q1_samples <- colnames(Q1_Lum_A)
  Lum_A_Q2_samples <- colnames(Q2_Lum_A)
  Lum_A_Q3_samples <- colnames(Q3_Lum_A)
  Lum_A_Q4_samples <- colnames(Q4_Lum_A)

  Lum_B_Q1_samples <- colnames(Q1_Lum_B)
  Lum_B_Q2_samples <- colnames(Q2_Lum_B)
  Lum_B_Q3_samples <- colnames(Q3_Lum_B)
  Lum_B_Q4_samples <- colnames(Q4_Lum_B)

  Her_2_Q1_samples <- colnames(Q1_Her_2)
  Her_2_Q2_samples <- colnames(Q2_Her_2)
  Her_2_Q3_samples <- colnames(Q3_Her_2)
  Her_2_Q4_samples <- colnames(Q4_Her_2)

  Basal_Q1_samples <- colnames(Q1_Basal)
  Basal_Q2_samples <- colnames(Q2_Basal)
  Basal_Q3_samples <- colnames(Q3_Basal)
  Basal_Q4_samples <- colnames(Q4_Basal)

  Normal_Q1_samples <- colnames(Q1_Normal)
  Normal_Q2_samples <- colnames(Q2_Normal)
  Normal_Q3_samples <- colnames(Q3_Normal)
  Normal_Q4_samples <- colnames(Q4_Normal)

  #Finding enrichment scores for the samples in each quartile
  xCell_Lum_A_Q1 <- t(xCell[,Lum_A_Q1_samples])
  xCell_Lum_A_Q2 <- t(xCell[,Lum_A_Q2_samples])
  xCell_Lum_A_Q3 <- t(xCell[,Lum_A_Q3_samples])
  xCell_Lum_A_Q4 <- t(xCell[,Lum_A_Q4_samples])

  xCell_Lum_B_Q1 <- t(xCell[,Lum_B_Q1_samples])
  xCell_Lum_B_Q2 <- t(xCell[,Lum_B_Q2_samples])
  xCell_Lum_B_Q3 <- t(xCell[,Lum_B_Q3_samples])
  xCell_Lum_B_Q4 <- t(xCell[,Lum_B_Q4_samples])

  xCell_Her_2_Q1 <- t(xCell[,Her_2_Q1_samples])
  xCell_Her_2_Q2 <- t(xCell[,Her_2_Q2_samples])
  xCell_Her_2_Q3 <- t(xCell[,Her_2_Q3_samples])
  xCell_Her_2_Q4 <- t(xCell[,Her_2_Q4_samples])

  xCell_Basal_Q1 <- t(xCell[,Basal_Q1_samples])
  xCell_Basal_Q2 <- t(xCell[,Basal_Q2_samples])
  xCell_Basal_Q3 <- t(xCell[,Basal_Q3_samples])
  xCell_Basal_Q4 <- t(xCell[,Basal_Q4_samples])

  xCell_Normal_Q1 <- t(xCell[,Normal_Q1_samples])
  xCell_Normal_Q2 <- t(xCell[,Normal_Q2_samples])
  xCell_Normal_Q3 <- t(xCell[,Normal_Q3_samples])
  xCell_Normal_Q4 <- t(xCell[,Normal_Q4_samples])

  len_xCell <- length(xCell_cells)
  temp_means <- c()
  for (i in seq(1, len_xCell)){
    temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    nm1 <- temp_TSPAN, "_table")
    assign(nm1, `[<-`(get(nm1), get(nm1)[temp_cell,], temp_means))
    temp_means <- c()
  }
}

Sample data

> dput(head(TSPANS))
structure(list(V1 = c("TSPAN1", "TSPAN3", "TSPAN4", "TSPAN6",
"TSPAN8", "TSPAN9")), row.names = c(NA, 6L), class = "data.frame")

> dput(head(PAM50))
structure(list(Sample_ID = c("TCGA.3C.AAAU.01A.11R.A41B.07",
"TCGA.3C.AALI.01A.11R.A41B.07", "TCGA.3C.AALJ.01A.31R.A41B.07",
"TCGA.3C.AALK.01A.11R.A41B.07", "TCGA.4H.AAAK.01A.12R.A41B.07",
"TCGA.5L.AAT0.01A.12R.A41B.07"), subtype = c("LumB", "Her2",
"LumB", "Her2", "LumB", "LumA")), row.names = c("1", "2", "3",
"4", "5", "6"), class = "data.frame")

> dput(xCell[1:5, 1:5])
structure(list(TCGA.3C.AAAU.01A.11R.A41B.07 = c(0.0182278777214451,
0, 0, 0.00312390016077943, 0.136068543973221), TCGA.3C.AALI.01A.11R.A41B.07 = c(0.282595778602895,
0, 0.0600603500818251, 0.0589537608635649, 0.205506668589802),
    TCGA.3C.AALJ.01A.31R.A41B.07 = c(0.18283171431184, 0.0941680866198556,
    0.146150110122777, 0.0304405814585031, 8.9658687089931e-20
    ), TCGA.3C.AALK.01A.11R.A41B.07 = c(0.134145304728982, 0.032112973032126,
    0.154386799682783, 0, 4.17812708486922e-20), TCGA.4H.AAAK.01A.12R.A41B.07 = c(0.106111324096064,
    0.0121130054841642, 0.191944288358642, 0, 0.125099426066817
    )), row.names = c("aDC", "Adipocytes", "Astrocytes", "B-cells",
"Basophils"), class = "data.frame")

> dput(RNA_seq[1:5, 1:5])
structure(list(TCGA.3C.AAAU.01A.11R.A41B.07 = c(197.0897, 0,
0, 102.9634, 1.3786), TCGA.3C.AALI.01A.11R.A41B.07 = c(237.3844,
0, 0, 70.8646, 4.3502), TCGA.3C.AALJ.01A.31R.A41B.07 = c(423.2366,
0.9066, 0, 161.2602, 0), TCGA.3C.AALK.01A.11R.A41B.07 = c(191.0178,
0, 0, 62.5072, 1.6549), TCGA.4H.AAAK.01A.12R.A41B.07 = c(268.8809,
0.4255, 3.8298, 154.3702, 3.4043)), row.names = c("A1BG", "A1CF",
"A2BP1", "A2LD1", "A2ML1"), class = "data.frame")

> dput(head(TSPAN1_table))
structure(list(Lum_A_Q1_means = c(NA, NA, NA, NA, NA, NA), Lum_A_Q2_means = c(NA,
NA, NA, NA, NA, NA), Lum_A_Q3_means = c(NA, NA, NA, NA, NA, NA
), Lum_A_Q4_means = c(NA, NA, NA, NA, NA, NA), Lum_B_Q1_means = c(NA,
NA, NA, NA, NA, NA), Lum_B_Q2_means = c(NA, NA, NA, NA, NA, NA
), Lum_B_Q3_means = c(NA, NA, NA, NA, NA, NA), Lum_B_Q4_means = c(NA,
NA, NA, NA, NA, NA), Her_2_Q1_means = c(NA, NA, NA, NA, NA, NA
), Her_2_Q2_means = c(NA, NA, NA, NA, NA, NA), Her_2_Q3_means = c(NA,
NA, NA, NA, NA, NA), Her_2_Q4_means = c(NA, NA, NA, NA, NA, NA
), Basal_Q1_means = c(NA, NA, NA, NA, NA, NA), Basal_Q2_means = c(NA,
NA, NA, NA, NA, NA), Basal_Q3_means = c(NA, NA, NA, NA, NA, NA
), Basal_Q4_means = c(NA, NA, NA, NA, NA, NA), Normal_Q1_means = c(NA,
NA, NA, NA, NA, NA), Normal_Q2_means = c(NA, NA, NA, NA, NA,
NA), Normal_Q3_means = c(NA, NA, NA, NA, NA, NA), Normal_Q4_means = c(NA,
NA, NA, NA, NA, NA)), row.names = c("aDC", "Adipocytes", "Astrocytes",
"B-cells", "Basophils", "CD4+ memory T-cells"), class = "data.frame")

Body:
We need to get the value with get an assign using assign

   temp_cell <- xCell_cells[i]
    print(temp_TSPAN)
    print(temp_cell)
    temp_means <- c(mean(xCell_Lum_A_Q1[,temp_cell]),mean(xCell_Lum_A_Q2[,temp_cell]),mean(xCell_Lum_A_Q3[,temp_cell]),mean(xCell_Lum_A_Q4[,temp_cell]),
                    mean(xCell_Lum_B_Q1[,temp_cell]),mean(xCell_Lum_B_Q2[,temp_cell]),mean(xCell_Lum_B_Q3[,temp_cell]),mean(xCell_Lum_B_Q4[,temp_cell]),
                    mean(xCell_Her_2_Q1[,temp_cell]),mean(xCell_Her_2_Q2[,temp_cell]),mean(xCell_Her_2_Q3[,temp_cell]),mean(xCell_Her_2_Q4[,temp_cell]),
                    mean(xCell_Basal_Q1[,temp_cell]),mean(xCell_Basal_Q2[,temp_cell]),mean(xCell_Basal_Q3[,temp_cell]),mean(xCell_Basal_Q4[,temp_cell]),
                    mean(xCell_Normal_Q1[,temp_cell]),mean(xCell_Normal_Q2[,temp_cell]),mean(xCell_Normal_Q3[,temp_cell]),mean(xCell_Normal_Q4[,temp_cell]))

    print(temp_means)
    nm1 <- temp_TSPAN, "_table")
    assign(nm1, `[<-`(get(nm1), get(nm1)[temp_cell,], temp_means))

    temp_means <- c()
  }

May be the OP is looking for simplified version with

lapply(split(RNA_seq, setNames(PAM50$subtype, PAM50$Sample_ID)[colnames(RNA_seq)]),
      function(dat) apply(dat, 1, function(x) {
         qnt <- quantile(x)
         data.frame(val = names(x), grp = names(qnt)[findInterval(x, qnt)])
         apply(xCell[, names(x)], 2, function(y) tapply(y, names(x), FUN = mean))
       }))


问:
PHP class that sorts an ordered integer array with the help of sort() function
I have written down the following for the above question

```<code><?php

class sortClass{

  public function __construct(array $arrayPassed){
    return sort($arrayPassed);
    }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted);

?>
</code>```

And the output is 'sortClass Object()' , I'd like some help to understand why it would not print out the sorted array , When we instantiate a class - the constructor will automatically execute and return what ever it returns right? so why isn;t printing $sorted object printing whats returned in the constructor?

答:
You don't need a wrapper class just to sort, you can  just run sort function directly, the issue with your code is, returning in __constructor.

I suggest you run it directly like this:

```<code><?php
  $newarray = array(11,-2,4,35,0,8,-9);
  sort($newarray);
  print_r($newarray);
?>
</code>```

or this one if you still need a OOP version:

```<code><?php

class sortClass{
  private $arrayPassed = [];
  public function __construct(array $arrayPassed){
    $this->arrayPassed = $arrayPassed;
  }

  public function sort() {
    sort($this->arrayPassed);
    return $this->arrayPassed;
  }
}

$newarray = array(11,-2,4,35,0,8,-9);

$sortClass =  new sortClass($newarray);

print_r($sortClass->sort());
</code>```

Body:
I have written down the following for the above question

<?php

class sortClass{

  public function __construct(array $arrayPassed){
    return sort($arrayPassed);
    }

}
$newarray=array(11,-2,4,35,0,8,-9);
$sorted =  new sortClass($newarray);
print_r($sorted);

?>

And the output is 'sortClass Object()' , I'd like some help to understand why it would not print out the sorted array , When we instantiate a class - the constructor will automatically execute and return what ever it returns right? so why isn;t printing $sorted object printing whats returned in the constructor?

Body:
You don't need a wrapper class just to sort, you can  just run sort function directly, the issue with your code is, returning in __constructor.

I suggest you run it directly like this:

<?php
  $newarray = array(11,-2,4,35,0,8,-9);
  sort($newarray);
  print_r($newarray);
?>

or this one if you still need a OOP version:

<?php

class sortClass{
  private $arrayPassed = [];
  public function __construct(array $arrayPassed){
    $this->arrayPassed = $arrayPassed;
  }

  public function sort() {
    sort($this->arrayPassed);
    return $this->arrayPassed;
  }
}

$newarray = array(11,-2,4,35,0,8,-9);

$sortClass =  new sortClass($newarray);

print_r($sortClass->sort());


问:
Corrections to CMakeList.txt file for Google testing?
I have been looking at examples of CMake to help me build my project with its test folder. The main issue is that I have to include all the test/.cpp* files in my test folder into tests/main.cpp for the tests to run. I think I should include my tests with the add_test call in my test/CMakeLists.txt. Below is my current CMakeLists file:

enable_testing()

find_package(GTest REQUIRED)

add_executable(test main.cpp)

target_include_directories(test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include)

target_link_libraries(test MainProjectLib ${GTEST_LIBRARIES})

And my main.cpp is the following.

```<code>#include "file_in_test1.cpp"
#include "file_in_test2.cpp"
#include <gtest/gtest.h>

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
</code>```

I read some examples that use the standard CTest library for unit testing, but I am using Google Test. I would like to be able to run cmake, make, and then ./test to run all test methods found in file_in_test1.cpp and file_in_test2.cpp without having to directly import those files into test/main.cpp. What additions to CMakeLists.txt do I have to make?

答:
The one line you could add at the end would be:

```<code>gtest_discover_tests(test)
</code>```

This is a replacement for gtest_add_tests since cmake version 3.10, and then after you build everything, you can just run ctest and it will give you a nice summary of the tests it just ran. You can read more about this option here.

Also, just as a note, it would probably be better to make individual test files for each of the tests you have, rather than including the .cpp files in your main test file.

What I generally do is define an option to allow for testing and a function that creates the test I need (see below):

```<code>option(build_all_tests "Build all unit tests in the test directory." OFF)

if (build_all_tests)
    include(CTest)
    include(GoogleTest)

    enable_testing()

    ## Function to create a new test based off the pre-defined naming template ##
    function(new_test testname interiorDirectory)
        add_executable(${testname} ${interiorDirectory}/${testname}.cpp)

        target_link_libraries(${testname} ${GTEST_LIBRARIES})

        gtest_discover_tests(${testname}
                        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${interiorDirectory})
    endfunction(new_test)

    ## Locate GTest ##
    find_package(GTest REQUIRED)
    include_directories(${GTEST_INCLUDE_DIRS})

    ## Create all tests ##
    new_test(test1 test/test1)
    new_test(test2 test/test2)
    ...
endif()
</code>```

Body:
I have been looking at examples of CMake to help me build my project with its test folder. The main issue is that I have to include all the test/.cpp* files in my test folder into tests/main.cpp for the tests to run. I think I should include my tests with the add_test call in my test/CMakeLists.txt. Below is my current CMakeLists file:

enable_testing()

find_package(GTest REQUIRED)

add_executable(test main.cpp)

target_include_directories(test PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/../include)

target_link_libraries(test MainProjectLib ${GTEST_LIBRARIES})

And my main.cpp is the following.

#include "file_in_test1.cpp"
#include "file_in_test2.cpp"
#include <gtest/gtest.h>

int main(int argc, char **argv) {
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

I read some examples that use the standard CTest library for unit testing, but I am using Google Test. I would like to be able to run cmake, make, and then ./test to run all test methods found in file_in_test1.cpp and file_in_test2.cpp without having to directly import those files into test/main.cpp. What additions to CMakeLists.txt do I have to make?

Body:
The one line you could add at the end would be:

gtest_discover_tests(test)

This is a replacement for gtest_add_tests since cmake version 3.10, and then after you build everything, you can just run ctest and it will give you a nice summary of the tests it just ran. You can read more about this option here.

Also, just as a note, it would probably be better to make individual test files for each of the tests you have, rather than including the .cpp files in your main test file.

What I generally do is define an option to allow for testing and a function that creates the test I need (see below):

option(build_all_tests "Build all unit tests in the test directory." OFF)

if (build_all_tests)
    include(CTest)
    include(GoogleTest)

    enable_testing()

    ## Function to create a new test based off the pre-defined naming template ##
    function(new_test testname interiorDirectory)
        add_executable(${testname} ${interiorDirectory}/${testname}.cpp)

        target_link_libraries(${testname} ${GTEST_LIBRARIES})

        gtest_discover_tests(${testname}
                        WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/${interiorDirectory})
    endfunction(new_test)

    ## Locate GTest ##
    find_package(GTest REQUIRED)
    include_directories(${GTEST_INCLUDE_DIRS})

    ## Create all tests ##
    new_test(test1 test/test1)
    new_test(test2 test/test2)
    ...
endif()


问:
Ruby on rails: how to update an div with partial without making an ajax call to server
I want to update an div with contents of a partial when a user clicks on a radio button. Now the contents of that partial are static html (a form may be). So because I do not have any data to fetch from the server I am reluctant to make an ajax call to server just to fetch that partial and update the div. Here is what I have tried.

```<code> function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).appendChild("<%=  render :partial => 'layouts/agency_selection' %>");
      }

<input type="radio" name="view" value="agencies" onClick ="loadControlPanel(this.value)" /> Agencies
</code>```

But this doesn't work because the render  replaces the entire partial there along with the new lines which throws javascript errors in the function loadControlPanel(type).

Is there any way to overcome this? or some other simpler solution?

Thanks
Shaunak

答:
OKay here is the work around i have found to get around this. I am calling 'gsub' on the render to replace the newlines with nothing. I am still open to more elegant solutions though.</p>

```<code>function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).innerHTML = '<%=  (render :partial => "layouts/agency_selection").gsub("\n","") %>';
      }
</code>```

Body:
I want to update an div with contents of a partial when a user clicks on a radio button. Now the contents of that partial are static html (a form may be). So because I do not have any data to fetch from the server I am reluctant to make an ajax call to server just to fetch that partial and update the div. Here is what I have tried.

 function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).appendChild("<%=  render :partial => 'layouts/agency_selection' %>");
      }

<input type="radio" name="view" value="agencies" onClick ="loadControlPanel(this.value)" /> Agencies

But this doesn't work because the render  replaces the entire partial there along with the new lines which throws javascript errors in the function loadControlPanel(type).

Is there any way to overcome this? or some other simpler solution?

Thanks
Shaunak

Body:
OKay here is the work around i have found to get around this. I am calling 'gsub' on the render to replace the newlines with nothing. I am still open to more elegant solutions though.

function loadControlPanel(type)
      {
        alert(type);
        $(controlPanelDiv).innerHTML = '<%=  (render :partial => "layouts/agency_selection").gsub("\n","") %>';
      }


问:
How to write Perl modified content into a file in Python scripts?
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

```<code>new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file
</code>```

Above codes work in Linux. I improved them in Python scripts. If I use below command

```<code>import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)
</code>```

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

```<code>cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file
</code>```

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

```<code>FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507
</code>```

I hope to get output like below:

```<code>FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430
</code>```

答:
This can be easily done in perl. Recall \s includes the \n\t\r. You need \h which is any horizontal space and does not include line feed

just do

```<code> perl -pe 's/\h+/,/g' $new_dat_file > $new_csv_file
</code>```

Body:
My research data is not a normal file. The column number of each row may be different. I want to convert the "dat" file into "*.csv" file using Perl because it can run efficiently (I have poor experience in Python). Below is the script I ran. It works fine in Linux, but it does not output the context in Python scripts.

new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
perl -p -e 's/\\t\s+|\s+/,/g' $new_dat_file |perl -p -e 's/,FRAM/\\nFRAM/g' >  $new_csv_file

Above codes work in Linux. I improved them in Python scripts. If I use below command

import os
new_dat_file="14689_bondlength.prmfrm.dat"
new_csv_file="14689_bondlength.prmfrm.csv"
cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g'
os.system(cmd)

I can see the output correctly. However, if I modify cmd values like below to save the output into a csv file, but I got an empty file.

cmd = "perl -p -e 's/\\t\s+|\s+/,/g' " + new_dat_file + " |perl -p -e 's/,FRAM/\\nFRAM/g' > " + new_csv_file

How can I fix this issue? If I cannot do so, any other alternative way available? Any further suggestion would be highly appreciated.

BTW: partial data listed below

FRAM_#            0            0(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.008
FRAM_#          100           25(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.955
FRAM_#          200           50(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.993
FRAM_#          300           75(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.973
FRAM_#          400          100(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.988
FRAM_#          500          125(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.033
FRAM_#          600          150(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.032
FRAM_#          700          175(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.986
FRAM_#          800          200(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.061
FRAM_#          900          225(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  1.078
FRAM_#         1000          250(fs)  CN= 1 PRMRYTGT     14689      H      15449      O  0.922
FRAM_#         1100          275(fs)  CN= 2 PRMRYTGT     14689      H      17402      O  1.257     15449      O  1.430
FRAM_#       303200        75800(fs)  CN= 0 PRMRYTGT_BD     14689      H
FRAM_#       921200       230300(fs)  CN= 1 PRMRYTGT_BD     14689      H        8375      O  1.062
FRAM_#      1078700       269675(fs)  CN= 1 PRMRYTGT_BD     14689      H       12971      O  1.507
FRAM_#     18203400      4550850(fs)  CN= 1 PRMRYTGT_BD     14689      H       16172      O  1.507

I hope to get output like below:

FRAM_#,0,0(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.008
FRAM_#,100,25(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.955
FRAM_#,200,50(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.993
FRAM_#,300,75(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.973
FRAM_#,400,100(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.988
FRAM_#,500,125(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.033
FRAM_#,600,150(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.032
FRAM_#,700,175(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.986
FRAM_#,800,200(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.061
FRAM_#,900,225(fs),CN=,1,PRMRYTGT,14689,H,15449,O,1.078
FRAM_#,1000,250(fs),CN=,1,PRMRYTGT,14689,H,15449,O,0.922
FRAM_#,1100,275(fs),CN=,2,PRMRYTGT,14689,H,17402,O,1.257,15449,O,1.430

Body:
This can be easily done in perl. Recall \s includes the \n\t\r. You need \h which is any horizontal space and does not include line feed

just do

 perl -pe 's/\h+/,/g' $new_dat_file > $new_csv_file


问:
Count and summation of positive and negative number sequences
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
</code>```

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}
```
<h3>python</h3>
<pre class="lang-py prettyprint-override"><code>sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
</code>```

result

```<code>        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046
</code>```

答:
As for Python, someone will come up with a solution using the pandas library. In the meantime, here is a simple proposal:

class Combiner:
    def __init__(self):
        self.index = self.seq_index = self.summation = 0

    def combine(self, value):
        self.index += 1
        if value * self.summation <= 0:
            self.seq_index = 1
            self.summation = value
        else:
            self.seq_index += 1
            self.summation += value
        return self.index, value, self.seq_index, self.summation

c = Combiner()
lst = [c.combine(v) for v in x]

for t in lst:
    print(f"{t[0]:3} {t[1]:7.3f} {t[2]:3} {t[3]:7.3f}")
```

<p>Output:</p>

<pre class="lang-none prettyprint-override"><code>  1  -0.010   1  -0.010
  2   0.003   1   0.003
  3  -0.002   1  -0.002
  4   0.018   1   0.018
  5   0.002   2   0.020
  6   0.006   3   0.026
  7  -0.012   1  -0.012
  8   0.014   1   0.014
  9  -0.017   1  -0.017
 10  -0.007   2  -0.024
 11   0.002   1   0.002
 12   0.002   2   0.004
 13  -0.004   1  -0.004
 14   0.015   1   0.015
 15   0.002   2   0.017
 16  -0.001   1  -0.001
 17  -0.008   2  -0.009
 18   0.010   1   0.010
 19  -0.018   1  -0.018
 20   0.046   1   0.046
</code>```

If you need separate lists, you can do

idxs, vals, seqs, sums = (list(tpl) for tpl in zip(*lst))
```

<p>or, if iterators are OK, simply</p>

<pre class="lang-python prettyprint-override"><code>idxs, vals, seqs, sums = zip(*lst)
</code>```

(explanation here)

Body:
I want to write a code to count and sum any positive and negative series of numbers.

Numbers are either positive or negative(no zero).

I have written codes with for loops. Is there any creative alternative?

Data

R

set.seed(100)
x <- round(rnorm(20, sd = 0.02), 3)

python

x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007,

     0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]

loops

R

sign_indicator <- ifelse(x > 0, 1,-1)
number_of_sequence <- rep(NA, 20)
n <- 1
for (i in 2:20) {
  if (sign_indicator[i] == sign_indicator[i - 1]) {
    n <- n + 1
  } else{
    n <- 1
  }
  number_of_sequence[i] <- n

}
number_of_sequence[1] <- 1

#############################

summation <- rep(NA, 20)

for (i in 1:20) {
  summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])
}

python

sign_indicator = [1 if i > 0 else -1 for i in X]

number_of_sequence = [1]
N = 1
for i in range(1, len(sign_indicator)):
    if sign_indicator[i] == sign_indicator[i - 1]:
        N += 1
    else:
        N = 1
    number_of_sequence.append(N)

#############################
summation = []

for i in range(len(X)):
    if number_of_sequence[i] == 1:
          summation.append(X[i])

    else:
        summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))

result

        x n_of_sequence    sum
1  -0.010             1 -0.010
2   0.003             1  0.003
3  -0.002             1 -0.002
4   0.018             1  0.018
5   0.002             2  0.020
6   0.006             3  0.026
7  -0.012             1 -0.012
8   0.014             1  0.014
9  -0.017             1 -0.017
10 -0.007             2 -0.024
11  0.002             1  0.002
12  0.002             2  0.004
13 -0.004             1 -0.004
14  0.015             1  0.015
15  0.002             2  0.017
16 -0.001             1 -0.001
17 -0.008             2 -0.009
18  0.010             1  0.010
19 -0.018             1 -0.018
20  0.046             1  0.046

Body:
As for Python, someone will come up with a solution using the pandas library. In the meantime, here is a simple proposal:

class Combiner:
    def __init__(self):
        self.index = self.seq_index = self.summation = 0

    def combine(self, value):
        self.index += 1
        if value * self.summation <= 0:
            self.seq_index = 1
            self.summation = value
        else:
            self.seq_index += 1
            self.summation += value
        return self.index, value, self.seq_index, self.summation

c = Combiner()
lst = [c.combine(v) for v in x]

for t in lst:
    print(f"{t[0]:3} {t[1]:7.3f} {t[2]:3} {t[3]:7.3f}")

Output:

  1  -0.010   1  -0.010
  2   0.003   1   0.003
  3  -0.002   1  -0.002
  4   0.018   1   0.018
  5   0.002   2   0.020
  6   0.006   3   0.026
  7  -0.012   1  -0.012
  8   0.014   1   0.014
  9  -0.017   1  -0.017
 10  -0.007   2  -0.024
 11   0.002   1   0.002
 12   0.002   2   0.004
 13  -0.004   1  -0.004
 14   0.015   1   0.015
 15   0.002   2   0.017
 16  -0.001   1  -0.001
 17  -0.008   2  -0.009
 18   0.010   1   0.010
 19  -0.018   1  -0.018
 20   0.046   1   0.046

If you need separate lists, you can do

idxs, vals, seqs, sums = (list(tpl) for tpl in zip(*lst))

or, if iterators are OK, simply

idxs, vals, seqs, sums = zip(*lst)

(explanation here)


问:
Rewriting subdirectory to query string parameter
I have two requirements;

That, for example, /product/12345 is internally redirected to /product/product.php?product=12345.

That if the user tries to access /product/product.php in the URL bar, it is redirected to /product/ for tidiness.

Separate, they both work correctly, but together it results in an infinite loop - I know that I'm redirecting from /product/ to /product.php and back again, but the difference is internal vs external and I'm not sure how to distinguish between them.

```<code>RewriteEngine On

RewriteRule ^product/product.php /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI} !^/product/product.php [NC]
RewriteRule ^product/(.*) /product/product.php?product=$1 [NC]
</code>```

答:
access /product/product.php in the URL bar, it is redirected to /product/ for tidiness

You might as well also redirect /product/product.php?product=12345 to the corresponding canonical URL (ie. /product/12345) - which you can do all in the same rule. If the product ID is numeric only then you should restrict your regex accordingly - this will also avoid the need for an additional condition.

For example:

```<code># Canonical redirect
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^(?:product=(\d*))?$ [NC]
RewriteRule ^product/product\.php$ /product/%1 [NC,R=307,L]

# Rewrite requests from "pretty" URL to underlying filesystem path
RewriteRule ^product/(\d*) /product/product.php?product=$1 [L]
</code>```

The condition that checks against the REDIRECT_STATUS environment variable is necessary to prevent a redirect loop in this instance since the query string is entirely optional.

By restricting the match to digits-only, we avoid the need for an additional condition on the internal rewrite, product.php won't match. If the product id can contain letters then restrict the pattern to avoid dots (.), eg. ([^./]*).

Only include a NC flag on the internal rewrite if this is strictly necessary, otherwise this potentially creates a duplicate content issue.

Body:
I have two requirements;

That, for example, /product/12345 is internally redirected to /product/product.php?product=12345.

That if the user tries to access /product/product.php in the URL bar, it is redirected to /product/ for tidiness.

Separate, they both work correctly, but together it results in an infinite loop - I know that I'm redirecting from /product/ to /product.php and back again, but the difference is internal vs external and I'm not sure how to distinguish between them.

RewriteEngine On

RewriteRule ^product/product.php /product/ [NC,R=307,END]

RewriteCond %{REQUEST_URI} !^/product/product.php [NC]
RewriteRule ^product/(.*) /product/product.php?product=$1 [NC]

Body:
access /product/product.php in the URL bar, it is redirected to /product/ for tidiness

You might as well also redirect /product/product.php?product=12345 to the corresponding canonical URL (ie. /product/12345) - which you can do all in the same rule. If the product ID is numeric only then you should restrict your regex accordingly - this will also avoid the need for an additional condition.

For example:

# Canonical redirect
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{QUERY_STRING} ^(?:product=(\d*))?$ [NC]
RewriteRule ^product/product\.php$ /product/%1 [NC,R=307,L]

# Rewrite requests from "pretty" URL to underlying filesystem path
RewriteRule ^product/(\d*) /product/product.php?product=$1 [L]

The condition that checks against the REDIRECT_STATUS environment variable is necessary to prevent a redirect loop in this instance since the query string is entirely optional.

By restricting the match to digits-only, we avoid the need for an additional condition on the internal rewrite, product.php won't match. If the product id can contain letters then restrict the pattern to avoid dots (.), eg. ([^./]*).

Only include a NC flag on the internal rewrite if this is strictly necessary, otherwise this potentially creates a duplicate content issue.


问:
Create Group from Sequences
How can I create a "group" vector that identifies sequences of same values in another vector.

From this

```<code>x <- c(0,1,0,0,1,0,1)
</code>```

I want to create this

```<code>outcome <- c(1,2,3,3,4,5,6)

[1] 0 1 0 0 1 0 1
[1] 1 2 3 3 4 5 6
</code>```

So, whenever there is a new sequence of the same values there is a new group number (or can be something other than a number as well).

I would actually know ways to get there, but they are all hideous. The best I can come up with is

```<code>comparison <- x != lag(x)
cumsum(replace_na(comparison, TRUE))
</code>```

but like I said - hideous. There must be a better way and I hope someone knows it.

答:
If x is always only 0s and 1s, another option is

```<code>cumsum(c(1, (x[-1] + head(x, -1)) %% 2))

[1] 1 2 3 3 4 5 6
</code>```

Title: Create Group from Sequences

Body:
How can I create a "group" vector that identifies sequences of same values in another vector.

From this

x <- c(0,1,0,0,1,0,1)

I want to create this

outcome <- c(1,2,3,3,4,5,6)

[1] 0 1 0 0 1 0 1
[1] 1 2 3 3 4 5 6

So, whenever there is a new sequence of the same values there is a new group number (or can be something other than a number as well).

I would actually know ways to get there, but they are all hideous. The best I can come up with is

comparison <- x != lag(x)
cumsum(replace_na(comparison, TRUE))

but like I said - hideous. There must be a better way and I hope someone knows it.

Body:
If x is always only 0s and 1s, another option is

cumsum(c(1, (x[-1] + head(x, -1)) %% 2))

[1] 1 2 3 3 4 5 6