text:
Q: Separate joined words in a string using python "10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goods referred to HGI QLD for further action.Attachments:Nil34FEB2004"

What I want to do is to read this string in python and separate the joined words. What I exactly want is a regular expression to separate the joined words in the string.
I want to read the above string from a file and the output should be as follows:
"10 JAN 2015 AirMail standard envelope from Hyderabad Address details : John Cena Palm Drive Adelaide. Also calculated: Nil Action Taken: Goods referred to USG for further action. Attachments : Nil 60 FEB 2004."

(Separate the joined words)
I need to write a regular expression to separate:
'10Jan2015AirMail', 'HyderabadAddress', 'details:John', 'DriveAdelaide'
Need a regular expression to identify joined words like above and separate them with a space in the same string like
'10 Jan 2015 AirMail, 'Hyderabad Address', 'details : John'
text = open('C:\sample.txt', 'r').read().replace("\n","").replace("\t","").replace("-","").replace("/"," ")

newtext = re.sub('[a-zA-Z0-9_:]','',text) #This regex does not work.Please assist

print text
print newtext

The above code does not work

A: I know that this solution can be done pretty much simpler classifying chars in sets (upper, lower, numeric) but I preferred to do a much more verbose solution:
test_text = "10JAN2015AirMail standard envelope from HyderabadAddress details:John Cena Palm DriveAdelaide.Also Contained:NilAction Taken:Goods referred to HGI QLD for further action.Attachments:Nil34FEB2004"
splitted_text = test_text.split(' ')
num = False
low = False
upp = False
result = []

for word in ss:
  new_word = ''
  if not word.isupper() and not word.islower():
    if word[0].isnumeric():
        num = True
        low = False
        upp = False
    elif word[0].islower():
        num = False
        low = True
        upp = False
    elif word[0].isupper():
        num = False
        low = False
        upp = True
    for letter in word:
      if letter.isnumeric():
        if num:
            new_word += letter
        else:
            new_word += ' ' + letter
        low = False
        upp = False
        num = True
      elif letter.islower():
        if low or upp:
            new_word += letter
        else:
            new_word += ' ' + letter
        low = True
        upp = False
        num = False
      elif letter.isupper():
        if low or num:
            new_word += ' ' + letter
        else:
            new_word += letter
        low = False
        upp = True
        num = False
      else:
        new_word += ' ' + letter
    result.append(''.join(new_word))
  else:
    result.append(word)
' '.join(result)
#'10 JAN 2015 Air Mail standard envelope from Hyderabad Address details : John Cena Palm Drive Adelaide . Also Contained : Nil Action Taken : Goods referred to HGI QLD for further action . Attachments : Nil 34 FEB 2004'

Sometimes one just need to be pointed int he right direction.


text:
Q: create and copy individual subroutines to separate files from a file having n sub routine definitions I have a file which contains n number of sub routine definitions like following (every routine starts with sub and ends with a keyword bar):
sub foo()
contents
bar

sub good ()
contents
bar

sub right ()
contents
bar

I want to create three files called foo.s, good.s and right.s and write the respective subroutines into corresponding files. I tried the following script but got into improper management of global/local variables as I am completely new to Perl scripting. How can I achieve this?
      my $op = 0;

      my $fnamet = $ARGV[0];
      if(not defined $fnamet) {
              die "Top file name not known\n";
      }
      my $srcfile = "source/$fnamet.s";
      print "$srcfile\n";
      open (SRC, $srcfile) or die "Couldn't find source file\n";

      foreach $line (<SRC>) {
              if ($op == 0) {
                      strtwrite($line, $op);
              } elsif ($op == 1) {
                      stopwrite($line, $op);
              }
      }
      if ($op == 1) {
              print "Some sub is missing bar statement or having\n";
              print "additional sub statement";
              close (DST);
      }
      close (SRC);
  }

  sub strtwrite {
      unless ($_[0] =~ /^\s*sub\s*.*/) {
              print "Searching for a sub start\n";
              $op = 0;
      } else {
              print "A sub start found\n";
              print "$_[0]\n";
              my @temp = (split /[\s,();]+/, $_[0]);
              my $strt = '';
              if($temp[1] =~ 'sub') {
                      print "Comparing with sub pass \n";
                      $strt = $temp[2];
              } else {
                      print "Comparing with sub fail \n";
                      $strt = $temp[1];
              }
              my $fnameb = "dstcodes/$strt.s";
             print "\n\n $fnameb \n\n";
              open (DST, '>$fnameb') or die "Couldn't open sub file\n";
              print DST $_[0];
              $op = 1;
      }
  }

  sub stopwrite {
      unless ($_[0] =~ /^\s*bar\s*.*/) {
              # Copy till the bar is found
              print "Searching for an bar\n";
              print DST $_[0];
              $op = 1;
      } else {
              # Close the current destination file and start waiting
              # for next SUB start
              print "A matching BAR found\n";
              print DST $_[0];
              close (DST);
              $op = 0;
      }
  }

A: This is relatively straightforward using a lexical variable for the output file handle (which it is best to do anyway).
This program simply opens an output file on $dst whenever a sub line is found in the input. Then the current input line is printed to $dst and everything just works.
A few hints:

*

*Always use strict and use warnings at the start of your program

*Declare your variables as close as possible to their first point of use, rather than all together at the top of the program

*Always use lexical file handles and the three-parameter form of open, and include the value of $! in the die string so that you know the reason for the failure

*If you don't put a newline on the end of your die string then Perl will display the file name and line number where the problem occurred

*Use while to read through a file, rather than for. The latter will unnecessarily read the entire file into memory before the loop starts, which will become a problem for large files

use strict;
use warnings;

die "Top file name not known" unless @ARGV;
my $srcfile = "source/$ARGV[0].s";

open my $src, $srcfile or die "Unable to open '$srcfile': $!";
my $dst;
while (<$src>) {
  if (/^\s*sub\s+(\w+)/) {
    my $file = "dstcodes/$1.s";
    open $dst, '>', $file or die "Unable to open '$file' for output: $!";
  }
  print $dst $_ if $dst;
}

close $dst if $dst;

A: You can try while loop with /g regex,
use strict;
use warnings;

my ($fnamet) = @ARGV;
open my $fh, "<", $fnamet or die $!;
my $str = do { local $/; <$fh> };
close $fh or die $!;

while ($str =~ /(sub \s+ (\w+) .+?) bar/xgs) {
  my ($cont, $name) = ($1, $2);

  open my $o, ">", "$name.s" or die $!;
  print $o $cont;
  close $o or die $!;
}

A: Well, first there is a quick fix to your problem: We pass a reference to the $op variable to the subs. Perl references are similar to C pointers. We can obtain a reference with the \ operator. We can dereference a ref like $$opref, that is the sigil $ doubles as dereference operator.
if ($op == 0) {
        strtwrite($line, \$op);
} elsif ($op == 1) {
        stopwrite($line, \$op);
}

and then in the subs, we unpack the arguments:
sub stopwrite {
  my ($line, $opref) = @_;

  ...
  $$opref = 1;
}

(There is the shorter solution of skipping the references and assigning to $_[1], but that isn't exactly readable).

But you see, I'm kind of objected to this technique because all of this is action-at-a-distance-ish and mutable state often makes simple things rather complicated.
Let's assume we have a subroutine extract_sub that skips any junk lines until it finds a sub declaration, extracts the sub to a file, and returns once the sub is terminated by the bar marker. To do this, extract_sub takes a file handle as argument. So our main part looks like:
use strict; use warnings;
use autodie;  # automatic error messages for `open`

@ARGV or die "Usage: $0 input-file\n";
my $filename = shift @ARGV;

# using "lexical filehandes" and an explicit open mode "<":
open my $source, "<", $filename;

extract_subs($source) until eof $source;

# $source is closed automatically

Now, what happens in extract_subs? First, we unpack the arguments into variables, which is easier to read:
sub extract_subs {
  my ($input) = @_;

Next, we start discarding lines until we see a sub:
  my $output;
  while (my $declaration = <$input>) {
    if ($declaration =~ /^\s* sub \s+ (\w+)/x) {
      my $name = $1;
      open $output, ">", "dstcodes/$name.s";  # no error handling because autodie
      print { $output } $declaration;  # print the whole declaration to this file
      last;  # leave the loop
    }
  }
  # check that the loop didn't abort because $input was exhausted:
  return unless defined $output;

We opened the file inside that loop to be able to print $declaration right there.
Now that we have opened the output file and are inside the sub, we print all lines to the $output until we see the termination line:
# implicitly read into $_ default variable
while (<$input>) {
  print { $output } $_;
  return if /^\s*bar\b/;  # exit the whole subroutine, not just the loop
}
# If this code is reached, then $input was exhausted before finding the "bar" terminator
die "A sub was not terminated with a bar statement"

I think this code is more elegant and easier to understand. Here are a few things you shouldn't do:

*

*Ancient forms of open like bareword filehandles, or specifying no open mode. Always use the three-argument form: open my $filehandle, "<", $filename or die "Can't open $filename: $!" – the or die part can be omitted when using autodie.

*Using globals, like bareword filehandles. They make code buggy and harder to understand.

*Not using strict and warnings. All those error messages seem pesky, but they generally point to real problems which should be fixed rather than ignored.

*Using flags to specify the state of a parser. If you factor your code into appropriate subroutines with good return values, such communication channels are not needed. Remember that you can return multiple values from a Perl subroutine if necessary.

*Using =~ as a general string operator. It is used for regex matching. If you want to test for string equality, then use the eq operator.

*Testing for specific truth values. If you only care if a variable is true or false, then use it in a condition directly: if ($foo) { bar() } else { baz() }. This is more robust than requiring specific values, e.g. if ($foo == 1) { bar() } elsif ($foo = 0) { baz() }.

*Using the unless ($cond) { A } else { B } construction. This is often rather hard to understand. Either of if (not $cond) { A} else { B } or if ($cond) { B } else { A } is better.

*Not reading "Modern Perl". Once you feel comfortable with programming Perl, you should read that book (it's also available online) to learn current best practices.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What undefined behaviour does this C++ code contain I wrote up this code after reading item 11 of Effective C++ ( Third Edition ).
#include <iostream>
using namespace std;

#define MAX_COLORS 20
class Widget
{
 public:
    Widget ( int seed );
    ~Widget ( );
    Widget& operator=( const Widget& rhs );
    void ToString ( );
 private:

    Widget& SelfAssignmentUnsafe ( const Widget& rhs );
    Widget& SelfAssignmentSafe ( const Widget& rhs );
    Widget& SelfAssignmentAndExceptionSafe ( const Widget& rhs );
    void MakeDeepCopy ( const Widget& rhs );
    int *colorPallete;
};

void Widget::ToString()
{
 int i = 0;
 for ( i = 0; i < MAX_COLORS; i++ )
 {
 cout << "colorPallete[" << i << "]: " << colorPallete[i] << endl;
 }
}

Widget::Widget ( int seed ):
    colorPallete ( new int[MAX_COLORS])
    {
     int i = 0;
     for ( i = 0; i < MAX_COLORS; i++ )
     {
      colorPallete[i] = seed + i;
     }
    }

Widget& Widget::operator=( const Widget& rhs )
{
//    return SelfAssignmentUnsafe ( rhs );

//    return SelfAssignmentSafe( rhs );

    return SelfAssignmentAndExceptionSafe ( rhs );
}

Widget& Widget::SelfAssignmentUnsafe ( const Widget& rhs )
{
    delete[] colorPallete;
    colorPallete = 0;
    MakeDeepCopy( rhs );
    return *this;
}

Widget& Widget::SelfAssignmentSafe ( const Widget& rhs )
{
    if ( this == &rhs ) return *this;

    delete[] colorPallete;
    colorPallete = 0;
    MakeDeepCopy ( rhs );
    return *this;
}

void Widget::MakeDeepCopy ( const Widget& rhs )
{
    int i = 0;
    colorPallete = new int [MAX_COLORS];
    for ( i = 0;i < MAX_COLORS; i++ )
    {
     colorPallete[i] = rhs.colorPallete[i];
    }
}

Widget& Widget::SelfAssignmentAndExceptionSafe ( const Widget& rhs )
{
    int *origColorPallete = colorPallete;
    MakeDeepCopy ( rhs );
    delete[] origColorPallete;
    origColorPallete = 0;
    return *this;
}

Widget::~Widget()
{
 delete[] colorPallete;
}

int main()
{
 Widget b(10);
 Widget a(20);
 b.ToString();
 b = b;
 cout << endl << "After: " << endl;
 b.ToString();
}

The author talks about handling assignment to self in the assignment operator:
Widget a(10);
a = a;

From the assignment operator for Widget I call Widget::SelfAssignmentAndExceptionSafe.
In Widget::SelfAssignmentAndExceptionSafe the idea is to save the colorPallete pointer in origColorPallete. Then make a deep copy of rhs.colorPallete. When the copy succeeds I delete the original pointer and return reference to self.
The above mechanism is supposed to be self assignment and exception safe.
However, Widget::SelfAssignmentAndExceptionSafe is not able to handle assignment to self properly. The colorPallete array contains junk after self-assignment. Its handling the other cases very well.
Why could this be?
Please help.
[EDIT: After examining all the answers]
Thanks for your answers. I have updated the MakeDeepCopy method and the example's working fine now. Below, I have pasted the updated code:
#include <iostream>

using namespace std;

#define MAX_COLORS 20
class Widget
{
 public:
    Widget ( int seed );
    ~Widget ( );
    Widget& operator=( const Widget& rhs );
    void ToString ( );
 private:
    Widget( Widget& rhs );
    Widget& SelfAssignmentUnsafe ( const Widget& rhs );
    Widget& SelfAssignmentSafe ( const Widget& rhs );
    Widget& SelfAssignmentAndExceptionSafe ( const Widget& rhs );
    void MakeDeepCopy ( const int* rhs );
    int *colorPallete;
};

void Widget::ToString()
{
 int i = 0;
 for ( i = 0; i < MAX_COLORS; i++ )
 {
 cout << "colorPallete[" << i << "]: " << colorPallete[i] << endl;
 }
}

Widget::Widget ( int seed ):
    colorPallete ( new int[MAX_COLORS])
    {
     int i = 0;
     for ( i = 0; i < MAX_COLORS; i++ )
     {
      colorPallete[i] = seed + i;
     }
    }

Widget& Widget::operator=( const Widget& rhs )
{
//    return SelfAssignmentUnsafe ( rhs );

//    return SelfAssignmentSafe( rhs );

    return SelfAssignmentAndExceptionSafe ( rhs );
}

Widget& Widget::SelfAssignmentUnsafe ( const Widget& rhs )
{
    delete[] colorPallete;
    colorPallete = 0;
    MakeDeepCopy( rhs.colorPallete );
    return *this;
}

Widget& Widget::SelfAssignmentSafe ( const Widget& rhs )
{
    if ( this == &rhs ) return *this;

    delete[] colorPallete;
    colorPallete = 0;
    MakeDeepCopy ( rhs.colorPallete );
    return *this;
}

void Widget::MakeDeepCopy ( const int* rhs )
{
    int i = 0;
    colorPallete = new int [MAX_COLORS];
    for ( i = 0;i < MAX_COLORS; i++ )
    {
     colorPallete[i] = rhs[i];
    }
}

Widget& Widget::SelfAssignmentAndExceptionSafe ( const Widget& rhs )
{
    int *origColorPallete = colorPallete;
    MakeDeepCopy ( rhs.colorPallete );
    delete[] origColorPallete;
    origColorPallete = 0;
    return *this;
}

Widget::~Widget()
{
 delete[] colorPallete;
}

int main()
{
 Widget b(10);
 Widget a(20);
 b.ToString();
 b = b;
 cout << endl << "After: " << endl;
 b.ToString();
}

[EDIT: Modified code based on Charles's response ]
The idea is to implement "copy-and-swap" idiom to make code both self assignment and exception safe. Note that copy is implemented only in the copy constructor. If the copy succeeds we swap in the assignment operator.
Another improvement over the previous update is that MakeDeepCopy's interface depended on correct usage. We had to store/delete the colorPallete pointer before calling MakeDeepCopy. No such dependencies exist now.
#include <iostream>

using namespace std;

#define MAX_COLORS 20
class Widget
{
 public:
    Widget ( int seed );
    ~Widget ( );
    Widget& operator=( const Widget& rhs );
    void ToString ( );
    Widget( const Widget& rhs );
 private:
    int *colorPallete;
};

void Widget::ToString()
{
 int i = 0;
 for ( i = 0; i < MAX_COLORS; i++ )
 {
 cout << "colorPallete[" << i << "]: " << colorPallete[i] << endl;
 }
}

Widget::Widget ( int seed ):
    colorPallete ( new int[MAX_COLORS])
    {
     int i = 0;
     for ( i = 0; i < MAX_COLORS; i++ )
     {
      colorPallete[i] = seed + i;
     }
    }

Widget::Widget( const Widget& rhs ):
    colorPallete( new int[MAX_COLORS] )
{
    std::copy ( rhs.colorPallete, rhs.colorPallete + MAX_COLORS, colorPallete );
}

Widget& Widget::operator=( const Widget& rhs )
{
    Widget tmp(rhs);

    std::swap ( colorPallete, tmp.colorPallete );

    return *this;
}

Widget::~Widget()
{
 delete[] colorPallete;
}

int main()
{
 Widget b(10);
 Widget a(20);
 b.ToString();
 b = b;
 cout << endl << "After: " << endl;
 b.ToString();
}

A: The junk you're seeing is because the MakeDeepCopy function always copies from the colorPallete member of rhs, instead of the copy you made in origColorPallete.
The following modification would fix it:
int *Widget::MakeDeepCopy ( const int *rhs )
{
    int i = 0;
    int *colorPallete = new int [MAX_COLORS];
    for ( i = 0;i < MAX_COLORS; i++ )
    {
     colorPallete[i] = rhs[i];
    }
    return colorPallete;
}

Widget& Widget::SelfAssignmentAndExceptionSafe ( const Widget& rhs )
{
    int *origColorPallete = colorPallete;
    colorPallete = MakeDeepCopy ( origColorPallete );
    delete[] origColorPallete;
    origColorPallete = 0;
    return *this;
}

Actually, with the above modification you may want to rename MakeDeepCopy to CopyColorPalette or something (particularly if you want to keep the original MakeDeepCopy for other purposes).

A: When you call MakeDeepCopy you always pass in the reference to the object. Hence it again runs as a self-assignment.
You'll be much better off if you check against self-assignment in each public method and only run copying if assignment is called with another object passed.

A: You could avoid a lot of this hassle by simply using a std::vector instead of a dynamically allocated array. Vectors support assignment (including self assignment) so there would be nothing really to do.

A: the problem is that you are not dealing with the copying on itself.
Therefore, when you are performing a copy on itself, the statement
colorPallete = new int [MAX_COLORS];

is actually also overwriting the colorPallete of rhs

A: Sticking out like a sore thumb in your example is the lack of a user-defined copy constructor. As you are providing a user-defined destructor and assignment operator, it's reasonable to reason that you might need a user-defined copy constructor and that is, indeed, the case here. Any explicit or implicit call to the compiler generated copy constructor will lead to undefined behaviour when the last of the original and the copy is destroyed.
You can write a trivial no-throw swap function for your class and it's fairly easy to write an exception neutral copy constructor. (Actually, I believe that it's trivial to write and reasonably easy to reason that it's exception neutral.) If you implement your assignment operator in terms of these two functions (the copy-and-swap idiom), you should find it a lot easier. In particular, you should find that the need for any checks for self-assignment should go away.
Edit:
Since your update you have made the Widget assignment operator exception safe. However, your design depends on the fact that you only have a single operation in the assignment operation that could possibly throw (the allocation of new memory) as the assigment of ints cannot throw. In general, if you held an array of objects this would not hold.
I understand that MakeDeepCopy is a private function, but even so it has an interface the depends heavily on correct usage. Either the member variable colorPallete must be delete[]ed and set to 0, or it must be saved to a temporary in the event that the call succeeds so that it can then be delete[]ed.
Even if you did not want to make a copy constructor public, I would still use it to implement the assignment operator as it makes the whole code simpler.
E.g.
Widget::Widget( const Widget& rhs )
    : colorPallete( new int[MAX_COLORS] )
{
    // OK because assigning ints won't through
    std::copy( rhs.colorPallete, rhs.colorPallete + MAX_COLORS. colorPallete );
}

Widget& Widget::operator=( const Widget& rhs )
{
    // Try allocating a copy, Widget's copy constructor must
    // leak anything if it throws

    Widget tmp( rhs );

    // If that worked, swap with the copy - this can't throw

    std::swap( colorPallete, tmp.colorPallete );

    // Our old internals are now part of tmp so will be
    // deallocated by tmp's destructor
}

I've got what's effectively your MakeDeepCopy in the copy constructor but without any of the necessary conditions on the calling code because it is a copy constructor and a simple two line assignment operator that is (IMHO) more obviously exception safe.
Note that if you held an array of objects that might throw during assignment, you'd have to do something a bit cleverer to maintain exception safety and transparency. e.g. (and this probably illustrates why using a std::vector is a good idea):
template< class T  >
class PartialArrayDeleter
{
public:
    PartialArrayDeleter( T* p )
        : p_( p ) {}

    ~PartialArrayDeleter()
    {
        delete[] p_;
    }

    void reset()
    {
        p_ = 0;
    }

private:
    T* p_;
};

Widget::Widget( const Widget& rhs )
    : colorPallete( new Obj[MAX_COLORS] )
{
    PartialArrayDeleter<Obj> del( colorPallete );

    std::copy( rhs.colorPallete, rhs.colorPallete + MAX_COLORS. colorPallete );

    del.reset();
}

Edit 2:
In case you think it's not relevant to consider objects other than int being assigned, then note that if you only consider the class that you have, reallocating is not strictly necessary during assignment. All widgets have the same amount of memory allocated in their constructor. A simple, efficient and exception safe assignment operator would be:
Widget& Widget::operator=( const Widget& rhs )
{
    for( size_t i = 0; i != MAX_COLORS; ++i )
    {
        colorPallete[i] = rhs.colorPallete[i];
    }
    return *this;
}

Self-assignment of ints is safe and as previous noted assignment of ints is also exception safe. (I'm not 100% sure but I don't think that std::copy is technically guaranteed safe for a self-assignment copy.)


text:
Q: How do I get the keyWindow reference in a swift app? In Objective-C in the viewDidLoad method of a UIViewController I do this to get the keyWindow reference in my iOS app:
 UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];

So, I am porting this view controller into Swift and I do this one the viewDidLoad call:
let window = UIApplication.sharedApplication().keyWindow

I am trying to understand why the window is nil. When I put a breakpoint right after that line I then inspect window in the console and I get this:
(lldb) po window
nil

How can I get window to be a valid reference to the keyWindow of my application in swift?

A: I came to this question when I was searching for getting window in swift. If you want to get window instead of keyWindow, try this (Swift 2):
if let app = UIApplication.sharedApplication().delegate as? AppDelegate, let window = app.window {
    MBProgressHUD.show(text, view:window)
}

Updated for Swift 3: (Thanks @Trevor)
if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
    MBProgressHUD.show(text, view:window)
}

A: Updating superarts.org's answer for Swift 3:
if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
      MBProgressHUD.show(text, view: window)
}

A: The easiest way to do that is:
in Objective-C
[UIApplication sharedApplication].windows.firstObject

in Swift
UIApplication.shared.windows.first!

Note that this works only if you do not support multiple windows.

A: The key window must not yet be set at the time of viewDidLoad. Your code works fine in viewDidAppear. Alternately, you can get the windows array in viewDidLoad, and get one (if there's more than one) of the windows from that array.

A: Swift 4 simply has UIApplication.shared.keyWindow property, no casting necessary.
Note that iOS 13/iPadOS introduces UIScenes and explicit support for multiple windows, and thus deprecates the concept of keyWindow as it is no longer valid.
This question has an overview how to get access to scene based windows.

A: Don't call window in didLoad function call the keyWindow in viewDidAppear function of ViewController

A: Swift 5.1
Works for me
If you are also looking for a way to deal with foreground and background modes you should try this
UIApplication.shared.windows.first(where: { $0.isKeyWindow })


text:
Q: Eslint with TypeScript: No files matching the pattern "'./src/**/*.{js,ts}'" were found I'm trying to set up Eslint and Prettier with TypeScript (vanilla JS project). Whenever I try to run lint command from the command line, I get this error:

No files matching the pattern "'./src/**/*.{js,ts}'" were found.

I don't see how could this be wrong, since all my dev files are placed in the "./src" folder. My VSCode is also not giving any feedback on linting.
"scripts": {
    "dev": "webpack-cli serve --mode=development --env [development] --open --hot",
    "build": "webpack --mode=production --env production",
    "lint": "eslint './src/**/*.{js,ts}' --quiet"
  },

My eslintrc.js
module.exports = {
  parser: "@typescript-eslint/parser",
  parserOptions: {
    project: ["./tsconfig.json"],
    ecmaVersion: 2020,
    sourceType: "module",
  },
  extends: [
    "airbnb-typescript/base",
    "plugin:@typescript-eslint/recommended",
    // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
    "prettier",
  ],
  env: {
    browser: true,
    es6: true,
  },
  plugins: ["@typescript-eslint", "import", "prettier"],
  rules: {},
};

My tsconfig.json
{
  "compilerOptions": {
    /* Make sure to avoid setting module to "CommonJS", or webpack won't be able to tree-shake your code [https://webpack.js.org/guides/typescript/] */
    "module": "commonjs",
    // Raises errors for declarations with an implied any type "noImplicitAny": true,
    "outDir": "./build/",
    "preserveConstEnums": true,
    "removeComments": true,
    "sourceMap": true,
    /* Represents the specific ECMAScript version
    to transpile the code in the browser  */
    "target": "es5",
    "lib": ["esnext", "dom", "dom.iterable"],
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "allowJs": true,
    "baseUrl": "./src",
    "paths": {
      "src/*": ["./src/*"]
    },
    "typeRoots": ["src/customTypes", "node_modules/@types"],
    "resolveJsonModule": true,
    "moduleResolution": "node",
    "downlevelIteration": true
  },
  "include": ["src/"],
  "exclude": ["node_modules", "**/node_modules/*"]
}


text:
Q: Model for ice sheet thickness How should I proceed to find a formula $\lambda(t)$ for the thickness of and ice sheet in terms of

*

*The diference $T_{a}(t)-T_w(t)$ of the temperatures of air above the sheet and water below

*Thermal conductivity ($k$) and entalphy of fusion ($h$) of ice

Im new to "modelling" this stuff so I haven't made any real progress. All the equations I find online make sense for an ice sheet of area $A$ or take into account the depth of the river/lake or some other factor, but I want to assume that the ice sheet is infinite in extension: an infinite plane with some thickness dividing the space into "water region" and "air region". I wouldn't mind if $T_a$ and $T_w$ are constant (they are regions so huge that their temperatures do not really change).
Please consider explaining some steps that may be obvious in physics. I'm looking for a line of reasoning like "by conservation of energy we should have the following equation _______ which, combined with ______ gives us ______" or something similar. Nothing fancy, only an equation $\lambda(t)=$expression in terms of $k$, $h$ and the temperature difference
Thanks!


text:
Q: OpenLayers: creating a minimal map I'm sorry for this basic question. But I'm pretty new with OperLayers. As a first step, I want to show the OpenStreetMap which is already zoomed on Vienna. The code displays a map with an OpenStreetMap layer centered on Nottingham. Instead of Nottingham I want Vienna.
The code of Nottingham

A: Even if I (as @kryger) don't understand what the exact problem is (I hope you don't ask at SO others just for a pair of coordinates?), I will try an answer:
You can have a look at the source of this example: http://openlayers.org/dev/examples/osm.html
The only thing you have to modify are the startup coordinate pair:
...
new OpenLayers.LonLat(16.3866, 48.1913).transform(...)
...

You can find this coordinates, if you browse OSM and have a look at the URL http://www.openstreetmap.org/node/17328659#map=12/48.1913/16.3866

Maybe it's just an misunderstanding and don't call me rude, but every support community expects minimal work by the questioner. A study of http://openlayers.org/dev/examples/ seems to be not to hard esp. for new users. Anyway have fun with Openlayers :)


text:
Q: Can we wear hats in chat? I want to wear my hat in chat. Any chance of this happening?
I spend a lot of time in chat, so showing off my achievements in chat would be something that interests me.
HAT GET. :)

A: Sorry, I'm going to have to status-declined this. There wasn't a good way of implementing this without certain site functions taking a big hit. Also remember: chat.stackoverflow.com is the same size as the entire chat.stackexchange.com. Hats are an extra javascript overlay that takes a minute to get going. It was too expensive for us to implement this year.
However: I really like this idea! We will definitely consider it for next year. And, as others have pointed out: being in chat will earn you some hats down the road. :)

A: Hats work on chats now, as of WinterBash 2013.
I assume they will be rolling it out to the network in a while.


text:
Q: WordPress rewrite post url to keep page url I was wondering if it's possible to rewrite the url of a post to keep the current url as permalink and add the post name at the end of current url. I ask this because I've created a custom WP_Query and integrated that in a page.
So I want the url to be like http://sitename.me/pagename (here is the custom query) and the post link would look like http://sitename.me/pagename/postname instead of sitename.me/category/postname.
Do you have any suggestions how can this be achieved?
Thanks,
Ciprian

A: You are asking to fetch someone with out knowing their identity!
You will have to send the postname some way or the other. May be through Input Type=Hidden and fetch it from the query-string.


text:
Q: How to input answers to a shell script automatically using a a batch file? I have a shell script that that has some questions that nee to be answered(Answers are in form of strings). I have to make another batch file that opens the shelll script and answers the questions automatically. the problem i am facing is that when i open the shell script on cmd using my batch file, i get stuck on the shell script. Any ideas on what commands i will need to input the answers automatically?

A: Generically, you need to use either redirection with a temporary file, or a pipe.
I'll assume your controller batch file needs to provide three answers to script.bat.
Using Redirection
@echo off
>answers.txt echo answer1
>>answers.txt echo answer2
>>answers.txt echo answer3
call script.bat <answers.txt
del answers.txt

or you can use a single redirection if you use parentheses
@echo off
>answers.txt (
  echo answer1
  echo answer2
  echo answer3
)
call script.bat <answers.txt
del answers.txt

Using a Pipe
@echo off
(
  echo answer1
  echo answer2
  echo answer3
) | script.bat


text:
Q: How few samples are needed to compare two means? I have the following statistical problem:
I have two boxes, each has exactly 10000 numbers in it. Each number is either 0, 1, or 3. What I need to know is if the average amount in one box is bigger or smaller than the average amount in the other box.
Unfortunately, picking numbers is very costly for me. So what I would like to know is, how and how many numbers do I have to pick so that I can say with e.g. 90% probability that one box's average is below or above the other ones'?
EDIT:
I can iteratively randomly pick one number of a chosen box, and after each pick I can recalculate the probability. So I do not want to calculate how many I have to pick beforhand, but I would like to update a probability after each pick.
For example, when I randomly pick 10 numbers out of box 1 and each time I get a "3", and from the other box I pick 10 numbers and each one is "1", chances should be high that box 1's mean is higher than that of box 2. So I think it should be possible to somehow calculate if it is useful to continue picking or say with high probability that further picking will not change the final outcome.
This is no homework, but should be part of an optimization software I am writing. I want to quickly evaluate if one solution is better than another one.

A: Your initial question was a simple problem of comparing means via one batch sample.  Your revised question is about sequential analysis, which is even more judicious about sample size.  I wish more people thought about sequential analysis, as it's much more cost-effective when samples are expensive.
In deference to the "teach a man to fish" school of thought, I'll recommend looking into a book on this topic.  Wald's 1973 book is very nice, though I've never seen a Dover book list for so much on Amazon.


text:
Q: Mavn shade plugin with AWS Lambda I'm using the maven shade plugin as below to create a jar for aws lambda
 <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>${maven.shade.plugin.version}</version>
                <configuration>
                    <createDependencyReducedPom>false</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <!-- Suppress module-info.class warning-->
                                <exclude>module-info.class</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                    </execution>
                </executions>

As per the documentation, I am supposed to discard the original-xxx.jar.
But is 14MB source code not too big for AWS lambda?
Is there a way to reduce it. I only used AWS core/event/dynamoDB libraries with Jackson
original-artifactName-version.jar = 7KB.
artifactName-version.jar = 14MB

A: If your Lambda gets too big you can use a Lambda Layer to put all the Lambda's dependencies there. In this article you can find how to do it.


text:
Q: Views does not open in live MVC application After I published my application none of links works in web site except default.aspx. When I clicked them "page not found" is shown. I guess, it is about routing. But I did not do any change on  default mvc routing settings. What could cause this kind of thing?
Thanks.

A: Verify that IIS which hosts your published web site has all the correct settings to run ASP.NET MVC (see this for on how to set up IIS 6 and this for IIS 7).

A: One would need more details to debug the issue. On a quicker note, first check for server logs (IIS/Apache) - it would indicate whether the request reached the server or not, where was the requested routed to, who processed it and what happened. Also check for server error logs.


text:
Q: Rspec nested controller create method does not increase count by 1 I am testing an Invoice model (a Client has many invoices, an Invoice belongs to a Client) and trying to check whether the create method works.
This is what I have come up with:
before do
  @valid_invoice = FactoryGirl.create(:invoice)
  @valid_client = @valid_invoice.client
end

it "creates a new Invoice" do
    expect {
      post :create, { invoice: @valid_client.invoices.build(valid_attributes), client_id: @valid_client.to_param }
    }.to change(Invoice, :count).by(1)
  end

This is my invoice factory:
FactoryGirl.define do
    factory :invoice do
        association :client
        gross_amount 3.14
        net_amount 3.14
        number "MyString"
        payment_on "2013-01-01"
        vat_rate 0.19
    end
end

This is the create method in the invoices_controller:
def create
@client = Client.find(params[:client_id])
@invoice = @client.invoices.build(params[:invoice])

respond_to do |format|
  if @invoice.save
    format.html { redirect_to([@invoice.client, @invoice], :notice => 'Invoice was successfully created.') }
    format.json { render :json => @invoice, :status => :created, :location => [@invoice.client, @invoice] }
  else
    format.html { render :action => "new" }
    format.json { render :json => @invoice.errors, :status => :unprocessable_entity }
  end
end
end

And these are the valid attributes, ie the attributes needed for an invoice to be created successfully:
def valid_attributes
{
  gross_amount: 3.14,
  net_amount: 3.14,
  number: "MyString",
  payment_on: "2013-01-01",
  vat_rate: 0.19
}
end

These are all valid. Maybe the client_id is missing?
It is only telling me that the count did not change by one - so I am not sure what the problem is. What am I doing wrong?

A: @gregates - Your answer was right, why did you remove it? :-) Post it again and I will check it as best answer.
This is the solution:
post :create, { invoice: valid_attributes, client_id: @valid_client.to_param }, valid_session

instead of
post :create, { invoice: @valid_client.invoices.build(valid_attributes), client_id: @valid_client.to_param }

in the test.
Also, I had to change the number in the valid_attributes. Debugging every single validation showed me that it was the same as in the factory - but must instead be unique. This solved it for me! Thanks for everyone's help!


text:
Q: How to use Liferay Mobile SDK 6.2.18 to generate jar libraries now that http is deprecated by both Gradle and Maven? In my current project we're working on mantaining/developing mobile (android/iOS) apps that use the services of the client's website  (liferay 6.2). Whenever the guys in Backend generate new services (or just update an existing service to a new version with new features) we need to use the Liferay Mobile SDK 6.2.18, which uses really dated gradle 1 and http protocol, to generate a new jar library to allow the app call those new services.
As I guess many will know already, gradle recently deprecated HTTP in favour of HTTPS, and maven shortly after followed suit, so now we are completely unable to generate the jar libraries.
Unfortunately, our client won't accept upgrading Liferay to 7 - which Backend guys tell me would solve this bump in the road - so we need to find a workaround to this situation. I've tried searching both google in general (filtering by last month results) and SO in particular, but no dice.
Has anyone else here who found themselves in this situation managed to work around it?


text:
Q: callback function executes before the finished request.on function I made a npm module for my personal use to download file
using request and displaying the progress bar using progress
https://github.com/MaxySpark/maxyspark-download
but when I test it the callback function executes first, it should execute after finished the download.
my test file
const maxDonwload = require('maxyspark-download');

var filename = "prog.gif";
var url = "http://skillprogramming.com/images/pictuers/how_many_of_you_get_the_same_feeling.gif";
function endFunc() {
    console.log("download completed : "+filename);
}
maxDonwload.download(url,filename,endFunc());

Here is the output
download completed : prog.gif
File Size : 0.50 MB

  downloading [====================] 100% 0.0s
HERE HERE

I added a the line console.log("HERE HRERE"); to node-modules index.js file  in
req.on('end' function() {
    console.log("HERE HRERE");
    callback;
}

console.log("HERE HRERE"); execute after the download complete but callback does not.

A: You are calling the function, instead you should pass it as argument without the ():
maxDonwload.download(url,filename,endFunc);

A: You are calling endFunc() instead of passing the function itself as a parameter.
This should fix it:
maxDonwload.download(url,filename,endFunc);


text:
Q: How to import a large SQL file in the server? Unfortunately I have a SQL file more than 350 MB. I have to import this file on the server to connect the database with one of my clients website. How I can do this? If it was my PC, then I can easily do it by editing the php.ini file. But it's in the live server and the sql file upload limit is only 50 MB. What can I do? I have the cPanel and also the server access. Can anyone help me? Thanks in advance.

A: If you have SSH access then login to MySQL server and use the following command:
mysql -u username -p database_name < file.sql

This is only basic for more detail you can find here

A: Assuming you have FTP access but don't have SSH command-line access, which is often the case with shared servers:

*

*Upload the file via FTP

*Write a PHP program to read through the file line by line and import it. If the file is CSV or similar data, you will need to parse and turn into SQL statements. If the file is SQL statements then you just process each one as a direct SQL command.

PHP is often set to a relatively short timeout to avoid runaway scripts. So you may want to add a set_time_limit() call inside your main loop so that it won't be aborted in the middle.
I also recommend using a counter in the loop to track lines processed. If you get a SQL error then report it (mysqli_error() or similar function) along with the line count. That way you can edit your file locally, find/fix the problem and upload only the unprocessed data to try again.


text:
Q: Sentence comparison: how to highlight differences I have the following sequences of strings within a column in pandas:
SEQ
An empty world
So the word is
So word is
No word is

I can check the similarity using fuzzywuzzy or cosine distance.
However I would like to know how to get information about the word which changes position from amore to another.
For example:
Similarity between the first row and the second one is 0. But here is similarity between row 2 and 3.
They present almost the same words and the same position. I would like to visualize this change (missing word) if possible. Similarly to the 3rd row and the 4th.
How can I see the changes between two rows/texts?

A: Assuming you're using jupyter / ipython and you are just interested in comparisons between a row and that preceding it I would do something like this.
The general concept is:

*

*find shared tokens between the two strings (by splitting on ' ' and finding the intersection of two sets).

*apply some html formatting to the tokens shared between the two strings.

*apply this to all rows.

*output the resulting dataframe as html and render it in ipython.

import pandas as pd

data = ['An empty world',
        'So the word is',
        'So word is',
        'No word is']

df = pd.DataFrame(data, columns=['phrase'])

bold = lambda x: f'<b>{x}</b>'

def highlight_shared(string1, string2, format_func):
    shared_toks = set(string1.split(' ')) & set(string2.split(' '))
    return ' '.join([format_func(tok) if tok in shared_toks else tok for tok in string1.split(' ') ])

highlight_shared('the cat sat on the mat', 'the cat is fat', bold)

df['previous_phrase'] = df.phrase.shift(1, fill_value='')
df['tokens_shared_with_previous'] = df.apply(lambda x: highlight_shared(x.phrase, x.previous_phrase, bold), axis=1)

from IPython.core.display import HTML

HTML(df.loc[:, ['phrase', 'tokens_shared_with_previous']].to_html(escape=False))


text:
Q: join or merge with overwrite in pandas I want to perform a join/merge/append operation on a dataframe with datetime index.
Let's say I have df1 and I want to add df2 to it.  df2 can have fewer or more columns, and overlapping indexes.  For all rows where the indexes match, if df2 has the same column as df1, I want the values of df1 be overwritten with those from df2.
How can I obtain the desired result?

A: How about: df2.combine_first(df1)?
In [33]: df2
Out[33]:
                   A         B         C         D
2000-01-03  0.638998  1.277361  0.193649  0.345063
2000-01-04 -0.816756 -1.711666 -1.155077 -0.678726
2000-01-05  0.435507 -0.025162 -1.112890  0.324111
2000-01-06 -0.210756 -1.027164  0.036664  0.884715
2000-01-07 -0.821631 -0.700394 -0.706505  1.193341
2000-01-10  1.015447 -0.909930  0.027548  0.258471
2000-01-11 -0.497239 -0.979071 -0.461560  0.447598

In [34]: df1
Out[34]:
                   A         B         C
2000-01-03  2.288863  0.188175 -0.040928
2000-01-04  0.159107 -0.666861 -0.551628
2000-01-05 -0.356838 -0.231036 -1.211446
2000-01-06 -0.866475  1.113018 -0.001483
2000-01-07  0.303269  0.021034  0.471715
2000-01-10  1.149815  0.686696 -1.230991
2000-01-11 -1.296118 -0.172950 -0.603887
2000-01-12 -1.034574 -0.523238  0.626968
2000-01-13 -0.193280  1.857499 -0.046383
2000-01-14 -1.043492 -0.820525  0.868685

In [35]: df2.comb
df2.combine        df2.combineAdd     df2.combine_first  df2.combineMult

In [35]: df2.combine_first(df1)
Out[35]:
                   A         B         C         D
2000-01-03  0.638998  1.277361  0.193649  0.345063
2000-01-04 -0.816756 -1.711666 -1.155077 -0.678726
2000-01-05  0.435507 -0.025162 -1.112890  0.324111
2000-01-06 -0.210756 -1.027164  0.036664  0.884715
2000-01-07 -0.821631 -0.700394 -0.706505  1.193341
2000-01-10  1.015447 -0.909930  0.027548  0.258471
2000-01-11 -0.497239 -0.979071 -0.461560  0.447598
2000-01-12 -1.034574 -0.523238  0.626968       NaN
2000-01-13 -0.193280  1.857499 -0.046383       NaN
2000-01-14 -1.043492 -0.820525  0.868685       NaN

Note that it takes the values from df1 for indices that do not overlap with df2. If this doesn't do exactly what you want I would be willing to improve this function / add options to it.

A: For a merge like this, the update method of a DataFrame is useful.
Taking the examples from the documentation:
import pandas as pd
import numpy as np

df1 = pd.DataFrame([[np.nan, 3., 5.], [-4.6, 2.1, np.nan],
                   [np.nan, 7., np.nan]])
df2 = pd.DataFrame([[-42.6, np.nan, -8.2], [-5., 1.6, 4]],
                   index=[1, 2])

Data before the update:
>>> df1
     0    1    2
0  NaN  3.0  5.0
1 -4.6  2.1  NaN
2  NaN  7.0  NaN
>>>
>>> df2
      0    1    2
1 -42.6  NaN -8.2
2  -5.0  1.6  4.0

Let's update df1 with data from df2:
df1.update(df2)

Data after the update:
>>> df1
      0    1    2
0   NaN  3.0  5.0
1 -42.6  2.1 -8.2
2  -5.0  1.6  4.0

Remarks:

*

*It's important to notice that this is an operation "in place", modifying the DataFrame that calls update.

*Also note that non NaN values in df1 are not overwritten with NaN values in df2

A: I did not find a satisfactory answer for this task yet where one does not need to pre-specify which columns should be used. I am doing it by combining merge, rename, and drop. df_some_wrong is a dataframe with important new columns. However, it has some old columns that have wrong values and should be overwritten with the correct values contained in df_correct. Only the columns with wrong values in df_some_wrong are shared between df_some_wrong and df_correct.
wrong_suffix = "_wrong"
correct_suffix = "_correct"
# merge, rename shared columns with suffixes
merged_df = df_some_wrong.merge(
    df_correct.
    left_index=True,
    right_index=True,
    suffixes=(wrong_suffix, correct_suffix),
)
# find all the renamed columns from df_correct
rename_and_drop_cols = [
    col for col in merged_df.columns if col.endswith(correct_suffix)
]
# dict that describes how correct columns should be renamed
# to old column name
rename_cols = {
    key: key.replace(correct_suffix, "") for key in rename_and_drop_cols
}
# list describing the wrong columns that can be dropped
drop = [
    col.replace(correct_suffix, wrong_suffix) for col in rename_and_drop_cols
]
# finally rename and drop
merged_df = merged_df.rename(rename, axis=1).drop(drop, axis=1)


text:
Q: Container fix width. Center div dynamic width. want left right divs to fill out remaining width equally Have Three columns..Combine width of all three is fixed.. 2nd ( center ) column will have dynamic content.. I need left and right column to fill out remaining space ( container width - center column dynamic width )equally.
Example:
http://jsfiddle.net/htKje/

Lorem Ipsum

CSS :
.container { width:500px; }
.bg {backgrould:#CCC; }

A: If you need the left and right columns just for setting the background, then most probably, you don't even need them at all.
Simply setting the background on the .container, giving the same container text-align: center, making the center column inline-block and reseting the background and text-align on it will do the trick.
demo
HTML:

booooo add remove text here

CSS:
.container {
    background: #ccc;
    text-align: center;
}
.c {
    display: inline-block;
    background: white;
    text-align: left;
}


text:
Q: Pandas.read_excel: Blanks in string columns convert to floats, converting via str() produces string 'Nan' In importing an excel file via read_excel, string columns containing blanks are read in as float. When I force them back to strings via str(), the blanks become the string 'Nan', such that when I specify df[df.column=='Nan'], the values are returned.
How can I revise my code to ensure that blanks within a column do not force the entire column to float, and that blanks in a string column are read in as ''?

A: Try filling NA values on read:
df = pd.read_excel(...).fillna('')

A: You don't actually have to convert to string. You can actually do a:
df[df.colname!=df.colname] #Returns True if it encounters a NaN


text:
Q: Alternating row colors what am I missing I get no errors but no table is displayed, I know its not on prepared statements but there is no interaction its just a display so there is no chance of SQL injection
what Am I missing
Hello I have edited the long version
     <?php
echo "
";
echo "
";
echo "NAme	Headhot	Date	Age	";
echo "
";
include("dbopent.php");
$result = mysql_query("
SELECT N, Limg, Lpage, F, Age
FROM (
SELECT N, Limg, Lpage, F, Age
FROM (
SELECT N, Limg, Lpage, F, CURDATE( ) , (
YEAR( CURDATE( ) ) - YEAR( F )
) - ( RIGHT( CURDATE( ) , 5 ) < RIGHT( F, 5 ) ) AS Age
FROM ACT)alias
WHERE Age BETWEEN 30 AND 39)ALIAS
");

while($row=mysql_fetch_array($result))
$color="1";
{
  if($color==1){
echo "
";

echo "" . $row['N'] . "	";
echo "" . "" . "	";
echo "" . $row['F'] . "	";
echo "" . $row['Age'] . "	";

echo "
";
}
else {
echo "
";

echo "" . $row['N'] . "	";
echo "" . "" . "	";
echo "" . $row['F'] . "	";
echo "" . $row['Age'] . "	";

echo "
";

$color="1";
}
   }
echo '
';
?>

A: You write "SELECT SELECT".
P.S. And it is bad practice to mix PHP and HTML code. Look towards the MVC.

A: First issue is that you don't have the FROM clause in your SQL statement. A valid query is as follows:
SELECT * FROM Table WHERE condition = something.
You can define integers without the quotes: $color = "1"; has to be $color = 1; Also, you are supposed to add it after the open curly bracket.
while($row=mysql_fetch_array($result))
{
   $color = 1;
   // rest of the code
}

Also please put error_reporting(E_ALL); on top of your script after the begin tag so it will display any errors on the screen.
You should also explain your issue in a better way, it's unclear what you want.

A: Define color to 1... increase on each loop. do a modulus base 2 to see if there is a remainder and if there is it's odd then otherwise it's even.
$color = 1;
while($row=mysql_fetch_array($result))
{
$color++;
if ($color % 2 == 0){
    $outputColor = "#7b7b7b";
} else {
    $outputColor = "#fff";
}
echo "
";

echo "" . $row['Name'] . "	";
echo "" . "" . "	";
echo "" . $row['date'] . "	";
echo "" . $row['Age'] . "	";

echo "
";
}

this doesn't repeat all that code that is unnecessary.. rather define the color and output it once...
However you should REALLY be using a css style since i didn't think all browsers support a TR with a background color.
Something like echo "
";
and instead setting $outputColor to 'odd' or 'even'
then
.odd td {background-color:#7b7b7b}
.even td {background-color:#fff}


text:
Q: Items se repetindo em uma RecyclerView Tenho um fragment v4 que é gerenciado por uma SectionsPagerAdapter. No fragment tenho uma RecyclerView que tem um Adapter personalizado que recebe uma ArrayList que contém exatamente 96 objetos, que representa as horas do dia, ex: posição 0 = 00:00, 1 = 00:15, 2 = 00:30,  3 = 00:45, 4 = 01:00, e assim por diante até 96 = 23:45. Além da hora em si, ele tem também um campo nome e outro procedimentos. Esses campos só serão preenchidos se tiver alguém agendado para o horário, caso contrario são "".
O problema é que ele esta embaralhando tudo na hora de montar o adapter! Um horário ele repete em vários lugares aleatórios que não tem nunguem agendado... pelo que percebi no log, conforme faz o scroll na recyclerView, ela atualiza o adapter automaticamente... acho que é isso que esta bug... mas não sei como resolver...
Notem na imagem abaixo, deveria ter aparecido o valor somente na posição 01:45, mas aparece também na 00:30, detalhe que nessa posição da ArrayList o campo nome esta vazio.

Estou 2 dias tentando achar o problema mas não consegui... deve ser algo bobo que não estou percebendo =(
segue os codigos:
Fragment
public class FragmentAgenda extends Fragment {
private static MVP.Presenter presenter;
private View rootView;
private AdapterHorarios adapterHorarios;

public static FragmentAgenda newInstance(int sectionNumber, String dataInicial) {
    FragmentAgenda fragment = new FragmentAgenda();
    Bundle args = new Bundle();
    args.putInt(ARG_SECTION_NUMBER, sectionNumber);
    args.putString(ARG_DATA_CONSULTA, dataInicial);
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    this.rootView = inflater.inflate(R.layout.fragment_agenda, container, false);
    this.dad = (AgendaActivity) getContext();

    if (presenter == null)
        presenter = new Presenter();
    presenter.setView(this, getContext());
    presenter.retrieveAgendaDia(getArguments(), savedInstanceState);

    return rootView;
}

@Override
public void onStart() {
    super.onStart();

    initViews();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    getArguments().putParcelableArrayList(KEY_CONSULTAS, presenter.getConsultas());
    getArguments().putParcelableArrayList(KEY_HORARIOS, presenter.getHorarios());
}

private void initViews() {
    RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.containerHorario);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    adapterHorarios = new AdapterHorarios(getActivity(), presenter.getHorarios(), presenter);
    recyclerView.setAdapter(adapterHorarios);
}

@Override
public void upRecyclerView() {
    adapterHorarios.notifyDataSetChanged();
}
}

Presenter
public class Presenter extends PresenterDad implements MVP.Presenter {
private MVP.Model model;
private MVP.View view;
private Context contexto;
private ArrayList<Consulta> consultas;
private ArrayList<Consulta> horarios;
private String mesAno;

public Presenter() {
    this.model = new Model(this);
    this.consultas = new ArrayList<>();
    this.horarios = new ArrayList<>();
}

@Override
public Context getContext() {
    return contexto;
}

@Override
public void setView(MVP.View view, Context context) {
    this.view = view;
    this.contexto = context;
}

@Override
public void retrieveAgendaDia(Bundle args, Bundle savedInstanceState) {
    String dia = String.valueOf(args.getInt(MVP.View.ARG_SECTION_NUMBER));
    mesAno = args.getString(MVP.View.ARG_DATA_CONSULTA);

    if (args.getParcelableArrayList(MVP.View.KEY_CONSULTAS) != null) {
        horarios = args.getParcelableArrayList(MVP.View.KEY_HORARIOS);
        consultas = args.getParcelableArrayList(MVP.View.KEY_CONSULTAS);
        String data = String.format(dia, mesAno);
        model.montarHorarios(horarios, consultas, data);
        return;
    }
    model.retrieveAgendaDia(consultas, dia, mesAno);
}

@Override
public ArrayList<Consulta> getHorarios() {
    return horarios;
}

@Override
public ArrayList<Consulta> getConsultas() {
    return consultas;
}

@Override
public void upRecyclerView() {
    view.upRecyclerView();
}
}

Model
public class Model implements MVP.Model {
private final MVP.Presenter presenter;
private final ConsultaCtrl consultaCtrl;

public Model(Presenter presenter) {
    this.presenter = presenter;
    this.consultaCtrl = new ConsultaDAO();
}

@Override
public void retrieveAgendaDia(final ArrayList<Consulta> consultas, final String dia, final String mesAno) {
    consultaCtrl.retriveList(consultas, dia, mesAno, new Callback() {
        @Override
        public void result(boolean b) {
            if (b) {
                String data = String.format(Locale.GERMAN, "%02d/%s", Integer.valueOf(dia), mesAno);
                montarHorarios(presenter.getHorarios(), consultas, data);
            }
        }
    });
}

@Override
public void montarHorarios(ArrayList<Consulta> horarios, ArrayList<Consulta> consultas, String dataConsulta) {
    if (horarios.size() < 96) {
        horarios.clear();
        int hora = 0, flagHora = 0;
        int minuto = -15;

        for (int id = 0; id <= 95; id++) {
            if ((flagHora - 4) == 0) {
                hora++;
                flagHora = 1;
            } else flagHora++;

            if (minuto >= 45) minuto = 0;
            else minuto += 15;

            String data = String.format("%s %s:%s",
                    dataConsulta,
                    String.format(Locale.GERMAN, "%02d", hora),
                    String.format(Locale.GERMAN, "%02d", minuto)
            );
            horarios.add(new Consulta(hora, minuto, data.replace("-", "/")));
        }

        for (Consulta c : consultas) {
            for (int i = 0; i < horarios.size(); i++) {
                if (horarios.get(i).getDataConsulta().equals(c.getDataConsulta())) {
                    horarios.set(i, c);
                    i = horarios.size();
                }
            }
        }
    }

    presenter.upRecyclerView();
}
}

Adapter
public class AdapterHorarios extends RecyclerView.Adapter<HorariosViewHolder> {
private ArrayList<Consulta> consultas;
private Context contexto;

public AdapterHorarios(Context contexto, ArrayList<Consulta> consultas, MVP.Presenter presenter) {
    this.consultas = consultas;
    this.presenter = presenter;
    this.contexto = contexto;
}

@Override
public HorariosViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater
            .from(parent.getContext())
            .inflate(R.layout.adapter_agenda, parent, false);
    return new HorariosViewHolder( view );
}

@Override
public void onBindViewHolder(HorariosViewHolder holder, final int position) {
    holder.setDados(consultas.get(position));
}

@Override
public int getItemCount() {
    return consultas.size();
}
}

Holder
public class HorariosViewHolder extends RecyclerView.ViewHolder {
private TextView hora, nomePaciente, procedimentos;
private ImageView staus;

public HorariosViewHolder(View itemView) {
    super(itemView);

    staus = (ImageView) itemView.findViewById(R.id.check);
    nomePaciente = (TextView) itemView.findViewById(R.id.nomePaciente);
    procedimentos = (TextView) itemView.findViewById(R.id.procedimentos);
    hora = (TextView) itemView.findViewById(R.id.hora);
}

public void setDados(Consulta consulta){
    if (consulta.getNomePaciente() != null){
        staus.setImageResource(R.drawable.ic_radio_button_checked);
        nomePaciente.setText(consulta.getNomePaciente());
        procedimentos.setText(consulta.getDataConsulta());
    }
    hora.setText(Datas.formatHoraConsulta(consulta.getHoraConsulta(), consulta.getMinutoConsulta())); // retorna hora ex: "07:15"
}
}

A: O RecyclerView.Adapter implementa o padrão "View Holder" recorrendo à classe RecyclerView.ViewHolder usando-a nos métodos onCreateViewHolder() e onBindViewHolder(), permitindo que uma view anteriormente criada possa ser reaproveitada.
É da sua responsabilidade, no método onBindViewHolder(), retornar essa view preenchida com os valores correspondentes ao item da RecyclerView em causa.
O método que estar a ser usado para esse efeito é o setDados() de HorariosViewHolder.
No entanto, ele só actualiza a view quando consulta.getNomePaciente() != null.
Quando não é esse o caso, a view é retorna sem alteração(apenas hora é actualizada), ela tem valores de um item anteriormente usado.
Deve alterar o método de forma a que as duas situações sejam tratadas.
public void setDados(Consulta consulta){
    if (consulta.getNomePaciente() != null){
        staus.setImageResource(R.drawable.ic_radio_button_checked);
        nomePaciente.setText(consulta.getNomePaciente());
        procedimentos.setText(consulta.getDataConsulta());
    }else{
        staus.setImageResource(R.drawable.ic_radio_button_checked);//ou outra, não sei
        nomePaciente.setText("");
        procedimentos.setText("");
    }
    hora.setText(Datas.formatHoraConsulta(consulta.getHoraConsulta(), consulta.getMinutoConsulta())); // retorna hora ex: "07:15"
}


text:
Q: Unix inbox line wrapping behavior I've developed an application that parses data from unix inboxes, and retrieves the messages using IMAP.  The main issue I'm running into right now is that the flat file inbox in /var/mail that stores the emails is wrapping the line and inserts an equals after 75 characters.  The strangest thing is that this occurs only within the body of the message.
12345678901234567890123456789098    2010-03-04  1:56:43 192.156.1.1 Microsoft F=
irefox

Could this be a problem with the separate SMTP server reformatting the emails, or is it a problem with the inbox or the imap server?
Thanks.

A: That is normal, read up on Quoted-printable encoding.
You are probably going to have to look at the content-transfer-encoding header for the message or the mime part.  Check if it is quoted-printable and then decode it.  There is almost certainly a library or function available for your programming language to do this for you.


text:
Q: Flask-jwt How DO I specify authorization after successful authentication I'm using flask, flask-jwt and flask-restful. I can get the access_token , but once any user gets authenticated he can do everything to all database tables using the REST-API endpoint , how can I implement authorization where certain user can do specific action to certain row/field in database "one belongs to him for example".
All articles I've read talks about getting authenticated only, but do not go beyond.

A: I found a solution, actually jwt just returns a signed token which contains the user identity and other information, to see details included in the token one can use the following website:
https://jwt.io/
Using flask-jwt , there is an object called current_identity which can be obtained under any function decorated by @jwt_required, it has to be imported first:
from flask_jwt import jwt_required , current_identity
current_identity in my case returned id and name of the user whose trying to insert/update data through the API endpoint.
using some logic to compare the user related data from the database and his id can be used to authorize or prohibit the user from manipulating/reading data.


text:
Q: Split string in c# and getting the right string I want to split this String.
text1:text2

My code:
string[] split = line.Split(':');
Console.WriteLine(split[0])

Output:
text1

How can I get "text2" ?

A: You are close:
The results are 0 based, so the first string starts at 0 which is why split[0] returns text1.
So to get the second element text2 just use split[1] .

A: You need to access the second element of the array: split[1]


text:
Q: Windows 7: AppData folder not visible in windows explorer I am somewhat new to Windows 7. I am running a foreign language version
of Windows 7 (not sure if this matters or not). Anyways, when I use cmd
to run a command prompt environment and
C:\Users\MyUserNameHere> dir
I don't see the folder named AppData.
When I do the same thing and go and check this out from the windows explorer
application I also cannot see the AppData folder. However, when I
C:\Users\MyUserNameHere> cd AppData
I can cd to this folder. It is as though this folder is somehow hidden.
So, my questions are:

*

*What is this folder for, i.e., what is its purpose in Windows 7?
I see some installations install stuff under
this folder and others do not. Why?

*What is the difference between the three directories contained therein:
Local, LocalLow, and Roaming?
Do they have different purposes?

*Can I "unhide" this hidden AppData folder so that I can navigate to it
with more ease in the windows explorer.exe application?

*Aptana Studio 3 installed itself under the AppData\Local directory
whereas webcam shots taken with skype are found under AppData\Roaming.
Why this choice of directories? (this question is just a special case of 2.)
Thank you for clarifications,
I also would like to be pointed to a book detailing this sort of things for
Windows 7 so that I may be able to better use the OS if you don't mind
suggesting a link or book.

A: *

*The folder is used for applications to store any user data, such as settings or cache files.

*See this site for a good explanation.

*You can un-hide the folder by turning off the "hidden folders" feature under [Edit>Folder Options] (press the alt key to see the menus). Or see the above link for further info.

*I expect that the program is storing the shots in roaming so that if you were using a networked pc (such as on a domain in a work place) the images would be able to travel from PC to PC when you logged on and off.

A: As mentioned AppData folder is hidden by default to view it from a CMD line use the following;
cd %userprofile%
dir /a:h

The %userprofile% is a useful environment variable for accessing the current user profile folder location.
The switch added to dir tells dir to show files / folders with the attribute hidden.

Note: Changing the hidden files option in Folder
  options will only effect Explorer and Cmd.exe will still hide files /
  folders with the hidden attribute.

Following on from jamesakadamingo answer point 4
The reason for the difference is the AppData\Local folder is used for storing information specific to the users profile that should be stored locally (i.e it is specific to the current machine). LocalLow is the same but is specifically for low integrity applications to store data locally.
In your example of Aptana Studio 3 if you went and used another machine you wouldn't necessarily have Aptana Studio 3 installed, so persisting that information isn't of any benefit.
Whereas AppData\Roaming follows users from machine to machine (if their user profile is roaming) and usually contains information that could persist and still be of benefit, in the case of Skype, WebCam shots (which are just images accessible with any image viewer or editor) this would be useful content to persist with your profile.

A: A good source would be Windows 7 Tips by Paul Thurrott


text:
Q: Using IntelliJ 11 Community Edition with Mercurial I am using IntelliJ 11 Community Edition for a project that is in Mercurial (but not at the root of the repository). I integrated the project with Mercurial in the VCS menu, and all the options are now available. However, they don't seem to do anything. The only thing that seemed to do anything is to pull from the server. It doesn't show changed files, commit doesn't do anything. When I deleted a file I got this error message:
hg remove --after src/stats/KolmogorovSmirnovStatistic.java
abort: repository /home/ga1009/PhD/cpp/pmi/java not found!

the root of the repository is /home/ga1009/PhD. How can I get it configured?
I am using Debian Linux is it is relevant.

A: I raised a ticket on the official site and got a solution that seems to work:

Go to Settings | Version Control and map the repository root to the
  Mercurial VCS.

A: Looks like Mercurial is supported in the community edition:
http://www.jetbrains.com/idea/features/editions_comparison_matrix.html?IC
Sorry, I use Subversion.  But when I do, I have to check out the project from Subversion in order to get a working copy.  Did you do that with Mercurial?  Or are you working with your original files?
I'd do this:

*

*Back up your original source.  God forbid you should lose a repository named "PHD".

*Check the code into Mercurial.  Make sure you can see it in the browser.

*Blow away your original source.

*Open IntelliJ and check out from Mercurial.

You should be able to see changes added to the change list as you work.

A: I had to edit the .idea/vcs.xml file to get it working.
The VcsDirectoryMappings needs to read something like:
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$/.." vcs="hg4idea" />
  </component>


text:
Q: Runtime Error: member access within null pointer of type 'TreeNode'. UndefinedBehaviorSanitizer: /**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<double> averageOfLevels(TreeNode* root) {
        queue <TreeNode*> q;
        q.push(root);
        q.push(nullptr);
        vector<double>ans;
        while(q.size() > 1)
        {
            double sum=0;
            int nodes=0;
            while(q.size() > 1){
                TreeNode* curr = q.front();
                q.pop();
                sum += curr->val;
                nodes++;
                if(curr->left != nullptr)
                {
                    q.push(curr->left);
                }
                if(curr->right != nullptr)
                {
                    q.push(curr->right);
                }
                if(curr == nullptr)
                {
                    q.push(nullptr);
                    continue;
                }
            }
            ans.push_back(sum/(nodes*10^5));

        }
        return ans;

    }
};

I was practicing an interview code which seemed to be pretty easy. Given the root of a binary tree, I have to return the average value of the nodes on each level in the form of an array.
I made use of Level Order Traversal using a queue which will run to the end of the row/level before moving onto the next level.
I made use of the nullptr to tell when a level ends.
But then this code gave me an error:
Line 26: Char 30: runtime error: member access within null pointer of type 'TreeNode' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:35:30

What causes that error?


text:
Q: Не находит stdint.h Я подключал sfml к codeblocks, запустил проект и получил ошибку
fatal error stdint.h: no such file or directory.

Ошибка была в файле stdint.h
В строке
#include_next<stdint.h>

Помогите я новичок в sfml.


text:
Q: Error when converting large Formal class SpatRaster to dataframe I am attempting to convert a large Formal class SpatRaster to a dataframe, but receive an error, that seems to be related to memory allocation but I am not sure.
#Libraries:

library(terra)
library(raster)
library(geodata)

#Assigning the extent of the world that I am analyzing (approximately the Americas):

extent_obj <- extent(x = c(-160, -34, -46, 50))

#Pulling in the data from the internet (careful, for this can take up to 4 hours, only here for maximum reproducibility):

bioclim_all <- worldclim_global(var = "bio",
                                res = 0.5,
                                path = "data/")

#Crop the data to the extent:

crop_bioclim_all <- crop(x = bioclim_all, y = extent)

#Attempt to convert this object to a dataframe:

data_frame_bio_all <- terra::as.data.frame(crop_bioclim_all)

However, I receive the following error:
Error in x@ptr$readValues(row - 1, nrows, col - 1, ncols) :
  std::bad_alloc

Does anyone know what might lead to this error? I ended up manually downloading the data and using this same code to read it (getData first checks the working directory for the data described before attempting to download), and the file is quite large, around 10 GB of data. For reference, this code runs in less than 2 minutes on my machine when working with the much lower resolution file from the same website, the res = 10 data.

A: You have about 17 million values
library(terra)
r <- rast(res=1/120 , ext=c(-160, -34, -46, 50), nlyr=19)
ncell(r) / 10e6
#[1] 17.41824

Your computer cannot load all these values into memory, at least not in one step in which case it needs contiguous memory. You could try to read layer by layer.
But why are you going down this dark path? There hardly ever is a good reason for making a data.frame like this. It suggests you are not very familiar with working with raster that and that you need to ask another question first (about your goal).


text:
Q: How can I fix the discrepancy between my code on Heroku and my code on Github? My application code on Heroku is different from my application code on my computer and on Github. For the latest git commit I made, I added all of the revisions to my files using "git add ." and the correct changes I was looking for got pushed to Github, however when I pushed the code to Heroku several of the changes didn't take effect. The design of my web application on my local server has the correct attributes I'm looking for, however even after I committed the new application code to Heroku the design didn't change to reflect the changes in my code.
I'm not sure what could be causing this problem, or how I can go about fixing it. Any help you could give me would be great! Thanks so much!

A: I know that a lot of people will tell you the obvious.
git status
git commit -am "Your update message"
git push heroku master
heroku restart
However, I had this issue and the real problem was with the SSH key.
I noticed that I was only able to make successful changes from a given machine. Delete the key for your machine on heroku and recreate and add the key again.
Are you using Windows or Linux?
Hope this helps.


text:
Q: How do I organize a multivariate linear model into matrices and vectors? I'm reading through an SUU lecture on multivariate regression, and I'm guessing some linear algebra knowledge is assumed. However, I have very little familiarity with linear algebra.
They start out with a function like this:
$$Y_j = \beta_0 +\beta_1z_{j1} +\beta_2z_{j2} +\cdots +\beta_rz_{jr} +\epsilon_j$$
and then, in the next slide:

With $n$ independent observations, we can write one model for each sample unit or we can organize everything into vectors and matrices so that the model is now
  $\mathbf{Y} =Z\boldsymbol{\beta}+\boldsymbol{\epsilon}$.

A: As given in the notes, we have $\mathbf{Y} \in \mathbb{R}^{n+1}$, $Z$ is the design matrix, $\boldsymbol{\beta} \in \mathbb{R}^{r+1}$, and $\boldsymbol{\epsilon} \in \mathbb{R}^{n+1}$. In matrix form, the multiple regression equation given above is written as
$$\begin{array}{c@{}c@{}c@{}c@{}c@{}c}
\begin{bmatrix}
y_1 \\
y_2 \\
\vdots \\
y_n \\
y_{n+1}
\end{bmatrix} &{}={} &\begin{bmatrix}
1 & z_{11} & z_{12} & \cdots & z_{1r} \\
1 & z_{21} & z_{22} & \cdots & z_{2r} \\
\vdots & \vdots & \vdots & \vdots & \vdots \\
1 & z_{(n-1)1} & z_{(n-1)2} & \cdots & z_{(n-1)r} \\
1 & z_{n1} & z_{n2} & \cdots & z_{nr} \\
\end{bmatrix}
&\begin{bmatrix}
\beta_0 \\
\beta_1 \\
\beta_2 \\
\vdots \\
\beta_r
\end{bmatrix} &{}+{} &\begin{bmatrix}
\epsilon_1 \\
\epsilon_2 \\
\vdots \\
\epsilon_n \\
\epsilon_{n+1}
\end{bmatrix} \\
\\[0.1ex]
\mathbf{Y} &{}={} &Z &\boldsymbol{\beta} &{}+{} &\boldsymbol{\epsilon}\text{.}
\end{array}$$
I leave it to you to see why this is. At the very least, I recommend that you learn how to multiply matrices.


text:
Q: Como fazer para que depois de ler um arquivo "txt" ele ler outro em seguida Como fazer para depois de ler o arquivo txt verificar se tem um próximo arquivo txt, sei que para ler o arquivo basta:
ifstream Arquivo;
Arquivo.open("teste.txt");
while ()
{
   // leitura
}

Depois de ler este arquivo, verificar se tem outro arquivo, se tiver ele vai ler este arquivo, e assim sucessivamente.

A: Outra forma, como sugerido na questão do SOEN que eu mencionei nos comentários, é usar o cabeçalho "dirent.h". Ele é padrão no Unix e pode ser baixado no Windows (e usado junto com o seu projeto - basta ter o arquivo de cabeçalho dirent.h). Assim, seu código fica mais independente do sistema operacional.
Um exemplo de uso:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

#include "dirent.h"

using namespace std;

vector<string> listfiles(char *sPath)
{
    vector<string> vRet;
    DIR *pDir = opendir(sPath);
    if(pDir != NULL)
    {
        struct dirent *pEnt;
        while((pEnt = readdir(pDir)) != NULL)
        {
            if(strcmp(pEnt->d_name, ".") != 0 && strcmp(pEnt->d_name, "..") != 0)
                vRet.push_back(pEnt->d_name);
        }
        closedir(pDir);
    }
    return vRet;
}

int main(void)
{
    vector<string> vFiles = listfiles("c:/teste/");
    char sFile[256];

    for(unsigned int i = 0; i < vFiles.size(); i++)
    {
        sprintf_s(sFile, 256, "c:/teste/%s", vFiles[i].c_str());

        ifstream oFile(sFile);
        string sData;

        getline(oFile, sData);

        printf("1a linha do arquivo {%s}: [%s]\n", sFile, sData.c_str());
    }

    return 0;
}

A: Uma forma de listar os arquivos é através das funções FindFirstFile e FindNextFile (Windows):
#include <windows.h> /* Para usar as funções de busca de arquivos */
#include <vector>    /* Para usar */
#include <sstream>   /* Para usar o Stringstream */
#include <iostream>  /* Para manipular a entrada/saída de streams */
#include <fstream>   /* Para usar o ifstream */
....
using namespace std;
...
vector<string> ProcurarArquivos(string diretorio) {
    vector<string> arquivos;                      /* Vetor que irá armazenar os resultados temporários */
    string busca = diretorio + "\\*.txt";         /* Cria o filtro, no diretório será encontrado somente arquivos .txt */
    HANDLE hFind;                                 /* Identificador da pesquisa */
    WIN32_FIND_DATA data;                         /* Estrutura que conterá informações dos arquivos */
    hFind = FindFirstFile(busca.c_str(), &data);  /* Procura pelo primeiro arquivo */
    if (hFind != INVALID_HANDLE_VALUE) {          /* Se a função não falhar */
        do {
            arquivos.push_back(data.cFileName);   /* Armazena no vetor o nome do arquivo encontrado */
        } while (FindNextFile(hFind, &data));     /* Procura pelo próximo arquivo */
    FindClose(hFind);                             /* Fecha o identificador da pesquisa */
    }
    return arquivos;                              /* Retorna o vetor como resultado */
}

Para ler o conteúdo do arquivo e retornar numa string, faça:
string LerAquivo(string arquivo) {
    ifstream ifs;                                          /* Stream usada para fazer operações em arquivos */
    ifs.exceptions (ifstream::failbit | ifstream::badbit); /* Define quais exceções podem ser lançadas */
    try {                                                  /* Tenta executar o código abaixo */
        ifs.open(arquivo.c_str());                         /* Abre o arquivo */
        stringstream ss;                                   /* Stringstream que vai conter o resultado */
        ss << ifs.rdbuf();                                 /* Lê o buffer do stream e coloca no Stringstream */
        string str = ss.str();                             /* Coloca numa string o resultado do Stringstream */
        return str;                                        /* Retorna a string */
    }
    catch (ifstream::failure e) {                          /* Se houver erros em relação a leitura dos arquivos */
                                                           /* Fazer alguma coisa aqui caso ocorram erros */
        return "";                                         /* Retorna uma string vazia */
    }
}

Para obter o caminho da aplicação use a função GetModuleFileName:
string DiretorioDaAplicacao() {
    char buffer[MAX_PATH];                        /* Cria um buffer com tamanho máximo para um diretório */
    GetModuleFileName(NULL, buffer, MAX_PATH);    /* Para retornar o caminho completo do executável */
    int pos = string(buffer).find_last_of("\\/"); /* Captura a posição da última barra "/" */
    return string(buffer).substr(0, pos);         /* Extraí tudo desde o início até o ponto onde foi encontrado a barra "/" */
}

Para extrair somente o nome do arquivo, use a função:
string ExtrairNomeDoArquivo(string caminho) {
    int indice = caminho.rfind('/');              /* Encontra o índice da última ocorrência da barra "/" */
    return caminho.substr(indice + 1);            /* Extraí tudo a partir do índice da barra "/" */
}

Nota: Funciona somente no Windows, e há ocasiões em que essa função poderá falhar.
Exemplo de utilização:
int main() {
    string Diretorio = DiretorioDaAplicacao();             /* Captura o diretório da aplicação */
    vector<string> arquivos = ProcurarArquivos(Diretorio); /* Cria um vetor que armazenará os o caminho dos arquivos encontrados */
    for (vector<string>::iterator i = arquivos.begin(); i != arquivos.end(); i++) { /* Faz a iteração sobre o vetor "arquivos" */
            string conteudo = LerAquivo(*i);               /* Coloca na variável o conteúdo do arquivo atual da iteração */
            string arquivo  = ExtrairNomeDoArquivo(*i);    /* Coloca na variável somente o nome do arquivo atual da iteração */

            cout << "Nome do arquivo: " << arquivo << endl;
            cout << conteudo << endl;
    }
    cin.get(); /* Espera o usuário digitar algo*/
    return 0;  /* Termina o programa */
}


text: Q: How to load javascript from url in js console(for example chrome Ctrl + Shift+ J) I have webserver and I want to host there .js which I want load with simple/not so simple javascript code from chrome js console to modify webs etc... I don't have experience with javascript much and I wasn't able to google solution for this so I would like to know how to do what is in title, thanks for help :)


text:
Q: How to use fold to keep the values between function calls Consider having a list of 3 numbers where each number specify a shift in position and their value changes like this:
x starts off as zero and increases by one until 9 then y does the same and then z does the same. When they are all 9 they reset to zero.
I have written the following to that:
ShiftInX :: ShiftBy->ShiftBy
ShiftInX [z,y,9] = ShiftInY [z,y,0]
ShiftInX [z,y,x] = [z,y,x+1]

ShiftInY :: ShiftBy->ShiftBy
ShiftInY [z,9,0] = ShiftInZ [z,0,0]
ShiftInY [z,y,0] = [z,y+1,0]

ShiftInZ :: ShiftBy->ShiftBy
ShiftInZ [9,0,0] = [0,0,0]
ShiftInZ [z,0,0] = [z+1,0,0]

Also, there are 3 strings:
s1 = "ahsgtdfyu"
s2 = "kfhyrdncl"
s3 = "polsedrtd"

Given a string, I want to take each character of the given string, find it in s3, shift it by x, take that letter and find it in s2, shift it by y, take that letter and find it in s3 and shift it by z and retuen the character.
Do the same for each character of the given string. Before processing each character, the ShiftBy list changes as described at the begining.
I have written a function that gets a character and a shiftBy list as input and returns a character as output. It finds the output caharacter as described above.
    findChar :: String -> Char -> [Int] -> Char
Problem: I want to be able to call this function for each character of the given string but not loose the values of the shiftBy numbers so that the shiftBy number increase for each new character.
processString :: String -> [Int] -> String
I used map for this but the values are lost after each characetr is processed.
I am told i have to use Fold or explicit recursion for this. I understand what fold does but don't know how to use it here. Can anyone please help with this?
Many thanks

A: Your description is very confusing. If I understand correctly, you have a sort of encryption scheme, where s1, s2 and s3 are the key and the ShiftBy list is an encryption state that changes as you go through the string to be encrypted.
What I don't understand is what you mean by  "find it in s3, shift it by x". Do you mean a ROT encoding? Do you mean finding the index and then adding x to it to find the next character, rotating around the end? Do you mean actually modifying the key?
In any case, it sounds like the signature of your current character encryption function is
encryptChar :: Char -> ShiftBy -> Char

when it should be
encryptChar :: Char -> ShiftBy -> (Char, ShiftBy)

i.e. it needs to return the adjusted encryption state.
Or alternatively, don't pass out the altered encryption state and modify it outside, since it doesn't depend on the character.
So as for the fold, the key is to make the encryption state part of the fold state. Here's one way to do this:
-- Given:
encryptChar :: Char -> ShiftBy -> Char
adjustShiftState :: ShiftBy -> ShiftBy -- really just an alias of ShiftInX
-- You can fold thus:
encrypt :: String -> String
encrypt msg = fst $ foldr foldOne initialState msg
    where initialState = ("", [0, 0, 0])
          foldOne ch (encryptedString, shiftState) =
            (encryptChar ch shiftState : encryptedString, adjustShiftState shiftState)

In other words, as you fold, you always keep a pair of the encrypted string so far and the current shift state. At the very end of the encryption, you take the result string and throw the shift state away.
The above is efficient; however, it doesn't do quite what you want, since it goes through the string in reverse. You need a left fold, which (because the way : works) is a bit more complicated, and probably less efficient. (Judicious application of strict left fold and strictness markers could probably be used after profiling reveals issues.)
Here's the left fold version:
encrypt msg = fst $ foldl foldOne msg initialState
    where initialState = ("", [0, 0, 0])
          foldOne (encryptedString, shiftState) ch =
            (encryptedString ++ [encryptChar ch shiftState],
             adjustShiftState shiftState)

Note the use of list concatenation instead of simple cons.


text:
Q: How can I have 2 sentinels in an iterator? I am using the following code snippet to read all the content of a file between 2 lines delimited by start_string and stop_string
with open(file_name) as file:
    start_token = next(l for l in file if l.strip()==start_string) # Used to read until the start token
    result = [line for line in iter(lambda x=file: next(x).strip(), stop_string) if line]

return `result`

My problem is that I have discovered that some times the stop_string can have 2 different values, so I want to specify them to the sentinel.
Something like
result = [line for line in iter(lambda x=file: next(x).strip(), stop_string or stop_string_2") if line]

The idea is that the sentinel is stop_string or stop_string_2
The above code is obviously incorrect, but how can I accomplish it?
How can I have multiple sentinels in an iter?

A: I don't think this is a particularly good approach. I can suggest an alternative:
stop_strings = {stop_string, stop_string2}
with open(file_name) as file:
    iterator = iter(file)
    for line in iterator:
        if line.strip() == start_string:
            break

    result = []
    for line in iterator:
        result.append(line.strip())
        if line.strip() in stop_strings:
            break

Or probably better:
stop_strings = {stop_string, stop_string2}
with open(file_name) as file:
    lines = [line.strip() for line in file]

start = lines.index(start_string)
stop = next(i for i in range(start, len(lines)) if lines[i] in stop_strings)
result = lines[start+1:stop]

If you insist on a functional style, there is:
import itertools as it

stop_strings = {stop_string, stop_string2}
with open(file_name) as file:
    after_start = it.islice(it.dropwhile(lambda s: s.strip() != start_string, file),
                            1, None)
    before_end = it.takewhile(lambda s: s.strip() not in stop_strings, after_start)
    result = list(before_end)


text:
Q: Is using pm2 with node.js in cluster mode safe So pm2 is a process manager that allows me to start multiple instances of my app on the same server. How it works is that it load balances the requests to all instances.
So I thought that this is some form of fake multi-threading to Node.js environments. Then I thought of the following scenario:

What if my Node.js app instances are connected to MongoDB and instance
  0 is doing a find request while at the same time instance 1 is
  actually inserting into the same collection?

MongoDB is NOT single threaded and it has a thread pool. Does that mean that there is a possible clash or is thread safety now related to some form of mutex in MongoDB?
This is just an example case. Is there a possibility for pm2 to cause problems like this?

A: I use PM2 in all of my node applications. As far as cluster mode goes it is as safe as it can be (at least in my experience). There are some caveats to be aware of in PM2 though.

*

*Pay attention to your configuration file. No matter what format you will use (JSON YAML etc) you need to understand the ramifications of each setting. For instance using max cores etc.

*I would advise strongly not to use the watch parameter. It seems to slow up the system and I have had trouble with memory allocation on it.

*Use PM2 Monit to monitor just what is going on on the server so you can be on top of things.

*If you are dealing with a robust production which requires sophisticated clustering then it would be advisable to take a look at other though costly options. In a large, diversified and heavily used cluster system I would not put the entire cluster operation in the hands of one system.
But safe? As far as my experience, yes.

A: From MongoDB's docs, it has support for Concurrency Control.

Concurrency control allows multiple applications to run concurrently without causing data inconsistency or conflicts

If you need to update multiple documents, you can use its $isolated operator

Using the $isolated operator, a write operation that affects multiple documents can prevent other processes from interleaving once the write operation modifies the first document. This ensures that no client sees the changes until the write operation completes or errors out.

Note that $isolated does not work with sharded clusters, but I'm assuming you're working with just one MongoDB database instance.


text:
Q: store input field attributes id, name, type in angular 6 I want to store & send the input field attributes id, name, type & value; to my server.
I am able to store the "name: value," in json format & send to server.
I want to send the input data in below format:
{
   "iEntityId":2,
   "data":[
      {
         "id":2,
         "value":"some name",
         "name":"sSupplierName",
         "type":0
      },
      {
         "id":3,
         "value":"some code",
         "name":"sSupplierCode",
         "type":0
      }
   ]
}

Below is my input field:
<input [type]="q.sFieldType"
       [formControlName]="q.sFieldName"
       [id]="q.sFieldName"
       class="form-control m-input">

A: I have got the solution for this, we just need set a json object and then input the dynamic fields that are used in the input attributes.


text:
Q: extracting a list of observations from a single sas cell I have a sas dataset that has a list of variables embedded within a single character variable, delimited by pipes. It looks something like this:
Obs.  List_of_forms
1,"|FormA(04-15-2003)||FormB(04-15-2004)|",
2,"|FormA(04-15-2002)||FormA(04-15-2003)||FormB(04-15-2003)|"
I would like to extract each of the items delimited by pipes as individual variables, so the data would look something like this:
Obs., form1, form2, form3
1,"FormA(04-15-2003)","FormB(04-15-2004)",.,
2,"FormA(04-15-2002)","FormA(04-15-2003)","FormB(04-15-2003)"
But I'm at a loss for how to do this. I've thought about coding a do-loop to iterate through each pipe, but this seems needlessly complex. Any advice for a more elegant solution?

A: Use the SCAN() function. First we can setup your example data.
data have ;
  obs+1;
  input list_of_forms $60. ;
cards;
|FormA(04-15-2003)||FormB(04-15-2004)|
|FormA(04-15-2002)||FormA(04-15-2003)||FormB(04-15-2003)|
;;;;

Now we can convert it to multiple columns.
data want;
  set have ;
  array form (3) $60 ;
  do i=1 to dim(form);
    form(i) = scan(list_of_forms,i,'|');
  end;
  drop i;
run;

To make it more dynamic you could find the maximum number of values over the whole dataset and replace the hard coded upper bound of 3 on the new variables.
proc sql noprint ;
  select max(countw(list_of_forms,'|'))
    into :nforms
    from have
  ;
run;
...
array form (&nforms) $60 ;