问:
Returning a class in Kotlin
```<code>class Wolf {
    var hunger = 10
    val food = "meat"

    fun eat() {
        println("The Wolf is eating $food")
    }
}

class MyWolf {
    var wolf: Wolf? = Wolf()

    fun myFunction() {
        wolf?.eat()
    }
}

fun getAlphaWolf(): Wolf? {
    return Wolf()
}

fun main(args: Array<String>) {
    var w: Wolf? = Wolf()

    if (w != null) {
        w.eat()
    }

    var x = w?.hunger
    println("The value of x is $x")

    var y = w?.hunger ?: -1
    println("The value of y is $y")

    var myWolf = MyWolf()
    myWolf?.wolf?.hunger = 8
    println("The value of myWolf?.wolf?.hunger is ${myWolf?.wolf?.hunger}")

    var myArray = arrayOf("Hi", "Hello", null)
    for (item in myArray) {
        item?.let { println(it) }
    }

    getAlphaWolf()?.let { it.eat() }

    w = null
    var z = w!!.hunger
}
</code>```

This above code is extracted from a Kotlin textbook.
I have problem with the following:

```<code>fun getAlphaWolf(): Wolf? {
     return Wolf()
}
</code>```

As there is only a class called Wolf but no variable called Wolf in the code.
I wonder if it is possible to return a class inside a function?
What is the output if a class is returned inside a function?

答:
In the following code, the primary constructor of class Wolf is called:

```<code>fun getAlphaWolf(): Wolf? {
     return Wolf()
}
</code>```

So, getAlphaWolf returns a completely new instance of Wolf with default values: Wolf(hunger=10,food=meat).

Update: by the way, making the return type of this function nullable is redundant, because a new instance cannot be null.

Title: Returning a class in Kotlin

Body:
class Wolf {
    var hunger = 10
    val food = "meat"

    fun eat() {
        println("The Wolf is eating $food")
    }
}

class MyWolf {
    var wolf: Wolf? = Wolf()

    fun myFunction() {
        wolf?.eat()
    }
}

fun getAlphaWolf(): Wolf? {
    return Wolf()
}

fun main(args: Array<String>) {
    var w: Wolf? = Wolf()

    if (w != null) {
        w.eat()
    }

    var x = w?.hunger
    println("The value of x is $x")

    var y = w?.hunger ?: -1
    println("The value of y is $y")

    var myWolf = MyWolf()
    myWolf?.wolf?.hunger = 8
    println("The value of myWolf?.wolf?.hunger is ${myWolf?.wolf?.hunger}")

    var myArray = arrayOf("Hi", "Hello", null)
    for (item in myArray) {
        item?.let { println(it) }
    }

    getAlphaWolf()?.let { it.eat() }

    w = null
    var z = w!!.hunger
}

This above code is extracted from a Kotlin textbook.
I have problem with the following:

fun getAlphaWolf(): Wolf? {
     return Wolf()
}

As there is only a class called Wolf but no variable called Wolf in the code.
I wonder if it is possible to return a class inside a function?
What is the output if a class is returned inside a function?

Body:
In the following code, the primary constructor of class Wolf is called:

fun getAlphaWolf(): Wolf? {
     return Wolf()
}

So, getAlphaWolf returns a completely new instance of Wolf with default values: Wolf(hunger=10,food=meat).

Update: by the way, making the return type of this function nullable is redundant, because a new instance cannot be null.


来源: stackexchange

问:
print file content as quoted comma separated single line
How to print a file content as quoted and comma separated single line.

```<code>$cat test
file1.gz
file2.gz
file3.gz
file4.gz
</code>```

I want to print as 'file1.gz','file2.gz','file3.gz','file4.gz'

答:
Convert one column to one row with separator. With sed and paste:

```<code>sed "s/.*/'&'/" file | paste -sd ","
</code>```

Output:

```
'file1.gz','file2.gz','file3.gz','file4.gz'
```

ContentLicense: CC BY-SA 4.0

Body:
How to print a file content as quoted and comma separated single line.

$cat test
file1.gz
file2.gz
file3.gz
file4.gz

I want to print as 'file1.gz','file2.gz','file3.gz','file4.gz'

Body:
Convert one column to one row with separator. With sed and paste:

sed "s/.*/'&'/" file | paste -sd ","

Output:

'file1.gz','file2.gz','file3.gz','file4.gz'


问:
How to use lock as a mutex in multiprocessing?
I want to have two processes, one writing and one reading on/from the same variable. The data written is like this:

```<code>[0, 0]
[0, 1]
[1, 0]
[1, 1]
[2, 0]
[2, 1]
[3, 0]
[3, 1]
[4, 0]
[4, 1]
[5, 0]
[5, 1]
[6, 0]
[6, 1]
[7, 0]
[7, 1]
[8, 0]
[8, 1]
[9, 0]
[9, 1]
</code>```

But I'm having trouble because the reading process is reading between the variable change, forming new pairs, so I want to use a Lock/Mutex to prevent this from happening again. I guess I'd have to lock the object before changing it.
OBS: The object is shared between processes using a manager.

Here is the main code:

```<code>import multiprocessing

def mde(dad, mutex):
    for i in range(10):
        for j in range(2):
            mutex.acquire()
            dad[0] = i
            dad[1] = j
            mutex.release()
def mda(dad):
    c = 0
    while c < 30:
        print(dad)
        c += 1

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    mutex = manager.Lock()
    dado = manager.list([0, 0])
    p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))
    p2 = multiprocessing.Process(target=mda, args=(dado,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
</code>```

As you can see I tried to lock and unlock the variable in the writing process but the result still was mixed up. What am I doing wrong?

答:
Here is the corrected version (credit to MisterMiyagi). Both workers are waiting for each other to do their task, i.e. modifying the list, or displaying it.</p>

```<code>import multiprocessing

NX = 10
NY = 2

def mde(dad, mutex):
    for i in range(NX):
        for j in range(NY):
            mutex.acquire()
            dad[0] = i
            dad[1] = j
            mutex.release()

def mda(dad, mutex):
    c = 0
    while c <= NX*NY:
        mutex.acquire()
        print(dad)
        c += 1
        mutex.release()

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    mutex = manager.Lock()
    dado = manager.list([0, 0])
    p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))
    p2 = multiprocessing.Process(target=mda, args=(dado, mutex,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
</code>```

Body:
I want to have two processes, one writing and one reading on/from the same variable. The data written is like this:

[0, 0]
[0, 1]
[1, 0]
[1, 1]
[2, 0]
[2, 1]
[3, 0]
[3, 1]
[4, 0]
[4, 1]
[5, 0]
[5, 1]
[6, 0]
[6, 1]
[7, 0]
[7, 1]
[8, 0]
[8, 1]
[9, 0]
[9, 1]

But I'm having trouble because the reading process is reading between the variable change, forming new pairs, so I want to use a Lock/Mutex to prevent this from happening again. I guess I'd have to lock the object before changing it.
OBS: The object is shared between processes using a manager.

Here is the main code:

import multiprocessing

def mde(dad, mutex):
    for i in range(10):
        for j in range(2):
            mutex.acquire()
            dad[0] = i
            dad[1] = j
            mutex.release()
def mda(dad):
    c = 0
    while c < 30:
        print(dad)
        c += 1

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    mutex = manager.Lock()
    dado = manager.list([0, 0])
    p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))
    p2 = multiprocessing.Process(target=mda, args=(dado,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

As you can see I tried to lock and unlock the variable in the writing process but the result still was mixed up. What am I doing wrong?

Body:
Here is the corrected version (credit to MisterMiyagi). Both workers are waiting for each other to do their task, i.e. modifying the list, or displaying it.

import multiprocessing

NX = 10
NY = 2

def mde(dad, mutex):
    for i in range(NX):
        for j in range(NY):
            mutex.acquire()
            dad[0] = i
            dad[1] = j
            mutex.release()

def mda(dad, mutex):
    c = 0
    while c <= NX*NY:
        mutex.acquire()
        print(dad)
        c += 1
        mutex.release()

if __name__ == '__main__':
    manager = multiprocessing.Manager()
    mutex = manager.Lock()
    dado = manager.list([0, 0])
    p1 = multiprocessing.Process(target=mde, args=(dado, mutex,))
    p2 = multiprocessing.Process(target=mda, args=(dado, mutex,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()


问:
xml parsing in iPhone-sdk 3.0
```<code>// ResxmlParser is globally declared as NSXMLParser

-(void)parsingXML:(NSString *)resXml
{

   NSData *xmlNsData =[resXml dataUsingEncoding:NSASCIIStringEncoding];

        ResxmlParser = [[NSXMLParser alloc] initWithData:xmlNsData ];

        [ResxmlParser setDelegate: self];
        [ResxmlParser setShouldResolveExternalEntities: YES];
        [ResxmlParser parse] ;

}

 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
 {

 //NSLog(@"-----------%@",string);

 }

//------------------------------------------------------------------------------------
</code>```

this is working fine in iPhone sdk 2.2 and lower version , but it is not working on sdk 3.0..

any body can help me to solve this problem.. ?

答:
You can use Yahoo RSS for xml Parsing demo as below
I Pick Titles and description from RSS Item in this demo</p>

```<code>- (void)viewDidLoad {

NSURL *url = [[NSURL alloc] initWithString:@"http://www.ibtimes.com/rss/articles/reporters/david-zielenziger.rss"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

//Set delegate
[xmlParser setDelegate:self];

//Start parsing the XML file.
BOOL success = [xmlParser parse];

if(success)
    NSLog(@"No Errors");
else
    NSLog(@"Error Error Error!!!");
[super viewDidLoad];

NSLog(@"My array is %@",[arrData description]);
[tblView reloadData];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
  attributes:(NSDictionary *)attributeDict
{

NSLog(@"didStartElement Element:- %@",elementName);

if([elementName isEqualToString:@"rss"])
{
    if(arrData ==nil)
    {
        arrData = [[NSMutableArray alloc] init];
    }
}

else if([elementName isEqualToString:@"item"])
{
    if(([dictData retainCount]>0) && dictData!=nil)
    {
        [dictData release];
    }
    dictData=[[NSMutableDictionary alloc] init];

}
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{

NSLog(@"String :- %@",string);
if(!currentElementValue)
    currentElementValue = [[NSString alloc] initWithString:string];
else
    //currentElementValue = [NSString stringWithString:string];
    currentElementValue = [currentElementValue stringByAppendingString:string];
currentElementValue = [currentElementValue stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSLog(@"Processing Value: %@", currentElementValue);
}

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
 {

if([elementName isEqualToString:@"title"])
{
    [dictData setValue:currentElementValue forKey:elementName];
}
else if([elementName isEqualToString:@"description"])
{
    [dictData setValue:currentElementValue forKey:elementName];

}

else if([elementName isEqualToString:@"item"])
{
    [arrData addObject:dictData];
}
currentElementValue = @"";

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{

cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

cell.textLabel.text=[[arrData objectAtIndex:indexPath.row] valueForKey:@"title"];
cell.detailTextLabel.text=[[arrData objectAtIndex:indexPath.row] valueForKey:@"description"];

return cell;
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: xml parsing in iPhone-sdk 3.0

Body:
// ResxmlParser is globally declared as NSXMLParser

-(void)parsingXML:(NSString *)resXml
{

   NSData *xmlNsData =[resXml dataUsingEncoding:NSASCIIStringEncoding];

        ResxmlParser = [[NSXMLParser alloc] initWithData:xmlNsData ];

        [ResxmlParser setDelegate: self];
        [ResxmlParser setShouldResolveExternalEntities: YES];
        [ResxmlParser parse] ;

}

 -(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
 {

 //NSLog(@"-----------%@",string);

 }

//------------------------------------------------------------------------------------

this is working fine in iPhone sdk 2.2 and lower version , but it is not working on sdk 3.0..

any body can help me to solve this problem.. ?

Body:
You can use Yahoo RSS for xml Parsing demo as below
I Pick Titles and description from RSS Item in this demo

- (void)viewDidLoad {

NSURL *url = [[NSURL alloc] initWithString:@"http://www.ibtimes.com/rss/articles/reporters/david-zielenziger.rss"];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];

//Set delegate
[xmlParser setDelegate:self];

//Start parsing the XML file.
BOOL success = [xmlParser parse];

if(success)
    NSLog(@"No Errors");
else
    NSLog(@"Error Error Error!!!");
[super viewDidLoad];

NSLog(@"My array is %@",[arrData description]);
[tblView reloadData];
}

-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
  attributes:(NSDictionary *)attributeDict
{

NSLog(@"didStartElement Element:- %@",elementName);

if([elementName isEqualToString:@"rss"])
{
    if(arrData ==nil)
    {
        arrData = [[NSMutableArray alloc] init];
    }
}

else if([elementName isEqualToString:@"item"])
{
    if(([dictData retainCount]>0) && dictData!=nil)
    {
        [dictData release];
    }
    dictData=[[NSMutableDictionary alloc] init];

}
}

-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{

NSLog(@"String :- %@",string);
if(!currentElementValue)
    currentElementValue = [[NSString alloc] initWithString:string];
else
    //currentElementValue = [NSString stringWithString:string];
    currentElementValue = [currentElementValue stringByAppendingString:string];
currentElementValue = [currentElementValue stringByReplacingOccurrencesOfString:@"\n" withString:@""];

NSLog(@"Processing Value: %@", currentElementValue);
}

 -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
 {

if([elementName isEqualToString:@"title"])
{
    [dictData setValue:currentElementValue forKey:elementName];
}
else if([elementName isEqualToString:@"description"])
{
    [dictData setValue:currentElementValue forKey:elementName];

}

else if([elementName isEqualToString:@"item"])
{
    [arrData addObject:dictData];
}
currentElementValue = @"";

}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{

cell=[[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

cell.textLabel.text=[[arrData objectAtIndex:indexPath.row] valueForKey:@"title"];
cell.detailTextLabel.text=[[arrData objectAtIndex:indexPath.row] valueForKey:@"description"];

return cell;
}

ContentLicense: CC BY-SA 3.0


问:
MySQL Question - I want to eliminate all text within any parenthesis
Just checking to see if any of you would have a solution for this – from the below text like this I want to eliminate all text within any parenthesis.

Input –

PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)

Output –

PAY - addition,FILES,DED,LOSS,F TO G

答:
If you are running MySQL 8.0, you can do this with regexp_replace():

```<code>regexp_replace(mytext, '\\([^)]*\\)', '')
</code>```

This works as long as there are no nested parentheses in the expression (which is consistent with your sample data).

Demo on DB Fiddle:

```<code> select regexp_replace(
    'PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)',
    '\\([^)]*\\)',
    ''
) val
</code>```

```
| val                                      |
| :--------------------------------------- |
| PAY - addition,FILES ,DED ,LOSS ,F TO G  |
```

Body:
If you are running MySQL 8.0, you can do this with regexp_replace():

regexp_replace(mytext, '\\([^)]*\\)', '')

This works as long as there are no nested parentheses in the expression (which is consistent with your sample data).

Demo on DB Fiddle:

 select regexp_replace(
    'PAY - addition,FILES (aaaaaaaaaaaaaa/bbbbbbbbbbbs i.e. ssss,ffff – i.e. cccccc),DED (ppppppp, llllll, fffff gggg),LOSS (ddddd, hhhhhh – i.e.),F TO G ( “F” is switching to “G”)',
    '\\([^)]*\\)',
    ''
) val

| val                                      |
| :--------------------------------------- |
| PAY - addition,FILES ,DED ,LOSS ,F TO G  |


问:
Replace text stored in string
Using iText 5.5, I am trying to assign value from list to variable. Any professional eager to help amateur?

File I am parsing: https://slicedinvoices.com/pdf/wordpress-pdf-invoice-plugin-sample.pdf

Here is my code:

```<code>using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDF_file_reader
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> InvoiceNumbers = new List<string>();

            string filePath = @"C:\temp\parser\Invoice_Template.pdf";
            int pagesToScan = 2;

            string strText = string.Empty;
            try
            {
                PdfReader reader = new PdfReader(filePath);

                for (int page = 1; page <= pagesToScan; page++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
                {
                    ITextExtractionStrategy its = new LocationTextExtractionStrategy();
                    strText = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
                    //creating the string array and storing the PDF line by line
                    string[] lines = strText.Split('\n');
                    foreach (string line in lines)
                    {
                        if (line.Contains("Invoice Number"))
                        {
                            InvoiceNumbers.Add(line.Trim());
                            break;
                        }
                    }

                    var match = InvoiceNumbers.FirstOrDefault(stringToCheck => stringToCheck.Contains("Invoice Number"));

                    match.Replace("Invoice number", "").Trim();

                    Console.Write(match);

                    Console.Read();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }
    }
}
</code>```

I need match to be INV-3337 currently it seems to be Invoice Number INV-3337. Why this command:

match.Replace("Invoice number", "").Trim();?

does not perform Replace.

My output:

答:
Instead of writing:

```<code>match.Replace("Invoice number", "").Trim();
</code>```

use:

```<code>match = match.Replace("Invoice Number", "").Trim();
</code>```

Title: Replace text stored in string

Body:
Using iText 5.5, I am trying to assign value from list to variable. Any professional eager to help amateur?

File I am parsing: https://slicedinvoices.com/pdf/wordpress-pdf-invoice-plugin-sample.pdf

Here is my code:

using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PDF_file_reader
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> InvoiceNumbers = new List<string>();

            string filePath = @"C:\temp\parser\Invoice_Template.pdf";
            int pagesToScan = 2;

            string strText = string.Empty;
            try
            {
                PdfReader reader = new PdfReader(filePath);

                for (int page = 1; page <= pagesToScan; page++) //(int page = 1; page <= reader.NumberOfPages; page++) <- for scanning all the pages in A PDF
                {
                    ITextExtractionStrategy its = new LocationTextExtractionStrategy();
                    strText = PdfTextExtractor.GetTextFromPage(reader, page, its);

                    strText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(strText)));
                    //creating the string array and storing the PDF line by line
                    string[] lines = strText.Split('\n');
                    foreach (string line in lines)
                    {
                        if (line.Contains("Invoice Number"))
                        {
                            InvoiceNumbers.Add(line.Trim());
                            break;
                        }
                    }

                    var match = InvoiceNumbers.FirstOrDefault(stringToCheck => stringToCheck.Contains("Invoice Number"));

                    match.Replace("Invoice number", "").Trim();

                    Console.Write(match);

                    Console.Read();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
        }
    }
}

I need match to be INV-3337 currently it seems to be Invoice Number INV-3337. Why this command:

match.Replace("Invoice number", "").Trim();?

does not perform Replace.

My output:

Body:
Instead of writing:

match.Replace("Invoice number", "").Trim();

use:

match = match.Replace("Invoice Number", "").Trim();


答: For others, coming across this thread. This is also due to the usage of non-ASCII characters to represent "-". Simply fix the non-ascii character in the float representation using regex or other methods and the conversion would work. More details available at Python convert string to float error with negative numbers</p>

Title: Python, negative numbers string to float

Body:
This is a very simple issue but I am making it needlessly complex and continue to hit road blocks.

I am trying to parse a simple text file which contains point cloud information, x, y, z.

It looks like this:

vertices:
v -543.243 -494.262 1282
v -538.79 -494.262 1282
v -536.422 -496.19 1287
v -531.951 -496.19 1287
v -527.481 -496.19 1287
v -213.909 -223.999 581
v -212.255 -224.384 582
v -209.15 -223.228 579
v -207.855 -223.999 581
v -205.482 -223.613 580
v -203.468 -223.613 580
v -201.106 -223.228 579
v -199.439 -223.613 580
v -197.765 -223.999 581
v -195.41 -223.613 580
v -193.062 -223.228 579
v -190.721 -222.842 578
v -189.04 -223.228 579
v -187.998 -224.384 582
v -185.976 -224.384 582
v -183.955 -224.384 582
v -181.621 -223.999 581
v -179.293 -223.613 580
v -177.279 -223.613 580
v -175.264 -223.613 580
v -173.549 -223.999 581
v -171.531 -223.999 581
v -169.513 -223.999 581
v -167.495 -223.999 581
v -165.761 -224.384 582
v -163.74 -224.384 582
v -161.718 -224.384 582
v -159.697 -224.384 582
v -157.946 -224.77 583
v -155.921 -224.77 583
v -153.896 -224.77 583
v -151.871 -224.77 583
v -149.847 -224.77 583
v -147.568 -224.384 582

Right okay. Not so bad.

Next I am using python in blender to convert these points into vertices:

It looks like so: `

    #Open the file
try:
    f=open(path, 'r')
except:
    print ("Path is not Valid")

#Create an array of
verts = []
#verts=[float(e) for e in verts if e]
#values = []

for line in f:
    lines = f.readline()
    #values = ([c for c in lines if c in '-1234567890.'])
    if line.startswith("v "): #Go through file line by line
        read = lines.strip(' v\n').split(',') #remove the v,split@,
            #read = values.split(',')
        #loop over all stuff in read, remove non-numerics
        for d in read:
            d= d.strip('-').split(' ')
            print("d:", (d))
            for n in d:
                n = n.strip('-')
                verts = verts.append(float(n[0]))
                #verts = verts.append(float(n[2]))
                #verts = verts.append(float(n[3]))
                print("vertsloops", d[0])
            print("read1", read[0])
            print(read)
            print("oo1verts", verts)
             ##################
             #Extend the array#
             #print ("Could not use the line reading: %s"%read)

# Create a new mesh, it is now empty
mesh = bpy.data.meshes.new("Cube")
# Create empty vertices field in the mesh
mesh.vertices.add(len(verts))
# Add vertices
mesh.vertices.foreach_set("co", verts)

#Add a new empty object named "Read the PointCloud Data"
obj = bpy.data.objects.new("Read the PointCloud Data", mesh)
# Link object to current scene
bpy.context.scene.objects.link(obj)
`

Somehow, I have tried many different combinations of splitting the string, but still getting errors. I know this is a simple task!?! Any Advice please!

The errors I get look at first like:

d: ['-536.422', '-496.19', '1287']
Traceback (most recent call last):
  File "/Users/.../importpoints.blend/importpoints", line 37, in <module>
ValueError: could not convert string to float: '-'
Error: Python script fail, look in the console for now...

And Then like so :

d: ['536.422', '-496.19', '1287']
vertsloops 536.422
Traceback (most recent call last):
  File "/Users/.../importpoints.blend/importpoints", line 37, in <module>
AttributeError: 'NoneType' object has no attribute 'append'
Error: Python script fail, look in the console for now...

One thing is, how come float('-531') won't be handled as a negative number. As it stands, it hits the '-' sting and considers it non-numeric so it cannot convert it. But its negative, so how can I indicate that???

Thanks.


问:
FormData object from React doesnt convert on backend C# to model
I have application made with React Native, and the backend API is in .NET C#.
I am trying to send some data from frontend to backend

reactjs

```<code>let formData = new FormData();
formData.append('token', token)
formData.append('document', document)
formData.append('file', file);
</code>```

Where token is a string, file is some file, but document is an object with params like Id and Name . So on backend I receive the data like this

C#

```<code>[HttpPost]
[AllowAnonymous]
public ActionResult SendDocument(string token, DocumentMobile document, HttpPostedFileBase file)
{
    //do thins
}
</code>```

The problem is that object document is not converted to DocumentMobile model, like it used to do without using FormData, and all props inside are null.

How to do this?

答:
By default, model binding gets data in the form of key-value pairs, assuming both are strings. Files are an exception.

You can pass key-value pairs like this

```<code>formData.append('document.title', document.title)
</code>```

Alternatively, you can build a custom model binder. Like it is described in this SO.

Body:
I have application made with React Native, and the backend API is in .NET C#.
I am trying to send some data from frontend to backend

reactjs

let formData = new FormData();
formData.append('token', token)
formData.append('document', document)
formData.append('file', file);

Where token is a string, file is some file, but document is an object with params like Id and Name . So on backend I receive the data like this

C#

[HttpPost]
[AllowAnonymous]
public ActionResult SendDocument(string token, DocumentMobile document, HttpPostedFileBase file)
{
    //do thins
}

The problem is that object document is not converted to DocumentMobile model, like it used to do without using FormData, and all props inside are null.

How to do this?

Body:
By default, model binding gets data in the form of key-value pairs, assuming both are strings. Files are an exception.

You can pass key-value pairs like this

formData.append('document.title', document.title)

Alternatively, you can build a custom model binder. Like it is described in this SO.


问:
What would happen to Application Insight when a Azure region goes down. Will Application insight still be accessible
What would happen to Application Insight when a Azure region goes down. Will Application insight still be accessible??? as we rely on telemetry data. </p>

答:
There is no built-in geo-replication for Application Insights. Best practice would be for you to have an instance for each of your application deployments in every region. E.g. if your app runs in East US and in West Europe, also have AppInsights in each region and log to there respectively.

If you need to have your telemetry available in cases of an regional outage as well, I would look into Continuous Export - to a storage account in a separate region.


问:
How to insert list of objects in 1 write to DynamoDB using Python?
Hi I am trying to generate a table that will have all the taxi trips of 1 day.
One of the attributes of 1 taxi trip would include a list of all the discounts that that were used on that trip.

There can be any number of discounts used. What I am not sure how to do is how can I include that list of discounts into one item attribute? So basically write 1 item with a list of attributes into DynamoDB?

Here is my table:

```<code>def create_table(self):
        table = dynamodb.create_table(
            TableName='TaxiTable',
            KeySchema=[
                {
                    'AttributeName': 'trip',
                    'KeyType': 'HASH'
                },
            ],
            AttributeDefinitions=[
                {
                    'AttributeName': 'trip',
                    'AttributeType': 'S'
                },

            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 10,
                'WriteCapacityUnits': 10
            }
        )

        print("Table status:", table.table_status)
</code>```

The 'trip' key would be 1 long string with the origin of that taxi ride, where it's last stop of the day was at, the taxi number, the number of stops, and the date of the trip.

```<code>trip_key: 12thAve.MapleDrive.0124.02.02202020
</code>```

underneath as an attribute I would like a list of all the discounts that were used on that taxi trip/
Something like:

```<code>trip_key: 12thAve.MapleDrive.0124.02.02202020
discount_map:
{
  discount1: { name: 'Senior', total_saved: '10'},
  discount2: { name: 'Student', total_saved: '30'},
  discount3: { name: 'Employee', total_saved: '20'},
  discount4: { name: 'Hotel', total_saved: '30'}
}
</code>```

I do not know how many discounts could be used on one trip. Could be between 5-10. But I would like to include all the discounts used in one insert. I would want to query a specific discount used on a taxi trip and the total saved from this table.

I dont know if first I should convert the list into a JSON object? Or if there is a way to iterate through the list and insert it how I would like.

```<code>import boto3

class taxi_discount:
    name = None
    total_saved = None

# rest of logic for this class...

class insert_to_dynamoDb:

    dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

    taxi_trip_key= None
    taxi_discounts_list = []

    def __init__(taxi_trip, discount_list):
            self.taxi_trip_key= taxi_trip
            self.discount_list = discount_list

    def write_to_table(self):
            table = dynamodb.Table('TaxiTable')

            response = table.put_item(
                Item={
                    'trip': taxi_trip_key,
                    'discount_map': taxi_discounts_list
                    }
                } )

</code>```

答:
DynamoDB supports batch writing.

Example from docs:

```<code>with table.batch_writer() as batch:
    for i in range(50):
        batch.put_item(
            Item={
                'account_type': 'anonymous',
                'username': 'user' + str(i),
                'first_name': 'unknown',
                'last_name': 'unknown'
            }
        )
</code>```

Guide docs

API docs

Body:
Hi I am trying to generate a table that will have all the taxi trips of 1 day.
One of the attributes of 1 taxi trip would include a list of all the discounts that that were used on that trip.

There can be any number of discounts used. What I am not sure how to do is how can I include that list of discounts into one item attribute? So basically write 1 item with a list of attributes into DynamoDB?

Here is my table:

def create_table(self):
        table = dynamodb.create_table(
            TableName='TaxiTable',
            KeySchema=[
                {
                    'AttributeName': 'trip',
                    'KeyType': 'HASH'
                },
            ],
            AttributeDefinitions=[
                {
                    'AttributeName': 'trip',
                    'AttributeType': 'S'
                },

            ],
            ProvisionedThroughput={
                'ReadCapacityUnits': 10,
                'WriteCapacityUnits': 10
            }
        )

        print("Table status:", table.table_status)

The 'trip' key would be 1 long string with the origin of that taxi ride, where it's last stop of the day was at, the taxi number, the number of stops, and the date of the trip.

trip_key: 12thAve.MapleDrive.0124.02.02202020

underneath as an attribute I would like a list of all the discounts that were used on that taxi trip/
Something like:

trip_key: 12thAve.MapleDrive.0124.02.02202020
discount_map:
{
  discount1: { name: 'Senior', total_saved: '10'},
  discount2: { name: 'Student', total_saved: '30'},
  discount3: { name: 'Employee', total_saved: '20'},
  discount4: { name: 'Hotel', total_saved: '30'}
}

I do not know how many discounts could be used on one trip. Could be between 5-10. But I would like to include all the discounts used in one insert. I would want to query a specific discount used on a taxi trip and the total saved from this table.

I dont know if first I should convert the list into a JSON object? Or if there is a way to iterate through the list and insert it how I would like.

import boto3

class taxi_discount:
    name = None
    total_saved = None

# rest of logic for this class...

class insert_to_dynamoDb:

    dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

    taxi_trip_key= None
    taxi_discounts_list = []

    def __init__(taxi_trip, discount_list):
            self.taxi_trip_key= taxi_trip
            self.discount_list = discount_list

    def write_to_table(self):
            table = dynamodb.Table('TaxiTable')

            response = table.put_item(
                Item={
                    'trip': taxi_trip_key,
                    'discount_map': taxi_discounts_list
                    }
                } )

Body:
DynamoDB supports batch writing.

Example from docs:

with table.batch_writer() as batch:
    for i in range(50):
        batch.put_item(
            Item={
                'account_type': 'anonymous',
                'username': 'user' + str(i),
                'first_name': 'unknown',
                'last_name': 'unknown'
            }
        )

Guide docs

API docs


问:
GWT Project Structure
Right now in our project, we have below mentioned structure. Our project is mainly using GWT & Spring framework.

com.customername.projectname.client.module name

com.customername.projectname.client.rpc.module name

com.customername.projectname.shared.validator.module name

com.customername.projectname.server.module name

com.customername.projectname.spring.dao.module name

com.customername.projectname.spring.service.module name

Our application.gwt.xml contains below entry for source which needs to be coverted in to java script.

```<code>source path='client'
source path='shared'
</code>```

As we are using spring at the server side, we are using spring annotation to mark the services and DAO and then in applicationContext.xml we are using below configuration to scan the DAO and Service Layer.

```<code><context:annotation-config/>
<context:component-scan base-package>
</code>```

Now our client wants to go with below mentioned structure. Grouping everything by module. Also in our case module is not GWT module. It is just like diff. parts of the application.

com.customername.projectname.modulename.client

com.customername.projectname.modulename.rpc

com.customername.projectname.Modulename.validator

com.customername.projectname.Modulename.server

com.customername.projectname.Modulename.spring.dao

com.customername.projectname.Modulename.spring.Service

My question is:

Is the upper approach is recommended considering it is very large application?

If the above approach is to be implemented , how to go about setting up the packages/source files which needs to be converted by gwt compiler from java to java script. Should I mention each module name in application.gwt.xml?

答:
To answer the second question, you should have one .gwt.xml file for each module, pointing out the client (and shared) directories in that module. For the GWT modules that use other GWT modules, you should use "inherit" in the .gwt.xml file to refer to them.

This page describes some of these concepts quite well:
http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html

Title: GWT Project Structure

Body:
Right now in our project, we have below mentioned structure. Our project is mainly using GWT & Spring framework.

com.customername.projectname.client.module name

com.customername.projectname.client.rpc.module name

com.customername.projectname.shared.validator.module name

com.customername.projectname.server.module name

com.customername.projectname.spring.dao.module name

com.customername.projectname.spring.service.module name

Our application.gwt.xml contains below entry for source which needs to be coverted in to java script.

source path='client'
source path='shared'

As we are using spring at the server side, we are using spring annotation to mark the services and DAO and then in applicationContext.xml we are using below configuration to scan the DAO and Service Layer.

<context:annotation-config/>
<context:component-scan base-package>

Now our client wants to go with below mentioned structure. Grouping everything by module. Also in our case module is not GWT module. It is just like diff. parts of the application.

com.customername.projectname.modulename.client

com.customername.projectname.modulename.rpc

com.customername.projectname.Modulename.validator

com.customername.projectname.Modulename.server

com.customername.projectname.Modulename.spring.dao

com.customername.projectname.Modulename.spring.Service

My question is:

Is the upper approach is recommended considering it is very large application?

If the above approach is to be implemented , how to go about setting up the packages/source files which needs to be converted by gwt compiler from java to java script. Should I mention each module name in application.gwt.xml?


问:
How to select value inside array
This the code in the var named available_dates

var available_dates = ["08-11-2018","09-11-2018"]

I wonder how can I choose the second date of the var and selected, to my second code

document.getElementById('app_date').value = available_dates

答:
You can simply access a value in your array available_dates by doing this:

```<code>document.getElementById('app_date').value = available_dates[i]
</code>```

Be careful to the fact that indexes start from 0. so available_dates[0] will return the first index. available_dates[1] will return the second and so on.

Title: How to select value inside array

Body:
You can simply access a value in your array available_dates by doing this:

document.getElementById('app_date').value = available_dates[i]

Be careful to the fact that indexes start from 0. so available_dates[0] will return the first index. available_dates[1] will return the second and so on.


问:
presto with hudi - select * from table
I have a parquet record created with hudi off a spark kinesis stream and stored in S3.

An AWS glue table is generated from this record. I update the InputRecord type to org.apache.hudi.hadoop.realtime.HoodieParquetRealtimeInputFormat as per instructions https://cwiki.apache.org/confluence/display/HUDI/Migration+Guide+From+com.uber.hoodie+to+org.apache.hudi

From the presto-cli i run

```<code>presto-cli --catalog hive --schema my-schema --server my-server:8889
presto:my-schema> select * from table
</code>```

this returns

```<code>Query 20200211_185222_00050_hej8h, FAILED, 1 node
Splits: 17 total, 0 done (0.00%)
0:01 [0 rows, 0B] [0 rows/s, 0B/s]

Query 20200211_185222_00050_hej8h failed: No value present
</code>```

however when i run

```<code>select id from table
</code>```

it returns

```<code>    id
----------
 34551832
(1 row)

Query 20200211_185250_00051_hej8h, FINISHED, 1 node
Splits: 17 total, 17 done (100.00%)
0:00 [1 rows, 93B] [2 rows/s, 213B/s]
</code>```

is this expected behaviour? or is there an underlying issue with the setup between Hudi/AWS Glue/Presto

Update 12-Feb-2020

Stack track using --debug option

```<code>presto:schema> select * from table;

Query 20200212_092259_00006_hej8h, FAILED, 1 node
http://xx-xxx-xxx-xxx.xx-xxxxx-xxx.compute.amazonaws.com:8889/ui/query.html?20200212_092259_00006_hej8h
Splits: 17 total, 0 done (0.00%)
CPU Time: 0.0s total,     0 rows/s,     0B/s, 23% active
Per Node: 0.1 parallelism,     0 rows/s,     0B/s
Parallelism: 0.1
Peak Memory: 0B
0:00 [0 rows, 0B] [0 rows/s, 0B/s]

Query 20200212_092259_00006_hej8h failed: No value present
java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at com.facebook.presto.parquet.reader.ParquetReader.readArray(ParquetReader.java:156)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:282)
    at com.facebook.presto.parquet.reader.ParquetReader.readStruct(ParquetReader.java:193)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:276)
    at com.facebook.presto.parquet.reader.ParquetReader.readStruct(ParquetReader.java:193)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:276)
    at com.facebook.presto.parquet.reader.ParquetReader.readBlock(ParquetReader.java:268)
    at com.facebook.presto.hive.parquet.ParquetPageSource$ParquetBlockLoader.load(ParquetPageSource.java:247)
    at com.facebook.presto.hive.parquet.ParquetPageSource$ParquetBlockLoader.load(ParquetPageSource.java:225)
    at com.facebook.presto.spi.block.LazyBlock.assureLoaded(LazyBlock.java:283)
    at com.facebook.presto.spi.block.LazyBlock.getLoadedBlock(LazyBlock.java:274)
    at com.facebook.presto.spi.Page.getLoadedPage(Page.java:261)
    at com.facebook.presto.operator.TableScanOperator.getOutput(TableScanOperator.java:254)
    at com.facebook.presto.operator.Driver.processInternal(Driver.java:379)
    at com.facebook.presto.operator.Driver.lambda$processFor$8(Driver.java:283)
    at com.facebook.presto.operator.Driver.tryWithLock(Driver.java:675)
    at com.facebook.presto.operator.Driver.processFor(Driver.java:276)
    at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:1077)
    at com.facebook.presto.execution.executor.PrioritizedSplitRunner.process(PrioritizedSplitRunner.java:162)
    at com.facebook.presto.execution.executor.TaskExecutor$TaskRunner.run(TaskExecutor.java:483)
    at com.facebook.presto.$gen.Presto_0_227____20200211_134743_1.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

</code>```

答: Appears the problem may be elsewhere, issue raised with hudi team here --> https://github.com/apache/incubator-hudi/issues/1325</p>

Title: presto with hudi - select * from table

Body:
I have a parquet record created with hudi off a spark kinesis stream and stored in S3.

An AWS glue table is generated from this record. I update the InputRecord type to org.apache.hudi.hadoop.realtime.HoodieParquetRealtimeInputFormat as per instructions https://cwiki.apache.org/confluence/display/HUDI/Migration+Guide+From+com.uber.hoodie+to+org.apache.hudi

From the presto-cli i run

presto-cli --catalog hive --schema my-schema --server my-server:8889
presto:my-schema> select * from table

this returns

Query 20200211_185222_00050_hej8h, FAILED, 1 node
Splits: 17 total, 0 done (0.00%)
0:01 [0 rows, 0B] [0 rows/s, 0B/s]

Query 20200211_185222_00050_hej8h failed: No value present

however when i run

select id from table

it returns

    id
----------
 34551832
(1 row)

Query 20200211_185250_00051_hej8h, FINISHED, 1 node
Splits: 17 total, 17 done (100.00%)
0:00 [1 rows, 93B] [2 rows/s, 213B/s]

is this expected behaviour? or is there an underlying issue with the setup between Hudi/AWS Glue/Presto

Update 12-Feb-2020

Stack track using --debug option

presto:schema> select * from table;

Query 20200212_092259_00006_hej8h, FAILED, 1 node
http://xx-xxx-xxx-xxx.xx-xxxxx-xxx.compute.amazonaws.com:8889/ui/query.html?20200212_092259_00006_hej8h
Splits: 17 total, 0 done (0.00%)
CPU Time: 0.0s total,     0 rows/s,     0B/s, 23% active
Per Node: 0.1 parallelism,     0 rows/s,     0B/s
Parallelism: 0.1
Peak Memory: 0B
0:00 [0 rows, 0B] [0 rows/s, 0B/s]

Query 20200212_092259_00006_hej8h failed: No value present
java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at com.facebook.presto.parquet.reader.ParquetReader.readArray(ParquetReader.java:156)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:282)
    at com.facebook.presto.parquet.reader.ParquetReader.readStruct(ParquetReader.java:193)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:276)
    at com.facebook.presto.parquet.reader.ParquetReader.readStruct(ParquetReader.java:193)
    at com.facebook.presto.parquet.reader.ParquetReader.readColumnChunk(ParquetReader.java:276)
    at com.facebook.presto.parquet.reader.ParquetReader.readBlock(ParquetReader.java:268)
    at com.facebook.presto.hive.parquet.ParquetPageSource$ParquetBlockLoader.load(ParquetPageSource.java:247)
    at com.facebook.presto.hive.parquet.ParquetPageSource$ParquetBlockLoader.load(ParquetPageSource.java:225)
    at com.facebook.presto.spi.block.LazyBlock.assureLoaded(LazyBlock.java:283)
    at com.facebook.presto.spi.block.LazyBlock.getLoadedBlock(LazyBlock.java:274)
    at com.facebook.presto.spi.Page.getLoadedPage(Page.java:261)
    at com.facebook.presto.operator.TableScanOperator.getOutput(TableScanOperator.java:254)
    at com.facebook.presto.operator.Driver.processInternal(Driver.java:379)
    at com.facebook.presto.operator.Driver.lambda$processFor$8(Driver.java:283)
    at com.facebook.presto.operator.Driver.tryWithLock(Driver.java:675)
    at com.facebook.presto.operator.Driver.processFor(Driver.java:276)
    at com.facebook.presto.execution.SqlTaskExecution$DriverSplitRunner.processFor(SqlTaskExecution.java:1077)
    at com.facebook.presto.execution.executor.PrioritizedSplitRunner.process(PrioritizedSplitRunner.java:162)
    at com.facebook.presto.execution.executor.TaskExecutor$TaskRunner.run(TaskExecutor.java:483)
    at com.facebook.presto.$gen.Presto_0_227____20200211_134743_1.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)


问:
Xcode 9 error: "iPhone has denied the launch request"
Using Xcode beta 9 (v4), I'm trying to launch the app by clicking on the "play" button. I get a "build succeeded" but right before launching, a popup message appears in Xcode:

"iPhone has denied the launch request."

It used to work yesterday. It does work on the simulator. I've rebooted my computer, the iPhone, uninstall the app, cleaned the build. Running out of ideas.

答:
If one trying to debug the app in real iOS devices connected through XCode, make sure you have selected provisional profile with iOS development certificate.

If you have selected provisional profile with distribution certificate then you will not able to use for debugging purpose this launching app locally through XCode will not work.


问:
String versus StringBuilder
I need to modify the input string to return some output. Basically, when I see a particular string I need to remove it. I am thinking whether to use StringBuilder versus String. From my perspective, String would be much simpler.

Suppose:

```<code>StringBuilder input = new StringBuilder(inputs)
if(inputs.contains("someword)"")) {
     // remove it by inputs = inputs.replace("someword", "");
}
</code>```

Is it better to use StringBuilder input = new StringBuilder(inputs) and delete the particular string or use the original inputs = inputs.replace(...).

I think it will get messy to use StringBuilder. StringBuilder is used for concatentation, but I am not concentating strings.

答:
In the past, StringBuilder was most times much faster than String when you applied multiple modifications to a String.

But since JDK 6, the compiler itself replaces String often automatically by StringBuilder (including all related lines) when this may improve the performance. This becomes visible by the use of a decompiler. So in most cases you won't notice any difference.

If you apply multiple operations to a string in a more complex structure than a simple batch of commands, then using StringBuilder is still better than the automatic compiler optimization.

Title: String versus StringBuilder

Body:
I need to modify the input string to return some output. Basically, when I see a particular string I need to remove it. I am thinking whether to use StringBuilder versus String. From my perspective, String would be much simpler.

Suppose:

StringBuilder input = new StringBuilder(inputs)
if(inputs.contains("someword)"")) {
     // remove it by inputs = inputs.replace("someword", "");
}

Is it better to use StringBuilder input = new StringBuilder(inputs) and delete the particular string or use the original inputs = inputs.replace(...).

I think it will get messy to use StringBuilder. StringBuilder is used for concatentation, but I am not concentating strings.


问:
Keep trailing zeroes in python
I am writing a class to represent money, and one issue I've been running into is that "1.50" != str(1.50).  str(1.50) equals 1.5, and alll of a sudden, POOF. 45 cents have vanished and the amount is now 1 dollar and 5 cents. not one dollar and 50 cents. Any way I could prevent str from doing this, or am I doing something wrong? This is Python 2 BTW.

答:
The proposed solutions do not work when the magnitude of the number is not known in advance, which is common in scientific applications rather than in money-related ones. I give an alternative solution for those, like me, coming to this question looking for the scientific case.

For example, if I want to print x = 1.500e-4 to three significant digits (common situation when dealing with measurements with a given uncertainty), the following command obviously does not give the correct result:

```<code>x = 1.500e-4
print(f"{x:.3f}")

----> 0.000
</code>```

Here I used the modern Python 3.6+ f-strings for the formatting.

One may think of using the g format specifier, but this also does not give the desired result to three significant digits as the trailing zero is omitted:

```<code>x = 1.500e-4
print(f"{x:.3g}")

----> 0.00015
</code>```

The correct answer can be obtained using the g format specifier together with a rather obscure option, the hash character #, of the format-specification mini language, in the following way:

```<code>x = 1.500e-4
print(f"{x:#.3g}")

----> 0.000150
</code>```

This formatting also works unchanged in the simpler case of the original question:

```<code>x = 1.500
print(f"{x:#.3g}")

----> 1.50
</code>```

Title: Keep trailing zeroes in python

Body:
The proposed solutions do not work when the magnitude of the number is not known in advance, which is common in scientific applications rather than in money-related ones. I give an alternative solution for those, like me, coming to this question looking for the scientific case.

For example, if I want to print x = 1.500e-4 to three significant digits (common situation when dealing with measurements with a given uncertainty), the following command obviously does not give the correct result:

x = 1.500e-4
print(f"{x:.3f}")

----> 0.000

Here I used the modern Python 3.6+ f-strings for the formatting.

One may think of using the g format specifier, but this also does not give the desired result to three significant digits as the trailing zero is omitted:

x = 1.500e-4
print(f"{x:.3g}")

----> 0.00015

The correct answer can be obtained using the g format specifier together with a rather obscure option, the hash character #, of the format-specification mini language, in the following way:

x = 1.500e-4
print(f"{x:#.3g}")

----> 0.000150

This formatting also works unchanged in the simpler case of the original question:

x = 1.500
print(f"{x:#.3g}")

----> 1.50


问:
Bash - How to show variable value instead of name in background process descriptions?
I have a function running process like this:

hello (){
  year=2001

  longRunProcess $year
}
```

<p>When I executed this function into background, the description of the running process is:</p>

<pre class="lang-sh prettyprint-override"><code>[1] longRunProcess $year
</code>```

, where I missed the information of $year. It cause me some troubles when running my hello() function in a for loop, which i cannot tell which year process is still running and which is not.

Is there a way to show the $year in process as its value instead of its name?

答:
If nothing else, you could use eval to expand the value before the command is invoked, rather than during:

$ arg=2001
$ sleep "$arg" &
[1] 4088610
$ eval "sleep ${arg@Q} &"
[2] 4088612
$ jobs
[1]-  Running                 sleep "$arg" &
[2]+  Running                 sleep '2001' &

```

${arg@Q} shell escapes the variable arg to make sure the eval won't be fragile or insecure if the argument changes from a simple number to arbitrary text.

Body:
I have a function running process like this:

hello (){
  year=2001

  longRunProcess $year
}

When I executed this function into background, the description of the running process is:

[1] longRunProcess $year

, where I missed the information of $year. It cause me some troubles when running my hello() function in a for loop, which i cannot tell which year process is still running and which is not.

Is there a way to show the $year in process as its value instead of its name?

Body:
If nothing else, you could use eval to expand the value before the command is invoked, rather than during:

$ arg=2001
$ sleep "$arg" &
[1] 4088610
$ eval "sleep ${arg@Q} &"
[2] 4088612
$ jobs
[1]-  Running                 sleep "$arg" &
[2]+  Running                 sleep '2001' &

${arg@Q} shell escapes the variable arg to make sure the eval won't be fragile or insecure if the argument changes from a simple number to arbitrary text.


问:
Consolidating 300+ files into 5-8, OutOfMemory exception
I have 369 files that need to be formatted and consolidated into 5-8 files before being submitted to the server.  I can't submit the 369 files because that would overwhelm the metadata tables in our database (they can handle it, but it'd be 369 rows for what was essentially one file, which would make querying and utilizing those tables a nightmare) and I can't handle it as one file because the total of 3.6 GB is too much for SSIS to handle on our servers.

I wrote the following script to fix the issue:

```<code>        static void PrepPAIDCLAIMSFiles()
        {
            const string HEADER = "some long header text, trimmed for SO question";
            const string FOOTER = "some long footer text, trimmed for SO question";
            //path is defined as a static member of the containing class
            string[] files = Directory.GetFiles(path + @"split\");
            int splitFileCount = 0, finalFileCount = 0;
            List<string> newFileContents = new List<string>();
            foreach(string file in files)
            {
                try
                {
                    var contents = File.ReadAllLines(file).ToList();
                    var fs = File.OpenRead(file);
                    if (splitFileCount == 0)
                    {
                        //Grab everything except the header
                        contents = contents.GetRange(1, contents.Count - 1);
                    }
                    else if (splitFileCount == files.Length - 1)
                    {
                        //Grab everything except the footer
                        contents = contents.GetRange(0, contents.Count - 1);
                    }
                    if (!Directory.Exists(path + @"split\formatted"))
                    {
                        Directory.CreateDirectory(path + @"split\formatted");
                    }
                    newFileContents.AddRange(contents);
                    if (splitFileCount % 50 == 0 || splitFileCount >= files.Length)
                    {
                        Console.WriteLine($"{splitFileCount} {finalFileCount}");
                        var sb = new StringBuilder(HEADER);
                        foreach (var row in newFileContents)
                        {
                            sb.Append(row);
                        }
                        sb.Append(FOOTER);
                        newFileContents = new List<string>();
                        GC.Collect();
                        string fileName = file.Split('\\').Last();
                        string baseFileName = fileName.Split('.')[0];
                        DateTime currentTime = DateTime.Now;
                        baseFileName += "." + COMPANY_NAME_SetHHMMSS(currentTime, finalFileCount) + ".TXT";
                        File.WriteAllText(path + @"split\formatted\" + baseFileName, sb.ToString());
                        finalFileCount += 1;
                    }
                    splitFileCount += 1;
                }
                catch(OutOfMemoryException OOM)
                {
                    Console.WriteLine(file);
                    Console.WriteLine(OOM.Message);
                    break;
                }
            }
        }
</code>```

The way this works is it reads the split file, puts its rows into a string builder, every time it gets to a multiple of 50 files, it writes the string builder to a new file and starts over.  The COMPANY_NAME_SetHHMMSS() method ensures the file has a unique name, so it's not writing to the same file over and over (and I can verify this by seeing the output, it writes two files before exploding.)

It breaks when it gets to the 81st file.  System.OutOfMemoryException on var contents = File.ReadAllLines(file).ToList();.  There's nothing special about the 81st file, it's the same exact size as all the others (~10MB.)  The files this function delivers are about ~500MB.  It also has no trouble reading and processing all the files upto and not including the 81st, so I don't think that it's running out of memory reading the file, but running out of memory doing something else and it's at the 81st where memory runs out.

The newFileContents() list should be getting emptied by overwriting it with a new list, right?  That shouldn't be growing with every iteration in this function.  GC.Collect() was sort of a last ditch effort.

The original file that the 369 splits come from has been a headache for a few days now, causing UltraEdit to crash, SSIS to crash, C# to crash, etc.  Splitting it via 7zip seemed to be the only option that worked, and splitting it to 369 files seemed to be the only option 7zip had that didn't also reformat or somehow compress the file in an undesirable way.

Is there something that I'm missing?  Something in my code that keeps growing in memory?  I know File.ReadAllLines() opens and closes the file, so it should be disposed after called, right?  newFileContents() gets overwritten every 50th file, as does the string builder.  What else could I be doing?

答:
One thing that jumps out at me is that you are opening a FileStream, never using it, and never disposing of it. With 300+ file streams this may be contributing to your issue.

```<code>var fs = File.OpenRead(file);
</code>```

Another thing that perked my ear is that you said 3.6GB. Make sure you are compiling for 64 bit architecture.

Finally, stuffing gigabytes into a string builder may cause you grief. Maybe create a staging file - which every time you open a new input file, you write that to the staging file, close the input, and not depend on stuffing everything into memory.

Body:
I have 369 files that need to be formatted and consolidated into 5-8 files before being submitted to the server.  I can't submit the 369 files because that would overwhelm the metadata tables in our database (they can handle it, but it'd be 369 rows for what was essentially one file, which would make querying and utilizing those tables a nightmare) and I can't handle it as one file because the total of 3.6 GB is too much for SSIS to handle on our servers.

I wrote the following script to fix the issue:

        static void PrepPAIDCLAIMSFiles()
        {
            const string HEADER = "some long header text, trimmed for SO question";
            const string FOOTER = "some long footer text, trimmed for SO question";
            //path is defined as a static member of the containing class
            string[] files = Directory.GetFiles(path + @"split\");
            int splitFileCount = 0, finalFileCount = 0;
            List<string> newFileContents = new List<string>();
            foreach(string file in files)
            {
                try
                {
                    var contents = File.ReadAllLines(file).ToList();
                    var fs = File.OpenRead(file);
                    if (splitFileCount == 0)
                    {
                        //Grab everything except the header
                        contents = contents.GetRange(1, contents.Count - 1);
                    }
                    else if (splitFileCount == files.Length - 1)
                    {
                        //Grab everything except the footer
                        contents = contents.GetRange(0, contents.Count - 1);
                    }
                    if (!Directory.Exists(path + @"split\formatted"))
                    {
                        Directory.CreateDirectory(path + @"split\formatted");
                    }
                    newFileContents.AddRange(contents);
                    if (splitFileCount % 50 == 0 || splitFileCount >= files.Length)
                    {
                        Console.WriteLine($"{splitFileCount} {finalFileCount}");
                        var sb = new StringBuilder(HEADER);
                        foreach (var row in newFileContents)
                        {
                            sb.Append(row);
                        }
                        sb.Append(FOOTER);
                        newFileContents = new List<string>();
                        GC.Collect();
                        string fileName = file.Split('\\').Last();
                        string baseFileName = fileName.Split('.')[0];
                        DateTime currentTime = DateTime.Now;
                        baseFileName += "." + COMPANY_NAME_SetHHMMSS(currentTime, finalFileCount) + ".TXT";
                        File.WriteAllText(path + @"split\formatted\" + baseFileName, sb.ToString());
                        finalFileCount += 1;
                    }
                    splitFileCount += 1;
                }
                catch(OutOfMemoryException OOM)
                {
                    Console.WriteLine(file);
                    Console.WriteLine(OOM.Message);
                    break;
                }
            }
        }

The way this works is it reads the split file, puts its rows into a string builder, every time it gets to a multiple of 50 files, it writes the string builder to a new file and starts over.  The COMPANY_NAME_SetHHMMSS() method ensures the file has a unique name, so it's not writing to the same file over and over (and I can verify this by seeing the output, it writes two files before exploding.)

It breaks when it gets to the 81st file.  System.OutOfMemoryException on var contents = File.ReadAllLines(file).ToList();.  There's nothing special about the 81st file, it's the same exact size as all the others (~10MB.)  The files this function delivers are about ~500MB.  It also has no trouble reading and processing all the files upto and not including the 81st, so I don't think that it's running out of memory reading the file, but running out of memory doing something else and it's at the 81st where memory runs out.

The newFileContents() list should be getting emptied by overwriting it with a new list, right?  That shouldn't be growing with every iteration in this function.  GC.Collect() was sort of a last ditch effort.

The original file that the 369 splits come from has been a headache for a few days now, causing UltraEdit to crash, SSIS to crash, C# to crash, etc.  Splitting it via 7zip seemed to be the only option that worked, and splitting it to 369 files seemed to be the only option 7zip had that didn't also reformat or somehow compress the file in an undesirable way.

Is there something that I'm missing?  Something in my code that keeps growing in memory?  I know File.ReadAllLines() opens and closes the file, so it should be disposed after called, right?  newFileContents() gets overwritten every 50th file, as does the string builder.  What else could I be doing?

Body:
One thing that jumps out at me is that you are opening a FileStream, never using it, and never disposing of it. With 300+ file streams this may be contributing to your issue.

var fs = File.OpenRead(file);

Another thing that perked my ear is that you said 3.6GB. Make sure you are compiling for 64 bit architecture.

Finally, stuffing gigabytes into a string builder may cause you grief. Maybe create a staging file - which every time you open a new input file, you write that to the staging file, close the input, and not depend on stuffing everything into memory.


问:
My first Lisp macro; is it leaky?
I've been working through Practical Common Lisp and as an exercise decided to write a macro to determine if a number is a multiple of another number:

(defmacro multp (value factor)

   `(= (rem ,value ,factor)  0))

so that :
(multp 40 10)
evaluates to true whilst
(multp 40 13)
does not

The question is does this macro leak in some way?  Also is this "good" Lisp?  Is there already an existing function/macro that I could have used?

答: Your macro looks fine to me. I don't know what a leaky macro is, but yours is pretty straightforward and doesn't require any gensyms. As far as if this is "good" Lisp, my rule of thumb is to use a macro only when a function won't do, and in this case a function can be used in place of your macro. However, if this solution works for you there's no reason not to use it.</p>

OwnerDisplayName: Tom Martin

Title: My first Lisp macro; is it leaky?

OwnerDisplayName: Kyle


问:
Server.UrlEncode vs. HttpUtility.UrlEncode
Is there a difference between Server.UrlEncode and HttpUtility.UrlEncode?</p>

答:
Server.UrlEncode() is there to provide backward compatibility with Classic ASP,

```<code>Server.UrlEncode(str);
</code>```

Is equivalent to:

```<code>HttpUtility.UrlEncode(str, Response.ContentEncoding);
</code>```

OwnerDisplayName: Manu

Body:
Server.UrlEncode() is there to provide backward compatibility with Classic ASP,

Server.UrlEncode(str);

Is equivalent to:

HttpUtility.UrlEncode(str, Response.ContentEncoding);

OwnerDisplayName: CMS


问:
Why does using an arrow function give the updated version of the state in React in comparison to calling the function normally?
Take the following react code

```<code>class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

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

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?

答:
Because the second one argument for this.setState()  is callback that is called when state is updated.
console.log() doesn't return function, it's called at the same time when you call this.setState()</p>

Body:
Take the following react code

class Foo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {state1: true, state2: false, state3: "hello"}
        this.onClick = this.onClick.bind(this)

    }

    onClick() {
        this.setState({state1: false, state2: true, state3: "goodbye"}, console.log(this.state))
    }

    render() {
        return(
            <button onClick = {this.onClick}></button>
        )
    }
}

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

When I use console.log in the callback for setState, I have to click the button twice in React in order for the console to display the correct version of state.

However, if write this.setState({state1: false, state2: true, state3: "goodbye"}, () => console.log(this.state)) instead, adding an arrow function, clicking the button once outputs the correct version of the state in the console. Why is that? Why does an arrow function output different behaviour in this scenario?


问:
What is the best practice to "re-render" a Component in React?
I have an array of items mapped, and when I delete an item, it deletes in the database, and if I manually refresh the page it is gone. However, I want to "re-render" the list of items, once I click the delete button. From what I can find, is I need a state change to "re-render", so I tried setting up a boolean, but It doesn't "re-render". Any suggestions on best practice to achieve this result would be helpful.</p>

```<code>class Profile extends Component {
  state = {
    username: '',
    movies: [],
    reRender: false    <---- by changing this state, I want a re-render of the component
  }

  getUserMovies = () => {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);

    axios.post('/getusermovies', {
      user: decoded.username
    }).then(response => {
      this.setState({
        username: decoded.username,
        // movieName: response.data.moviename
        movies: response.data
      })
      console.log(response.data)
    }).catch(error => {
      console.log(error + "err in the front end getusermovies function")
    })
  }

  componentDidMount() {
    this.getUserMovies();
  }

  deleteMovie = (itemId) => {
    axios.post('/delete', {
      movie: itemId
    }).catch(err => {
      console.log(err + "in the deleteMovie function in front end" + itemId)
    })

    this.setState(prevState => ({
      reRender: !prevState.reRender  <------ This is where I am calling a state.
    }))
  }

  render() {
    let movies = this.state.movies;
    return (
      <div className="container">
        <h1>{this.state.username}'s Movies: </h1>
        <div className="row">
          {movies.map(item =>
            <div className="profile-movies-box" >
              <img src={item.movie} alt='no image' className="movies-box-img" />
              <h4>{item.moviename}</h4>

              <button className="movie-buttons">
                <Link to={{
                  pathname: `/movie?movieName=${item.moviename}`,
                  state: { link: item.moviename }
                }}>View Movie</Link>
              </button>

              <button
                className="movie-btn"
                value={item.moviename}
                onClick={() => { this.deleteMovie(item.moviename) }}
              >Delete Movie</button>
            </div>
          )}
        </div>
      </div>
    );
  }
}

export default Profile;
</code>```

答:
You need to update movies array, remove item that has been deleted

deleteMovie = (itemId) => {

    axios.post('/delete', {
        movie: itemId
    })
    .then(res => {
      this.setState(prevState => ({
         movies: prevState.movies.filter(m => m.id !== itemId)
      }));
    })
   .catch(err => {
        console.log(err + "in the delteMovie function in front end" + itemId)
    })
 }```
</div>
</div>
</p>

<p>I would recommend using async await </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>deleteMovie = async (itemId) => {
  try {
   await axios.post('/delete', {
      movie: itemId
   });
   this.setState(prevState => ({
       movies: prevState.movies.filter(m => m.id !== itemId)
    }));
  } catch (err) {
    console.log(err + "in the delteMovie function in front end" + itemId)
  }
 }</code>```

Body:
I have an array of items mapped, and when I delete an item, it deletes in the database, and if I manually refresh the page it is gone. However, I want to "re-render" the list of items, once I click the delete button. From what I can find, is I need a state change to "re-render", so I tried setting up a boolean, but It doesn't "re-render". Any suggestions on best practice to achieve this result would be helpful.

class Profile extends Component {
  state = {
    username: '',
    movies: [],
    reRender: false    <---- by changing this state, I want a re-render of the component
  }

  getUserMovies = () => {
    const token = localStorage.usertoken;
    const decoded = jwt_decode(token);

    axios.post('/getusermovies', {
      user: decoded.username
    }).then(response => {
      this.setState({
        username: decoded.username,
        // movieName: response.data.moviename
        movies: response.data
      })
      console.log(response.data)
    }).catch(error => {
      console.log(error + "err in the front end getusermovies function")
    })
  }

  componentDidMount() {
    this.getUserMovies();
  }

  deleteMovie = (itemId) => {
    axios.post('/delete', {
      movie: itemId
    }).catch(err => {
      console.log(err + "in the deleteMovie function in front end" + itemId)
    })

    this.setState(prevState => ({
      reRender: !prevState.reRender  <------ This is where I am calling a state.
    }))
  }

  render() {
    let movies = this.state.movies;
    return (

{this.state.username}'s Movies:

          {movies.map(item =>

{item.moviename}

              <button className="movie-buttons">
                <Link to={{
                  pathname: `/movie?movieName=${item.moviename}`,
                  state: { link: item.moviename }
                }}>View Movie</Link>
              </button>

              <button
                className="movie-btn"
                value={item.moviename}
                onClick={() => { this.deleteMovie(item.moviename) }}
              >Delete Movie</button>

          )}

    );
  }
}

export default Profile;

Body:
You need to update movies array, remove item that has been deleted

deleteMovie = (itemId) => {

    axios.post('/delete', {
        movie: itemId
    })
    .then(res => {
      this.setState(prevState => ({
         movies: prevState.movies.filter(m => m.id !== itemId)
      }));
    })
   .catch(err => {
        console.log(err + "in the delteMovie function in front end" + itemId)
    })
 }

I would recommend using async await

deleteMovie = async (itemId) => {
  try {
   await axios.post('/delete', {
      movie: itemId
   });
   this.setState(prevState => ({
       movies: prevState.movies.filter(m => m.id !== itemId)
    }));
  } catch (err) {
    console.log(err + "in the delteMovie function in front end" + itemId)
  }
 }


问:
Angular 8 Routing + Navigation: Locking a Component
I have built a Authentication system in Angular and was wondering how to lock a route that I have built. In order to get to the "members" route, you need to have an user account. How would you block getting to this route as you could just type the route into URL. I want to prevent this as you need to be a user of the system before being able to route to this page.

Please let me know if you need any chunks of code,
thanks.

答: Route Guards is what you want. You define a guard function and then set what routes are governed by it in configuration. Works well.</p>


问:
How to make multiple route::put in one controller (Laravel 6)
I want to make two Route::put for my controller, but Im having errors when I do this.
I'm having an error like this:

Facade\Ignition\Exceptions\ViewException
  Route [home.callqueue] not defined. (View:
  C:\xampp\htdocs\dqrs\resources\views\dashboard.blade.php)

This is my Controller

```<code>    public function updatenotif(Request $request)
    {
        $request->validate([
            'text'=>['max:255']

        ]);

        DB::table('notifications')->where('id', '1')->update(['text'=>$request->text]);

        return redirect('admin')->withStatus(__('Notification message updated successfully.'));

    }

    public function callqueue(Request $request)
    {
        $request->validate([
            'called'=>['max:255']

        ]);

        $dept=Auth::user()->department;
        Queue::where('department',$dept)
                       ->whereDate('created_at', Carbon::today())
                       ->orderBy('id', 'desc')
                       ->first()
                       ->update(['called'=>$request->called]);

                       return redirect('admin')->withStatus(__('Queue has been called.'));
    }
</code>```

This is my web routes

```<code>  Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
  Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);
</code>```

答: Because return redirect('admin') is method get. </p>

Body:
I want to make two Route::put for my controller, but Im having errors when I do this.
I'm having an error like this:

Facade\Ignition\Exceptions\ViewException
  Route [home.callqueue] not defined. (View:
  C:\xampp\htdocs\dqrs\resources\views\dashboard.blade.php)

This is my Controller

    public function updatenotif(Request $request)
    {
        $request->validate([
            'text'=>['max:255']

        ]);

        DB::table('notifications')->where('id', '1')->update(['text'=>$request->text]);

        return redirect('admin')->withStatus(__('Notification message updated successfully.'));

    }

    public function callqueue(Request $request)
    {
        $request->validate([
            'called'=>['max:255']

        ]);

        $dept=Auth::user()->department;
        Queue::where('department',$dept)
                       ->whereDate('created_at', Carbon::today())
                       ->orderBy('id', 'desc')
                       ->first()
                       ->update(['called'=>$request->called]);

                       return redirect('admin')->withStatus(__('Queue has been called.'));
    }

This is my web routes

  Route::put('admin',['as'=>'home.callqueue','uses'=>'HomeController@callqueue']);
  Route::put('admin',['as'=>'home.updatenotif','uses'=>'HomeController@updatenotif']);


问:
print file content as quoted comma separated single line
How to print a file content as quoted and comma separated single line.

```<code>$cat test
file1.gz
file2.gz
file3.gz
file4.gz
</code>```

I want to print as 'file1.gz','file2.gz','file3.gz','file4.gz'

答:
```<code>$ awk '{printf "%s\047%s\047", sep, $0; sep=","} END{print ""}' file
'file1.gz','file2.gz','file3.gz','file4.gz'
</code>```

or equivalent functionality but storing the whole input file in memory:

```<code>$ awk '{out=out sep "\047" $0 "\047"; sep=","} END{print out}' file
'file1.gz','file2.gz','file3.gz','file4.gz'
</code>```

and abbreviated for the golfers :-):

```<code>$ awk -v q="'" '{o=o s q $0 q; s=","} END{print o}' file
'file1.gz','file2.gz','file3.gz','file4.gz'
</code>```

Personally, I'd use the first script above unless you have some specific need to build up the whole output record before printing it, e.g. to modify it in some way based on a multi-line regexp.

Body:
How to print a file content as quoted and comma separated single line.

$cat test
file1.gz
file2.gz
file3.gz
file4.gz

I want to print as 'file1.gz','file2.gz','file3.gz','file4.gz'

Body:
$ awk '{printf "%s\047%s\047", sep, $0; sep=","} END{print ""}' file
'file1.gz','file2.gz','file3.gz','file4.gz'

or equivalent functionality but storing the whole input file in memory:

$ awk '{out=out sep "\047" $0 "\047"; sep=","} END{print out}' file
'file1.gz','file2.gz','file3.gz','file4.gz'

and abbreviated for the golfers :-):

$ awk -v q="'" '{o=o s q $0 q; s=","} END{print o}' file
'file1.gz','file2.gz','file3.gz','file4.gz'

Personally, I'd use the first script above unless you have some specific need to build up the whole output record before printing it, e.g. to modify it in some way based on a multi-line regexp.


问:
XML parsing with Python and regex does not return all results
I am still struggling with regexp:

```<code>import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''

pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>'

print(re.findall(pattern, text, re.S))
</code>```

This returns:

```<code>[('abc', '8')]
</code>```

I would expect it to return:

```<code>[('abc', '4'), ('def', '8')]
</code>```

Why is it so greedy and matches everything until the last closing tag?

This is the regex101 link: https://regex101.com/r/ANO7RA/1

Maybe negative lookahead will solve this. I was not able to fully grasp the concept, though... :-(

答:
I seem to have found an answer myself:

```<code>pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>\s*<CATEGORY>[^<]*</CATEGORY>\s*<SW-ARRAYSIZE>\s*<VF>(.*)</VF>\s*</SW-ARRAYSIZE>'

print(re.findall(pattern, text))
</code>```

You really have to limit the usage of .* and make use of the very predictable structure of the XML.

Body:
I am still struggling with regexp:

import re

text = '''
          <SW-VARIABLE>
            <SHORT-NAME>abc</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>4</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
              cde
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>

          <SW-VARIABLE>
            <SHORT-NAME>def</SHORT-NAME>
            <CATEGORY>VALUE</CATEGORY>
            <SW-ARRAYSIZE>
              <VF>8</VF>
            </SW-ARRAYSIZE>
            <SW-DATA-DEF-PROPS>
                <HELLO>dsfadsf </HELLO>
                <NO>itis</NO>
            </SW-DATA-DEF-PROPS>
          </SW-VARIABLE>
'''

pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>'

print(re.findall(pattern, text, re.S))

This returns:

[('abc', '8')]

I would expect it to return:

[('abc', '4'), ('def', '8')]

Why is it so greedy and matches everything until the last closing tag?

This is the regex101 link: https://regex101.com/r/ANO7RA/1

Maybe negative lookahead will solve this. I was not able to fully grasp the concept, though... :-(

Body:
I seem to have found an answer myself:

pattern = r'<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>\s*<CATEGORY>[^<]*</CATEGORY>\s*<SW-ARRAYSIZE>\s*<VF>(.*)</VF>\s*</SW-ARRAYSIZE>'

print(re.findall(pattern, text))

You really have to limit the usage of .* and make use of the very predictable structure of the XML.


问:
How to write shell script for finding number of pages in PDF?
I am generating a PDF dynamically. How can I check the number of pages in the PDF using a shell script?</p>

答:
I made a few improvement in Marius Hofert tip to sum the returned values.</p>

```<code>for f in *.pdf; do pdfinfo "$f" | grep Pages | awk '{print $2}'; done | awk '{s+=$1}END{print s}'
</code>```

Body:
I made a few improvement in Marius Hofert tip to sum the returned values.

for f in *.pdf; do pdfinfo "$f" | grep Pages | awk '{print $2}'; done | awk '{s+=$1}END{print s}'


问:
Should I use Static class for Database connectivity in C#.net?
I have a class which contain all the database connection activities. What i want to know is should i make this class as static then i can call anywhere without creating it.
but the application runs in different pcs in same network in same time.

OR ELSE

should i create a normal class that can be use in other classes by inheriting it?

答:
I would not go for a static class.  It may declutter but there are always pros and cons.  I would also stay away from inheriting some base class.  As the GoF said: favour composition over inheritance.

So a factory would come in handy here:

```<code>    private IDatabaseConnectionFactory databaseConnectionFactory;

    public SomeClass() : this(new DatabaseConnectionFactory()) { }
    public SomeClass(IDatabaseConnectionFactory factory)
    {
        databaseConnectionFactory = factory;
    }

    .
    .
    using (var connection = DatabaseConnectionFactory.Create()) { ... }
    .
    .
</code>```

Where DatabaseConnectionFactory is injected or passed in.

HTH

Body:
I would not go for a static class.  It may declutter but there are always pros and cons.  I would also stay away from inheriting some base class.  As the GoF said: favour composition over inheritance.

So a factory would come in handy here:

    private IDatabaseConnectionFactory databaseConnectionFactory;

    public SomeClass() : this(new DatabaseConnectionFactory()) { }
    public SomeClass(IDatabaseConnectionFactory factory)
    {
        databaseConnectionFactory = factory;
    }

    .
    .
    using (var connection = DatabaseConnectionFactory.Create()) { ... }
    .
    .

Where DatabaseConnectionFactory is injected or passed in.

HTH


问:
Returning a class in Kotlin
```<code>class Wolf {
    var hunger = 10
    val food = "meat"

    fun eat() {
        println("The Wolf is eating $food")
    }
}

class MyWolf {
    var wolf: Wolf? = Wolf()

    fun myFunction() {
        wolf?.eat()
    }
}

fun getAlphaWolf(): Wolf? {
    return Wolf()
}

fun main(args: Array<String>) {
    var w: Wolf? = Wolf()

    if (w != null) {
        w.eat()
    }

    var x = w?.hunger
    println("The value of x is $x")

    var y = w?.hunger ?: -1
    println("The value of y is $y")

    var myWolf = MyWolf()
    myWolf?.wolf?.hunger = 8
    println("The value of myWolf?.wolf?.hunger is ${myWolf?.wolf?.hunger}")

    var myArray = arrayOf("Hi", "Hello", null)
    for (item in myArray) {
        item?.let { println(it) }
    }

    getAlphaWolf()?.let { it.eat() }

    w = null
    var z = w!!.hunger
}
</code>```

This above code is extracted from a Kotlin textbook.
I have problem with the following:

```<code>fun getAlphaWolf(): Wolf? {
     return Wolf()
}
</code>```

As there is only a class called Wolf but no variable called Wolf in the code.
I wonder if it is possible to return a class inside a function?
What is the output if a class is returned inside a function?

答:
If you are familiar with Java, then this Kotlin is equivalent to:

public class Application {
    public Wolf getAlphaWolf() {
        return new Wolf();
    }
}
```

<p>So, in Kotlin you are calling the no-arguments constructor. If you want to return the class <code>Wolf</code>, then that is also possible:</p>

```fun getWolfClass(): KClass<Wolf> {
    return Wolf::class
}
```

Title: Returning a class in Kotlin

Body:
class Wolf {
    var hunger = 10
    val food = "meat"

    fun eat() {
        println("The Wolf is eating $food")
    }
}

class MyWolf {
    var wolf: Wolf? = Wolf()

    fun myFunction() {
        wolf?.eat()
    }
}

fun getAlphaWolf(): Wolf? {
    return Wolf()
}

fun main(args: Array<String>) {
    var w: Wolf? = Wolf()

    if (w != null) {
        w.eat()
    }

    var x = w?.hunger
    println("The value of x is $x")

    var y = w?.hunger ?: -1
    println("The value of y is $y")

    var myWolf = MyWolf()
    myWolf?.wolf?.hunger = 8
    println("The value of myWolf?.wolf?.hunger is ${myWolf?.wolf?.hunger}")

    var myArray = arrayOf("Hi", "Hello", null)
    for (item in myArray) {
        item?.let { println(it) }
    }

    getAlphaWolf()?.let { it.eat() }

    w = null
    var z = w!!.hunger
}

This above code is extracted from a Kotlin textbook.
I have problem with the following:

fun getAlphaWolf(): Wolf? {
     return Wolf()
}

As there is only a class called Wolf but no variable called Wolf in the code.
I wonder if it is possible to return a class inside a function?
What is the output if a class is returned inside a function?

Body:
If you are familiar with Java, then this Kotlin is equivalent to:

public class Application {
    public Wolf getAlphaWolf() {
        return new Wolf();
    }
}

So, in Kotlin you are calling the no-arguments constructor. If you want to return the class Wolf, then that is also possible:

fun getWolfClass(): KClass<Wolf> {
    return Wolf::class
}


答:
I agree with others, it is best to use an xml parser here. But to fix what you have ...

You are missing a question mark. regexes are greedy by default. They grab as much as they can. To make them non-greedy, you need to add a question mark after the part that you want to be none-greedy for. This regex will give you what you want:

```<code><SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>
</code>```

you had the question mark correctly after

</SW-ARRAYSIZE>.*

but you were missing it after

</SHORT-NAME>.*

.

I think you want to only capture the content of the two '.*?'s. If that is the case, I would put them in groups and retrieve the groups in code to work with them.
The regex will then become:

```<code><SW-VARIABLE>\s*<SHORT-NAME>(?P<sn>[^<]*?)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>(?P<vf>[^<]*?)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>
</code>```

with the two group names being sn and vf. demo

Your python code for retrieving the named groups will then become:

```<code>matches= re.search(regex, string1)
print("shortName: ", matches.group('sn'))
print("vf: ", matches.group('vf'))
</code>```

Title: XML parsing with Python and regex does not return all results

Body:
I agree with others, it is best to use an xml parser here. But to fix what you have ...

You are missing a question mark. regexes are greedy by default. They grab as much as they can. To make them non-greedy, you need to add a question mark after the part that you want to be none-greedy for. This regex will give you what you want:

<SW-VARIABLE>\s*<SHORT-NAME>([^<]*)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>([^<]*)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>

you had the question mark correctly after

</SW-ARRAYSIZE>.*

but you were missing it after

</SHORT-NAME>.*

.

I think you want to only capture the content of the two '.*?'s. If that is the case, I would put them in groups and retrieve the groups in code to work with them.
The regex will then become:

<SW-VARIABLE>\s*<SHORT-NAME>(?P<sn>[^<]*?)</SHORT-NAME>.*?<SW-ARRAYSIZE>\s*<VF>(?P<vf>[^<]*?)</VF>\s*</SW-ARRAYSIZE>.*?<(?:/(?!<SW-VARIABLE>)[^/]*?)SW-VARIABLE>

with the two group names being sn and vf. demo

Your python code for retrieving the named groups will then become:

matches= re.search(regex, string1)
print("shortName: ", matches.group('sn'))
print("vf: ", matches.group('vf'))


问:
How to select value inside array
This the code in the var named available_dates

var available_dates = ["08-11-2018","09-11-2018"]

I wonder how can I choose the second date of the var and selected, to my second code

document.getElementById('app_date').value = available_dates

答:
U must indicate which position of the array u want:

document.getElementById('app_date').value = available_dates[1]

Be happy!!

Title: How to select value inside array


问:
ASP.NET: NuGet/NuPack: Configuring location package files are put in
Okay, so help me understand something here. I've got a new MVC solution and want to use NuGet to keep Modernizr up to date.

The problem is, NuGet puts the Modernizr scripts under ~/Scripts. This won't work--we've decided to put our JS in ~/js.

How do I modify the configuration of this package to tell NuGet that the Modernizr package should go in ~/Scripts or ~/Scripts/global instead?

答: I don't think you can do this - I don't think this is functionality of NuGet, but rather the location of the scripts inside the NuGet package. This could vary from one package to another :-(</p>


问:
How do I reduce a list in a Magnolia JavaScript model?
I'm attempting to reduce a FreeMarker list in a Magnolia JavaScript model. I want all items that start with a capital "P".

```<code>[#assign list = ["Poker", "Pet", "Dog", "Cat", "Penguin", "Paddle", "punk"]]
</code>```

My function should return:

```<code>["Poker", "Pet", "Penguin", "Paddle"]
</code>```

Attempts

I attempted to use Array.prototype.reduce().

var Model = function() {
  this.reduceList = function(list) {
    return list.reduce(function(reducedList, item) {
      if (item.indexOf('P') !== -1) {
        reducedList.push(item);
      }
      return reducedList;
    }, []);
  }
};

new Model();
```

```[#assign filteredList = model.reduceList(['Poker', 'Pet', 'Dog', 'Cat', 'Penguin', 'Paddle', 'punk'])]
```

<p>However, I get the following error.</p>

```jdk.nashorn.internal.runtime.ECMAException: TypeError: list.reduce is not a function
```

<p><strong>Note:</strong> Magnolia JavaScript models are built on Nashorn.</p>

<h2>Debugging</h2>

<p>When I return the type of the list:</p>

<pre class="lang-js prettyprint-override"><code>this.reduceList = function(list) {
  return typeof list;
}
</code>```

I get an object:

```<code>object
</code>```

When I return the list as a string:

this.reduceList = function(list) {
  return list.toString();
};
```

<p>I get a list:</p>

```[Poker, Pet, Dog, Cat, Penguin, Paddle, punk]
```

How do I reduce a list in a Magnolia JavaScript model?

答:
Use the filter() method. Here is a code sample:

var Model = function() {
  this.reduceList = function(list) {
    return Java.from(list).filter(function(item) {
      return item[0] === 'P'
    });
  }
};
```

Body:
I'm attempting to reduce a FreeMarker list in a Magnolia JavaScript model. I want all items that start with a capital "P".

[#assign list = ["Poker", "Pet", "Dog", "Cat", "Penguin", "Paddle", "punk"]]

My function should return:

["Poker", "Pet", "Penguin", "Paddle"]

Attempts

I attempted to use Array.prototype.reduce().

var Model = function() {
  this.reduceList = function(list) {
    return list.reduce(function(reducedList, item) {
      if (item.indexOf('P') !== -1) {
        reducedList.push(item);
      }
      return reducedList;
    }, []);
  }
};

new Model();

[#assign filteredList = model.reduceList(['Poker', 'Pet', 'Dog', 'Cat', 'Penguin', 'Paddle', 'punk'])]

However, I get the following error.

jdk.nashorn.internal.runtime.ECMAException: TypeError: list.reduce is not a function

Note: Magnolia JavaScript models are built on Nashorn.

Debugging

When I return the type of the list:

this.reduceList = function(list) {
  return typeof list;
}

I get an object:

object

When I return the list as a string:

this.reduceList = function(list) {
  return list.toString();
};

I get a list:

[Poker, Pet, Dog, Cat, Penguin, Paddle, punk]

How do I reduce a list in a Magnolia JavaScript model?