text:
Q: How to set Task Decorator in Task Executor through XML configuration? I have an application that uses Spring Integration for Parallel calls. All configurations are in the config.xml. Is there a way to set the decorator of every task executor I placed but still using the XML configuration?
I have to pass the MDC from the main thread to the parallel threads of my logger.
<task:executor id="taskExecutor" pool-size="650-700"
               queue-capacity="3000" rejection-policy="CALLER_RUNS"/>

This is the task executor config I have right now.

A: It can't be specified with <task:executor/> as it is not supported. Rather you can define a separate bean like this and configure your own task decorator
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
    <property name="corePoolSize" value="4" />
    <property name="maxPoolSize" value="4" />
    <property name="WaitForTasksToCompleteOnShutdown" value="true" />
    <property name="taskDecorator" ref="taskDecorator" />
</bean>


text:
Q: dual monitor/projector login screen if have a dual "monitor" setup, where one of the monitors actually is a projector.
the projector is not always turned on.
the problem is, that the login screen quite often is not visible and the rather unexperienced users do not know how to login then. yes, you would just have to move the mouse to the left or right and then the login screen appears.
anyway, is there a way to change the login screen to clone mode, which actually works well after login?
thanks
thomas

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible (or sane) to check if an octal number is in range with regular expression? I have to check if the content of a given XML element representing an octal number is in the range 0-77776.
Is it possible to obtain this result only with regular expression? I have tried in many ways but somehow some case is not handled. I cannot find a single expression that matches 7 and 54327 and not 77777.
What other approach do you suggest?

A: This regex works, but I can only get it working in perl so far. Hopefully whatever engine you're using will support it:
^([0-7]{0,4}|[0-7]{4}(?(?<=^7777)[0-6]|[0-7]))$
Example perl script:
sub verify {
    $num = shift;
    if ($num =~ m/^([0-7]{0,4}|[0-7]{4}(?(?<=^7777)[0-6]|[0-7]))$/) {
        print "$num: yes\n";
    }
    else { print "$num: no\n"; }
}

@nums = ("54327","7","77776","77777","77774");

foreach (@nums) {
    verify $_;
}

output:
54327: yes
7: yes
77776: yes
77777: no
77774: yes


text:
Q: How do I grep for a string excluding some other string I want to do sth like:
grep -A 10 'myString' && NOT 'anotherString'

If I didn't need -A 10 I know I could pipe greps and use -v, but it would not work like that in this case. So I would do sth like that:
grep "myString" | grep -v "anotherString"

Any ideas?

A: Try to invert and place the grep with the -A 10 argument in the end. Like this:
grep -v 'anotherString' | grep -A 10 'myString'

A: The only POSIX supported options for grep are -EFcefilnqsvx so be aware that the -A option may not be present on all implementations of grep. And even on GNU grep there is no option to specify "match OR match" and there is no regex that can emulate this as all it can do is provide additional matches, but can not withhold them. Essentially the only way to accomplish this with grep alone is to use a pipe.


text:
Q: Django templates _set.all two sub table I have two tables I want to check if there is data or not!
Models:
class Children(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    photo = models.ImageField(blank=True, default='avatar.jpg')

class Groups(models.Model):
    child = models.ForeignKey(Children, on_delete=models.CASCADE)

Templates:
{% if user.children_set.all.groups_set.all.exists %}

It's Like:
get_groups = Groups.objects.fitler(child__user=request.user).count

BUT I need this statement to be in templates, because I am trying to create for loop on User table:
{% for user in users %}
   {{user.username}}
   {% if user.children_set.all.groups_set.all.exists %}
      Yes
   {% else %}
      No
   {% endif %}
{% endfor %}

A: you can also use if condition in template if checking numbers is the ultimate goal like this:
{% if user.children_set.all.groups_set.count == 0 %}

this table is empty

{% else %}

this table is not empty and go with the looping to print items etc

{% endif %}

this may help


text:
Q: Enumerating all paths in a tree I've tried and tried; searched and searched, but could not really find an algorithm to solve my problem. I want to enumerate all paths in a tree, (not just simple paths) those which start and end with the leaf nodes (this is an easy constraint though).
For example, for a tree;
      1
    /   \
   2     3
  / \   / \
 4   5 6   7

I want to be able to generate the following paths:
4
4-2-5
4-2-5-2-1-3-6
4-2-5-2-1-3-7
4-2-5-2-1-3-6-3-7
4-2-1-3-6
4-2-1-3-7
4-2-1-3-6-3-7
5
5-2-1-3-6
5-2-1-3-7
5-2-1-3-6-3-7
6
6-3-7
7

I guess that's all.
I have tried the following solution Complexity of finding all simple paths using depth first search? . However, that only finds the simple paths, therefore paths such as 4-2-5-2-1-3-6 could not be found.
Are there any ways that you can guide me, any algorithm perhaps ?

A: Do paths like 4-2-1-2-5 count? If so, I think I have the answer:
It looks to me like you only want each edge to be visited "once" . So take the "dual" of your graph and look at paths as a sequence of edges rather than a sequence of vertices. This way, edges become your "vertices" and vertices become "edges".
This should reduce your problem to generating simple paths of a graph, a problem you already know how to do.
traverse(path, edg):
    mark edg as visited
    print path
    for each edge (e2) sharing a vertex with edg:
        traverse(e2, path+e2)

(with some sort of precaution to avoid duplicate paths being printed)

A: IF your tree is a binary tree, here's a reasonably simple recursive algorithm. In Python:
def lchild(u):
    return 2 * u

def rchild(u):
    return 2 * u + 1

def paths(u, depth):
    if depth <= 0:
        yield ((), (u,), ())
    else:
        for ldown, lpath, lup in paths(lchild(u), depth - 1):
            yield ((u,) + ldown, lpath, lup + (u,))
        for ldown, lpath, lup in paths(lchild(u), depth - 1):
            for rdown, rpath, rup in paths(rchild(u), depth - 1):
                yield ((u,) + ldown, lpath + lup + (u,) + rdown + rpath, rup + (u,))
        for rdown, rpath, rup in paths(rchild(u), depth - 1):
            yield ((u,) + rdown, rpath, rup + (u,))

if __name__ == '__main__':
    for down, path, up in paths(1, 2):
        print path


text:
Q: Why can't I put a print function statement here? I am trying following code with try-catch block:
import System.Environment
import System.IO
import System.IO.Error
import Control.Exception

isBinary :: String -> Bool
isBinary ss = do
    print "In isBinary fn"   -- works if this line is removed.
    let ans = any (\c -> ord c > 127) ss
    ans

toTry :: String -> IO ()
toTry firline = do
        print "In toTry fn."
        let answer = isBinary firline
        if not answer then do
            print "Sent line not binary: "
        else
            print "Sent line binary"

handler :: IOError -> IO ()
handler e = putStrLn "Whoops, had some trouble!"

ss = "this is a test"
main = do
    toTry ss `catch` handler

However, I am getting following error:
$ runghc trycatch3.hs

trycatch3.hs:9:9: error:
    • Couldn't match expected type 'Bool' with actual type 'IO Bool'
    • In a stmt of a 'do' block: print "in isBinary fn"
      In the expression:
        do { print "in isBinary fn";
             let ans = any (\ c -> ...) ss;
             return ans }
      In an equation for 'isBinary':
          isBinary ss
            = do { print "in isBinary fn";
                   let ans = ...;
                   return ans }

trycatch3.hs:10:30: error:
    • Variable not in scope: ord :: Char -> Integer
    • Perhaps you meant one of these:
        'or' (imported from Prelude), 'odd' (imported from Prelude)

The error goes away and program works well if the print statement is removed from isBinary function.
Why can't I put print statement in this function?

A: The answer is, "because types". Specifically:
isBinary :: String -> Bool
isBinary ss = do
  ....

Since it's a do block, the return type of isBinary must match a monadic type Monad m => m t for some m and some t. Here, since print "" :: IO (), m is IO, so it should've been
isBinary :: String -> IO Bool
isBinary ss = do

and now
    print "In isBinary fn"                 -- works
    let ans = any (\c -> ord c > 127) ss   -- also works
    ans                                    -- doesn't work

ans doesn't work because of types, again. Its type is Bool, but it must be IO Bool -- first, because this do block belongs to IO monad, on account of print; and second, because of the return type of the function as a whole.
Instead, use
    return ans

and now it'll work, because return injects a value into the monadic context, and being the last do block value it becomes the value produced by the do block overall (if return val appears in the middle it just passes the val to the next step in the combined computation).
The function toTry will have to be augmented to use the new definition:
toTry :: String -> IO ()
toTry firline = do
        print "In toTry fn."
        -- let answer = isBinary firline    -- incorrect, now!
        answer <- isBinary firline          -- isBinary ... :: IO Bool
        if not answer then do               --       answer ::    Bool
            print "Sent line not binary: "
        else
            print "Sent line binary"

m a on the right of <-, a on the left.
See this for a general description of do notation.

A: You might be confused by the same print line working in toTry, but not in isBinary. The difference stems from the declaration:
isBinary :: String -> Bool

This means that isBinary is a pure function (i.e. no side effects), taking a string and returning a boolean. In fact, you could simplify it to
isBinary ss = any (\c -> ord c > 127) ss

or even use the point-free style
isBinary = any (\c -> ord c > 127)

However, toTry is
toTry :: String -> IO ()

I.e. it takes a string and returns the IO monad which is impure (can have side effects, such as printing text to the console).
Haskell is a language that encourages using pure functions, and enforces it using the type system, by forcing the programmer to explicitly mark impure code.
Further reading:
What does "pure" mean in "pure functional language"?

A: Looking at your code, it seems your use of print in isBinary is not an integral part of what you want the function to do, but merely a debug print statement that will be removed later on. In that case, you do not want to change the type of isBinary to String -> IO Bool (for more on that, see Will Ness' answer), as you don't actually need IO except for debugging. Rather, the core libraries offer the Debug.Trace module, which caters to this kind of situation. With it, we can add your debug print statement like this:
isBinary :: String -> Bool
isBinary ss = trace "In isBinary fn" $ any (\c -> ord c > 127) ss

Then, once you are done debugging, you can remove the use of trace -- and it bears repeating you really should do that later on. Quoting the Debug.Trace documentation:

Functions for tracing and monitoring execution.
These can be useful for investigating bugs or performance problems. They should not be used in production code.


text:
Q: ElasticSearch fields not working I have the inquisitor plugin to query iis logs, but for some reason when i try to reduce the number of the returned fields it doesn't work at all.
This query works as expected:
{
 "query": {

    "term":
{ "geoip.country_name" : "ukraine"}

} }

but when i add fields it does not.
{
 "fields" : ["port"],
 "query": {

    "term":
{ "geoip.country_name" : "ukraine"}

}
}

A: Use _source, instead of fields,
I think 'port' is a nested object, which you cannot get by using 'fields'
so do as,
{
        "_source" : ["path"]
}

So, your source, only contains path.


text:
Q: FWER adjustment I want to use the built-in ToothGrowth dataset in R to write an assignment and conduct t.tests. The dataset has three columns and 60 rows and, for each observation, it contains the supplement given to a guinea pin which is OJ (orange juice) or VC (vitamin C), the length of tooth growth in a specified period of time and in the last column the dose in mg.
I want to separate the database into two smaller sets to conduct a t.test to see if the raise in dose affects the tooth length per supplement separately and then conduct a t.test to test the difference in means between supplement OJ and VC with response to tooth length as a whole and t.tests to see the difference between OJ and VC keeping the dose constant for both.
Should I use the Bonferroni adjustment for all the $p$-values or do something else? These are 10 tests, but 9 of them concern specific subsamples of the original dataset.


text:
Q: ^(){} syntax in Objective C I have seen some strange syntax like
self.myProperties = ^(){};

I wonder what is meaning of this ?

A: It's a block taking no parameters, returning nothing, doing nothing.
Check for reference:
http://fuckingblocksyntax.com

A: The expression right of the equation sign is an empty lambda expression in objective-c (or C respectively).
In the objective-c/C community often referred to as a block.
And you assign this "anonymous function entry point" to your property myProperties.
You can later pass its value to wherever a lambda expression/block is expected. Or you can call it of course.
Calling syntax should be
self.myProperties();

as it does not take any parameters nor does it return anything. And of course it does not do anything at all. But it should compile and run just fine.


text:
Q: How can I Install a theme from Github I saw this theme around the web and i liked it a lot.
https://github.com/baurigae/polar-night
But i'm a newbie on Ubuntu/Linux, and i have no idea how to install it. Can somebody help me?

A: *

*Go to the Github page and click the Download ZIP button.

*Extract the downloaded archive and rename the directory 'polar-night'

*Move the whole directory to ...

Edit: some more informations.
Two things you should know about themes:
1-You can move them to more than one place: /usr/share/themes make them available to all users, but you must have administration privileges to do so. There are two other places in your home folder: .local/share/themes and .themes.
2-If you open the theme folder, you'll notice it contains some sub-folders named after the window manager you're using. In other words, if the theme don't have any folder 'Unity' for instance, you will not be able to use it with Unity.
Now, if you want to move the extracted folder to your home configuration:

*

*Open a 'Files' window (Nautilus), and display your home folder.

*Hit ctrl-H: this will show you the hidden files, and particularly the folders .themes and .local which are most often hidden.

*If you choose to put the theme into .local/share/themes you may have to create the folder.

*Go to your 'Download' folder, and move the theme into the chosen folder (cut/paste, drag & drop, etc...).

If you want to put it into /usr/share/themes
Using Nautilus will fail because you've not the write permission on this folder. So, hit ctrl-Alt-T to open a terminal window.

*

*In this window, type sudo mv (don't forget the space after mv).

*Select the theme folder in Nautilus and drag it to the terminal window. It will write the folder path for you.

*Hit space one more time

*Select the /usr/share/themes folder in Nautilus and drag it to the terminal window (or just type: /usr/share/themes)

*Hit return, the terminal will ask for your password. Enter it and hit return. You're done.

HTH


text:
Q: Faster way to run VBA for searching a range of dates out of the list I have a VBA script which is used to search a range of specific dates out of a column with dates (from AparSheet), and find the dates which is earlier than the current next month and latter then the next month of the source date, that is stored in the source worksheet (WintelSheet), and copy the whole rows of data with dates in the range over the generated Sheet (copy from AparSheet to GeneratedSheet). The whole process takes around 40 plus minutes, which is very time-consuming and inefficient, though there are a lot data. At first, I'm trying to use filter, but my VBA script didn't work with the filter code. So I just simply use the if statement. I wonder how to modify the code to make it run faster, I already clear the data at the end of the script and off the screenupdating at the start of the script. Is there other ways to amend my script such as optimize the login within the code? (Another question using filtering function at Filter by a range of months in VBA)
Files for testing: http://www.filedropper.com/samplefortesting
Here's my script:
Sub Paste_Dates()

    Dim WintelSheet As Worksheet, _
    GeneratedSheet As Worksheet, _
    AparSheet As Worksheet, _
    wkbSourceBook As Workbook, _
    wkbCrntWorkBook As Workbook, _
    worksheetName As String, _
    Default As String
    Dim wSlastRow As Long
    Dim wSLastPasteRow As Long 'This will be used to check how far down has been copied thus far
    Dim X As Integer, Y As Integer
    Dim NumberOfPasteRows As Long 'This will store how many months there are between dates, to paste into
    Dim PasteCounter As Integer
    Dim dtStart As Date, dtFinal As Date

    Application.ScreenUpdating = False

    Set wkbCrntWorkBook = ActiveWorkbook
    '// Set here Workbook(Sheets) names
    Set GeneratedSheet = wkbCrntWorkBook.Worksheets("APAR Hostname List")
    Set AparSheet = wkbCrntWorkBook.Worksheets("SG APAR")
    wSLastPasteRow = 2
    'extract data from another excel file
    With Application.FileDialog(msoFileDialogOpen)
    .Filters.Clear
    .Filters.Add "Excel 2007-13", "*.xlsx; *.xlsm; *.xls"
    .AllowMultiSelect = False
    .Show

    If .SelectedItems.Count > 0 Then

        'Prompts user to choose which Worksheet they want to copy from
        MSG1 = MsgBox("Do you wish to copy from 'July CEP Server Patch Tracker' ?", vbYesNo, "Name of Worksheet")
        If MSG1 = vbYes Then
            worksheetName = "July CEP Server Patch Tracker"
        Else
            Default = "Sheet"
            worksheetName = Application.InputBox("Enter the name of Worksheet (Case-sensitive)", Default, Default)
        'End of first If statement
        End If

        Set wkbSourceBook = Workbooks.Open(.SelectedItems(1))
        Set WintelSheet = wkbSourceBook.Sheets(worksheetName)

        With WintelSheet

        '//Find the last row of hostname in column A in WintelSheet
        wSlastRow = .Range("A" & .Rows.Count).End(xlUp).Row
        '//Find the last row of APAR No. in column J in AparSheet
        NumberOfPasteRows = AparSheet.Range("J" & .Rows.Count).End(xlUp).Row
        '//Loop through each hostname in WintelSheet
            For X = 2 To wSlastRow
            '// W is the column with patch release date/PATCHED TILL
            If Not IsError(.Range("W" & X).Value) Then
                If IsDate(.Range("W" & X)) Then
                '//Calculate the last day of the month for dates in Column W (dtStart) and first day of the next current month (dtFinal)
                dtStart = DateSerial(Year(.Range("W" & X)), Month(.Range("W" & X)) + 1, 1)
                dtFinal = DateSerial(Year(Now), Month(Now) + 1, 1)
                'Loop though every rows from row 2 in AparSheet to copy rows with dates in range and put hostname in these rows
                For Y = 2 To NumberOfPasteRows
                With AparSheet
                'Find the dates which earlier then dtFinal latter than dtStart
                If .Range("L" & Y).Value >= DateValue(dtStart) And .Range("L" & Y).Value < DateValue(dtFinal) Then
                    'column A is the hostname list in WintelSheet
                        .Range("A" & Y).EntireRow.Copy Destination:=GeneratedSheet.Range("A" & wSLastPasteRow).EntireRow
                        WintelSheet.Range("A" & X).Copy Destination:=GeneratedSheet.Range("B" & wSLastPasteRow)
                        wSLastPasteRow = wSLastPasteRow + 1

                End If
                End With
                Next Y
                End If
            End If
            Next X

        End With
        wkbSourceBook.Close False
    End If
    End With

    'Free objects
    Set wkbCrntWorkBook = Nothing
    Set GeneratedSheet = Nothing
    Set wkbSourceBook = Nothing
    Set WintelSheet = Nothing
    Set AparSheet = Nothing

    Application.ScreenUpdating = True

    '// Simple Msg Box
    MsgBox "Copy & Paste is Done."
End Sub

Here's a few screenshots for the sample data as requested.
WintelSheet:
AparSheet:
GeneratedSheet:

A: A few suggestions for the existing code:

*

*move With AparSheet one line up, so it will run much rarely

*DateValue conversion is an extra step and don't affects the output, delete them and just use: .Range("L" & Y).Value >= dtStart And .Range("L" & Y).Value < dtFinal

*as you use "L" column of ApartSheet quite often, declare it: set columnL =ApartSheet.Range("L1:L" & NumberOfPasteRows)

*probably less crucial in your code, but try to store results of calculations instead of calculating them several times

*

*move dtFinal = DateSerial(Year(Now), Month(Now) + 1, 1) out from the loop

*store dtStart in an array

*if you have any calculation in any of the sheets, switch them off at the beginning of the macro, and switch on after it Application.Calculation = xlCalculationManual
However I also agree with the comments that big change can be achieved by changing logic of your code.

A: To improve performance, it's necessary to decrease number of cell reads (read columns to array), and maximise size of ranges copied at once.
To generate output list:

*

*sort hosts sheet by date ascending

*sort APAR sheet by date ascending

*create output sheet

*pass all three sheets to the following procedure

Sub CopyRows(shHosts  As Worksheet, shApar As Worksheet, shOutPut As Worksheet)
    Dim vApar As Variant, vHosts As Variant
    Dim iRows As Long, iOffset As Long
    Dim i As Integer, j As Integer
    Dim dMaxDate As Date

    On Error GoTo CleanUp

    Application.ScreenUpdating = False

    iRows = shApar.Range("J" & shApar.Rows.Count).End(xlUp).Row
    vApar = shApar.Range("L2:L" & iRows).Value2

    For i = 1 To iRows - 1
      vApar(i, 1) = vApar(i, 1) - Day(vApar(i, 1)) + 1
    Next

    iRows = shHosts.Range("W" & shHosts.Rows.Count).End(xlUp).Row
    vHosts = shHosts.Range("W2:W" & iRows).Value2

    dMaxDate = DateSerial(Year(Date), Month(Date) + 1, 1)
    j = 1
    iOffset = 0
    For i = 1 To UBound(vApar)
      If vApar(i, 1) >= dMaxDate Then Exit For
      While j < UBound(vHosts) And vHosts(j, 1) < vApar(i, 1)
        j = j + 1
      Wend

      If j > 1 Then
         shApar.Range(i+1 & ":" & i+1).Copy
         shOutPut.Range("2:2").Offset(iOffset, 0).Resize(j).PasteSpecial xlPasteValues
         shOutPut.Range("b2:b2").Offset(iOffset, 0).Resize(j).Value2 = shHosts.Range("a2:a" & j+1).Value2
         iOffset = iOffset + j
      End If
    Next i

CleanUp:
    Application.ScreenUpdating = True

End Sub

In sample sheet 123 410 rows were generated in 0.9 second.

A: I think one way to improve efficiency is to Union your ranges until you've hit a condition upon which you then act. I made this small change to a workbook that was deleting 23 of 24 rows for 24 hours worth of data for thousands of rows. Process would take a good 5 minutes if not longer; after the change...was done in an instant.


text:
Q: How to pass in a lambda and have access to a particular set of methods I want to have something like:
 AStaticClass.MakeCall(commonCmds => commonCmds.MethodOfAParticularClass)

So I want to have a lambda expression as an argument and have the delegate list the available set of methods of a particular class that I can access through intellisense with the lambda function. Then make a call to the passed in method.
i.e. commonCmds => commonCmds. {Lists all the methods of a particular class}
and then I want to have a method that makes that call.
I can't figure it out the proper method signature.
So far I have public void MakeCall(Action cmd) {cmd.invoke;} THis obviously does not work. I tried func, Expression and cannot figure it out.
Thank you so much for the help!
EDIT:
CmdsTwo and CmdsOne Can be static. However I would like to my classes up in this way, since it will make a lot my other work much easier.
public void Main(string []args) {
    MyStaticClass.MakeCall(x => x.DoThis);

    MyStaticClass.MakeCallTwo(x => x.DoThisTwo);

    MyStaticClass.MakeCall(x => x.DoThisThree);
}

public static class MyStaticClass{
    public static void MakeCall<???>( ??????)

    public static void MakeCallTwo<???>( ??????)
}

public class Cmds{
    public void DoThis();

    public void DoThisThree();
}

public class CmdsTwo{
    public void DoThisTwo();
}

}

A: The closest i can think of right now is this:
commonCmds => commonCmds.GetType().GetMethods()

This returns you an array of MethodInfo, which describe all methods of the type of commonCmds. You'd have to invoke one of those like this:
object result = someMethodInfo.Invoke(someObjectInstance, new object[] { someParameter });

A: You can check it
AStaticClass.MakeCall( () => commonCmds.MethodOfAParticularClass)

A: You need to use the generic version of Action With A Type.
public void MakeCall(Action<TYPE_HERE> cmd)
{
   cmd.Invoke(...);
}

The type gets inferred and intellisense should kick in.

A: So I got it. Iused an extension method. Thank you.
 public static class MyStaticClass{
     public static void MakeCall(Action<Cmds> paramater){
           Helper(new Cmds(), parameter);
      }

      private static void Helper(this Cmds, Action<Cmds> invokeThis) {...}

     public static void MakeCallTwo<???>( ??????)
 }


text:
Q: Illegal instruction (core dumped) Node.Js I copied my system developed in ExpressJs to the production server.
My system uses HTTPS (SSL).
When the return is 400, 403, 404, or some code purposely so, it responds correctly with a JSON.
When the return should be 200, the node displayed an error in the console "Illegal instruction (core dumped)" and breaks the application.

A: It seems that you copied the node_modules instead of moving everything else and running npm install to install dependencies.
Update: Now after you posted your answer I see that it was precisely the case.
The problem is that some of the modules have compiled binary components that cannot be moved across different architectures. They need to be build every time so you never should copy the node_modules directory.
But if you do copy the node_modules directory or if you update Node.js in your system then instead of removing node_modules and running npm install you can run npm rebuild instead. (Thanks to mscdex for pointing it out in the comments.)

A: I solved the problem, delete the folder node_modules and run npm install


text:
Q: awk command to sum pairs of lines and filter out under particular condition I have a file with numbers and I want to sum numbers from two lines and this for each column, then in my last step I want to filter out pairs of lines that has a count bigger or equal than 3 of '0' sum counts. I write a small example to make it clear:
This is my file (without the comments ofc), it contains 2 pairs of lines (=4 lines) with 5 columns.
2 6 0 8 9  # pair 1.A
0 1 0 5 1  # pair 1.B
0 2 0 3 0  # pair 2.A
0 0 0 0 0  # pair 2.B

And I need to sum up pairs of lines so I get something like this (intermediate step)
2 7 0 13 10 # sum pair 1, it has one 0
0 2 0 3 0   # sum pair 2, it has three 0

Then I want to print the original lines, but only those which the sum of 0 (of the sum of the two lines) is lower than 3, therefore I should get printed this:
2 6 0 8 9  # pair 1.A
0 1 0 5 1  # pair 1.B

Because the sum of the second pair of lines has three 0, then it should be excluded
So from the first file I need to get the last output.
So far what I have been able to do is to sum pairs of lines, count zeros, and identify those with a count lower than 3 of 0 but I don't know how to print the two lines that contributed to the SUM, I am only able to print one of the two lines (the last one). This is the awk I am using:
  awk '
  NR%2 { split($0, a); next }
  { for (i=1; i<=NF; i++) if (a[i]+$i == 0) SUM +=1;
  if (SUM < 3) print $0; SUM=0 }' myfile

(That's what I get now)
0 1 0 5 1 # pair 1.B

Thanks!

A: Another variation, could be useful to avoid loop iterations in some input cases:
awk '!(NR%2){ zeros=0; for(i=1;i<=NF;i++) { if(a[i]+$i==0) zeros++; if(zeros>=3) next }
     print prev ORS $0 }{ split($0,a); prev=$0 }' file

The output:
2 6 0 8 9
0 1 0 5 1

A: Well, after digging a little bit more I found that it was rather simple to print the previous line (I was complicating myself)
  awk '
  NR%2 { split($0, a) ; b=$0; next }
  { for (i=1; i<=NF; i++) if (a[i]+$i == 0) SUM +=1;
  if (SUM < 3) print b"\n"$0; SUM=0}' myfile

So I just have to save the first line in a variable b and print when the condition is favorable.
Hope it can help other people too

A: $ cat tst.awk
!(NR%2) {
    split(prev,p)
    zeroCnt = 0
    for (i=1; i<=NF; i++) {
        zeroCnt += (($i + p[i]) == 0 ? 1 : 0)
    }
    if (zeroCnt < 3) {
        print prev ORS $0
    }
}
{ prev = $0 }

$ awk -f tst.awk file
2 6 0 8 9
0 1 0 5 1


text:
Q: How to get a bearer token using HttpClient? Using Postman I succeeded invoking this api described here https://anypoint.mulesoft.com/exchange/portals/nz-post-group/b8271f09-2ad8-4e1c-b6b1-322c5727d148/nzpost.addresschecker/minor/1.0/pages/Suggest%20Addresses/
but I'm struggling achieving the same with C#.
tried this but didn't work. is this missing any extra header?:
public static async Task<HttpResponseMessage> GetToken()
    {
        var data = new
        {
            client_id = "xxxxxxxxxxxxxxxxxxxxxxxxx",
            client_secret = "xxxxxxxxxxxxxxxxxxxxxx",
            grant_type = "client_credentials"
        };

        var json = JsonConvert.SerializeObject(data);

        var stringContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");

        var client = new HttpClient();
        var response = await client.PostAsync("https://oauth.xxxx.co.nz/as/token.oauth2", stringContent);

        return response;
    }


text:
Q: Multiline xticklabel with pgfplots I'm stuck trying to create multiline xticklabels with PgfPlots...
Here is the example code (you can easily copy/paste it and run it)  :
\documentclass[a4paper, landscape, 10pt, table]{report}

\usepackage[yyyymmdd,hhmmss]{datetime}
\usepackage{array}
\usepackage[T1]{fontenc}
\usepackage{xstring}
\usepackage{ifthen}
\usepackage{readarray}
\usepackage{geometry}
\usepackage{tikz}
\usepackage{pgfplotstable}
\usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{filecontents}{foo.csv}
Index;Start;Data
2;2020-12-23 16:57:47;412.0773923
3;2020-12-23 16:59:00;425.727314
4;2020-12-23 17:00:38;420.1815766
5;2020-12-23 17:01:32;427.3558494
6;2020-12-23 17:02:23;435.2599509
7;2020-12-23 17:03:16;422.8598639
8;2020-12-23 17:04:07;427.1698654
9;2020-12-23 17:05:01;426.6655106
10;2020-12-23 17:05:52;438.6186867
11;2020-12-23 17:06:46;436.1867562
12;2020-12-23 17:07:36;444.5109958
13;2020-12-23 17:08:57;446.4977636
14;2020-12-23 17:09:48;447.1165436
15;2020-12-23 17:10:41;454.8714161
16;2020-12-23 17:11:32;456.5764032
17;2020-12-23 17:12:26;444.5470121
18;2020-12-23 17:13:17;447.9966227
19;2020-12-23 17:14:11;442.5465669
20;2020-12-23 17:15:01;441.6672087
21;2020-12-23 17:15:55;456.5650485
22;2020-12-23 17:16:46;456.7810362
23;2020-12-23 17:17:40;445.482203
24;2020-12-23 17:18:31;449.7298524
25;2020-12-23 17:19:25;460.3123754
26;2020-12-23 17:20:15;461.9648056
27;2020-12-23 17:21:09;462.9873732
28;2020-12-23 17:22:00;456.2594798
29;2020-12-23 17:22:54;457.2116098
30;2020-12-23 17:23:45;459.9223908
31;2020-12-23 17:24:39;461.0290298
32;2020-12-23 17:25:29;459.9460694
33;2020-12-23 17:26:23;449.536673
34;2020-12-23 17:27:14;454.6444983
35;2020-12-23 17:28:08;462.1797674
36;2020-12-23 17:28:59;454.62287
37;2020-12-23 17:29:53;449.687945
38;2020-12-23 17:30:44;455.6168224
39;2020-12-23 17:31:38;464.9462649
40;2020-12-23 17:32:29;459.6818162
41;2020-12-23 17:33:23;463.5861117
42;2020-12-23 17:34:13;469.1470683
43;2020-12-23 17:35:07;466.2078869
44;2020-12-23 17:35:57;461.4459158
45;2020-12-23 17:36:50;456.2636787
46;2020-12-23 17:37:40;464.1252974
47;2020-12-23 17:38:34;464.7491836
48;2020-12-23 17:39:23;459.8645124
49;2020-12-23 17:40:16;455.7546055
50;2020-12-23 17:41:06;461.0567762
51;2020-12-23 17:41:59;464.6463023
52;2020-12-23 17:42:49;467.4802616
53;2020-12-23 17:43:42;459.3240784
54;2020-12-23 17:44:32;466.8316536
55;2020-12-23 17:45:24;469.5408074
56;2020-12-23 17:46:14;465.4033565
57;2020-12-23 17:47:07;473.51648
58;2020-12-23 17:47:56;462.3859205
59;2020-12-23 17:48:49;459.3232076
60;2020-12-23 17:49:39;471.4571371
61;2020-12-23 17:50:31;471.0410186
62;2020-12-23 17:51:21;462.7363749
63;2020-12-23 17:52:13;467.747319
64;2020-12-23 17:53:03;458.7079077
65;2020-12-23 17:53:55;463.3457445
66;2020-12-23 17:54:45;469.0103588
67;2020-12-23 17:55:37;463.3431042
68;2020-12-24 17:56:27;472.3724498
69;2020-12-24 17:57:19;468.9144406
70;2020-12-24 17:58:08;476.6813445
71;2020-12-24 17:59:01;471.2801298
72;2020-12-24 17:59:50;463.2278963
73;2020-12-24 18:00:42;466.0256436
74;2020-12-24 18:01:32;477.221236
75;2020-12-24 18:02:24;477.49307
76;2020-12-24 18:03:14;468.8653761
77;2020-12-24 18:04:06;466.8310255
78;2020-12-24 18:04:56;476.4680725
79;2020-12-24 18:05:48;472.616772
80;2020-12-24 18:06:38;467.5842863
81;2020-12-24 18:07:30;470.9433635
82;2020-12-24 18:08:20;466.4518209
83;2020-12-24 18:09:12;474.2457634
84;2020-12-24 18:10:02;468.8689096
85;2020-12-24 18:10:55;474.6539176
86;2020-12-24 18:11:44;471.2339234
87;2020-12-24 18:12:37;469.0997411
88;2020-12-24 18:13:26;461.762462
89;2020-12-24 18:14:19;471.6879006
90;2020-12-24 18:15:09;469.0627948
91;2020-12-24 18:16:01;470.9495337
92;2020-12-24 18:16:51;478.7524877
93;2020-12-24 18:17:44;479.7872284
94;2020-12-24 18:18:34;482.4520557
95;2020-12-24 18:19:27;470.1152276
96;2020-12-24 18:20:16;480.5053191
97;2020-12-24 18:21:09;477.2644034
98;2020-12-24 18:21:59;480.6109115
99;2020-12-24 18:22:52;484.6098949
100;2020-12-24 20:23:42;478.444049
101;2020-12-24 20:24:36;481.6190172
102;2020-12-24 20:25:26;471.307398
103;2020-12-24 20:26:20;482.3291329
104;2020-12-24 20:27:10;471.2151328
105;2020-12-24 20:28:04;481.4354713
106;2020-12-24 20:28:55;481.6304485
107;2020-12-24 21:29:49;449.311133
\end{filecontents}

% Read measurements data
\pgfplotstableread[col sep=semicolon]{foo.csv}{\variables}

% Data
\begin{tikzpicture}

  % Bottom axis
  \begin{axis}[
      xmin=2, xmax=107,
      ymin=400, ymax=500,
      xtick distance=10,
      xtick pos=bottom,
      xtick align=outside,
      ytick pos=left,
      xlabel=Index,
      width=\textwidth,
      height=0.5\textwidth,
  ]
  \addplot[red] table [x={Index}, y={Data}] {\variables};
  \legend{Data}
  \end{axis}

  % Upper axis with date/time labels
  \begin{axis}[
    xmin=2, xmax=107,
    axis x line*= top,
    axis y line=none,
    xlabel=Date/Time,
    xtick distance=10,
    xtick={0,10,...,100},
    xtick align=outside,
    xticklabel={
      \pgfmathparse{int(round(\tick-2))}
      \pgfplotstablegetelem{\pgfmathresult}{Start}\of{\variables}
      \StrBefore{\pgfplotsretval}{ }[\date]
      \StrBehind{\pgfplotsretval}{ }[\time]
      \date \time
    },
    xticklabel style={align=center},
    grid=none,
    width=\textwidth,
    height=0.5\textwidth]
    \addplot [draw=none] table[x={Index},y={Data}] {\variables};
  \end{axis}
\end{tikzpicture}

\end{document}

And here is the bad result with text overlapping :

I would like to add a new line between date and time.
I tried :
...
\date\\\time
\date\\ \time
\date\newline\time
...

But it doesn't compile.
If I try :
...
\date \\ some string
...

It is ok and I obtain :

Can you explain me what I am doing wrong please ? And why it doesn't work with the \time variable ?
Thanks for your help

A: Seems like the \time macro is "lost" at the line break, though I can't say exactly why. If you repeat the whole date parsing after the \\ it works, i.e.
xticklabel={%
  \pgfmathparse{int(round(\tick-2))}%
  \pgfplotstablegetelem{\pgfmathresult}{Start}\of{\variables}%
  \StrBefore{\pgfplotsretval}{ }[\date]%
  \date\\
  \pgfmathparse{int(round(\tick-2))}%
  \pgfplotstablegetelem{\pgfmathresult}{Start}\of{\variables}%
  \StrBehind{\pgfplotsretval}{ }[\time]\time%
},

\documentclass[a4paper, landscape, 10pt, table]{report}

\usepackage[yyyymmdd,hhmmss]{datetime}
\usepackage{array}
\usepackage[T1]{fontenc}
\usepackage{xstring}
\usepackage{ifthen}
\usepackage{readarray}
\usepackage{geometry}
% \usepackage{tikz}
\usepackage{pgfplotstable} % loads pgfplots which loads tikz, so don't actually need to load those two explicitly
% \usepackage{pgfplots}

\pgfplotsset{compat=newest}

\begin{document}

\begin{filecontents}{foo.csv}
Index;Start;Data
2;2020-12-23 16:57:47;412.0773923
3;2020-12-23 16:59:00;425.727314
4;2020-12-23 17:00:38;420.1815766
5;2020-12-23 17:01:32;427.3558494
6;2020-12-23 17:02:23;435.2599509
7;2020-12-23 17:03:16;422.8598639
8;2020-12-23 17:04:07;427.1698654
9;2020-12-23 17:05:01;426.6655106
10;2020-12-23 17:05:52;438.6186867
11;2020-12-23 17:06:46;436.1867562
12;2020-12-23 17:07:36;444.5109958
13;2020-12-23 17:08:57;446.4977636
14;2020-12-23 17:09:48;447.1165436
15;2020-12-23 17:10:41;454.8714161
16;2020-12-23 17:11:32;456.5764032
17;2020-12-23 17:12:26;444.5470121
18;2020-12-23 17:13:17;447.9966227
19;2020-12-23 17:14:11;442.5465669
20;2020-12-23 17:15:01;441.6672087
21;2020-12-23 17:15:55;456.5650485
22;2020-12-23 17:16:46;456.7810362
23;2020-12-23 17:17:40;445.482203
24;2020-12-23 17:18:31;449.7298524
25;2020-12-23 17:19:25;460.3123754
26;2020-12-23 17:20:15;461.9648056
27;2020-12-23 17:21:09;462.9873732
28;2020-12-23 17:22:00;456.2594798
29;2020-12-23 17:22:54;457.2116098
30;2020-12-23 17:23:45;459.9223908
31;2020-12-23 17:24:39;461.0290298
32;2020-12-23 17:25:29;459.9460694
33;2020-12-23 17:26:23;449.536673
34;2020-12-23 17:27:14;454.6444983
35;2020-12-23 17:28:08;462.1797674
36;2020-12-23 17:28:59;454.62287
37;2020-12-23 17:29:53;449.687945
38;2020-12-23 17:30:44;455.6168224
39;2020-12-23 17:31:38;464.9462649
40;2020-12-23 17:32:29;459.6818162
41;2020-12-23 17:33:23;463.5861117
42;2020-12-23 17:34:13;469.1470683
43;2020-12-23 17:35:07;466.2078869
44;2020-12-23 17:35:57;461.4459158
45;2020-12-23 17:36:50;456.2636787
46;2020-12-23 17:37:40;464.1252974
47;2020-12-23 17:38:34;464.7491836
48;2020-12-23 17:39:23;459.8645124
49;2020-12-23 17:40:16;455.7546055
50;2020-12-23 17:41:06;461.0567762
51;2020-12-23 17:41:59;464.6463023
52;2020-12-23 17:42:49;467.4802616
53;2020-12-23 17:43:42;459.3240784
54;2020-12-23 17:44:32;466.8316536
55;2020-12-23 17:45:24;469.5408074
56;2020-12-23 17:46:14;465.4033565
57;2020-12-23 17:47:07;473.51648
58;2020-12-23 17:47:56;462.3859205
59;2020-12-23 17:48:49;459.3232076
60;2020-12-23 17:49:39;471.4571371
61;2020-12-23 17:50:31;471.0410186
62;2020-12-23 17:51:21;462.7363749
63;2020-12-23 17:52:13;467.747319
64;2020-12-23 17:53:03;458.7079077
65;2020-12-23 17:53:55;463.3457445
66;2020-12-23 17:54:45;469.0103588
67;2020-12-23 17:55:37;463.3431042
68;2020-12-24 17:56:27;472.3724498
69;2020-12-24 17:57:19;468.9144406
70;2020-12-24 17:58:08;476.6813445
71;2020-12-24 17:59:01;471.2801298
72;2020-12-24 17:59:50;463.2278963
73;2020-12-24 18:00:42;466.0256436
74;2020-12-24 18:01:32;477.221236
75;2020-12-24 18:02:24;477.49307
76;2020-12-24 18:03:14;468.8653761
77;2020-12-24 18:04:06;466.8310255
78;2020-12-24 18:04:56;476.4680725
79;2020-12-24 18:05:48;472.616772
80;2020-12-24 18:06:38;467.5842863
81;2020-12-24 18:07:30;470.9433635
82;2020-12-24 18:08:20;466.4518209
83;2020-12-24 18:09:12;474.2457634
84;2020-12-24 18:10:02;468.8689096
85;2020-12-24 18:10:55;474.6539176
86;2020-12-24 18:11:44;471.2339234
87;2020-12-24 18:12:37;469.0997411
88;2020-12-24 18:13:26;461.762462
89;2020-12-24 18:14:19;471.6879006
90;2020-12-24 18:15:09;469.0627948
91;2020-12-24 18:16:01;470.9495337
92;2020-12-24 18:16:51;478.7524877
93;2020-12-24 18:17:44;479.7872284
94;2020-12-24 18:18:34;482.4520557
95;2020-12-24 18:19:27;470.1152276
96;2020-12-24 18:20:16;480.5053191
97;2020-12-24 18:21:09;477.2644034
98;2020-12-24 18:21:59;480.6109115
99;2020-12-24 18:22:52;484.6098949
100;2020-12-24 20:23:42;478.444049
101;2020-12-24 20:24:36;481.6190172
102;2020-12-24 20:25:26;471.307398
103;2020-12-24 20:26:20;482.3291329
104;2020-12-24 20:27:10;471.2151328
105;2020-12-24 20:28:04;481.4354713
106;2020-12-24 20:28:55;481.6304485
107;2020-12-24 21:29:49;449.311133
\end{filecontents}

% Read measurements data
\pgfplotstableread[col sep=semicolon]{foo.csv}{\variables}

% Data
\begin{tikzpicture}

  % Bottom axis
  \begin{axis}[
      xmin=2, xmax=107,
      ymin=400, ymax=500,
      xtick distance=10,
      xtick pos=bottom,
      xtick align=outside,
      ytick pos=left,
      xlabel=Index,
      width=\textwidth,
      height=0.5\textwidth,
  ]
  \addplot[red] table [x={Index}, y={Data}] {\variables};
  \legend{Data}
  \end{axis}

  % Upper axis with date/time labels
  \begin{axis}[
    xmin=2, xmax=107,
    axis x line*= top,
    axis y line=none,
    xlabel=Date/Time,
    xtick distance=10,
    xtick={0,10,...,100},
    xtick align=outside,
    xticklabel={%
      \pgfmathparse{int(round(\tick-2))}%
      \pgfplotstablegetelem{\pgfmathresult}{Start}\of{\variables}%
      \StrBefore{\pgfplotsretval}{ }[\date]%
      \date\\
      \pgfmathparse{int(round(\tick-2))}%
      \pgfplotstablegetelem{\pgfmathresult}{Start}\of{\variables}%
      \StrBehind{\pgfplotsretval}{ }[\time]\time%
    },
    xticklabel style={align=center},
    grid=none,
    width=\textwidth,
    height=0.5\textwidth]
    \addplot [draw=none] table[x={Index},y={Data}] {\variables};
  \end{axis}
\end{tikzpicture}

\end{document}


text:
Q: Component for displaing (>25MB) text file in FLEX Flex front-end using AMF to Java back.
Trying to read, in real-time, a file that is being written to. For example, a log.
I'm using Java's RandomAccessFile class to read the "new" lines of the file and send them back to the UI as a byte array along with the byte offset to start reading from next time.
Using an mx:List to display all lines of the text file.
The problem I'm running into, is Flex, or Flash Player, running out of memory on mildly large files, >25MB.
Is there any preferred method of displaying large amounts of text data in Flex that I'm missing? Or does Flex/Flash just handle this poorly and I'm basically screwed?
Thanks.

A: If 25MB is only mildly large then I'd say you probably need to page the data into the component, and simple store just a couple of pages in memory at a time.  I'd probably pick something like TextArea over List, but creating seamless scrolling for a TextArea could be difficult if you don't have all the data which sounds like what you'll have to do.  So stick with List for now, and figure out how many lines you want to make a page.  And implement your backend as a method like:
// service call interface
public Page getPage( int lineStart, int lines );

// response object from the service call
public class Page {
    private var _totalLines:int;
    private var _lineStart:int;
    private var _lineEnd:int;

    [ArrayElementType("String")]
    private lines:ArrayCollection;
}

Then you can load a page and store X number of pages in memory, but use the totalLines in the file to know how big your model is so the scrollbar can render properly.  You'll just need to build a paging dataprovider that loads pages not yet loaded, and ditches pages if they aren't displayed or pages that are furthest from what's being displayed.

A: Right now I'm working on component that will be able to show up to 100Mb of text fast. You can just replace your mx:TextArea with LongTextArea:
<longText:LongTextArea text="{...}"/>

Download LongTextArea SWC.


text:
Q: How to customize the header of bootstrap I am using bootstrap for my site, I think the black header is not good and the font is too small. How to customize the header of bootstrap ? Is there any example ?

A: It's better to just override the class/id.
Declare the bootstrap first then your own css
<link href="assets/css/bootstrap.css" rel="stylesheet">
<link href="assets/css/mystyle.css" rel="stylesheet">

in your mystyle.css you can:
header,.header,#header{
  background: red;
  color: white;
  font-size: 15px;
}


text:
Q: "Error: Cannot find module html" when visiting HTML page When I started my application, and visited localhost:8333 in my browser, it threw an error:
Error: Cannot find module 'html'
  at Function.Module._resolveFilename (module.js:338:15)
  at Function.Module._load (module.js:280:25)
  at Module.require (module.js:364:17)
  at require (module.js:380:17)
  at new View (C:\Users\fr\node_modules\express\lib\view.js:42:49)
  at Function.app.render (C:\Users\fr\node_modules\express\lib\application.js:483:12)
  at ServerResponse.res.render (C:\Users\fr\node_modules\express\lib\response.js:755:7)
  at allClients (C:\Users\fr\node_modules\apps\chat.js:13:7)
  at callbacks (C:\Users\fr\node_modules\express\lib\router\index.js:161:37)
  at param (C:\Users\fr\node_modules\express\lib\router\index.js:135:11)

Here's my code:
var io = require('socket.io');
var express = require('express');

var app = express(),
http = require('http'),
server = http.createServer(app),
socket = require('socket.io').listen(server);

app.configure(function(){
    app.use(express.static(__dirname));
});
app.get('/', function(req, res, next){
    res.render('./test.html');
});

server.listen(8333);

This is my project folder structure:
node_modules/
    express/
    socket.io/
    apps/
        chat.js
        test.html

This is my new app.configure:
app.configure(function(){
    app.use(express.static(path.join(__dirname, 'public')));
});

But that code fails with this error:
path is not defined

A: I am assuming that test.html is a static file. To render static files, use the static middleware like so:
app.use(express.static(path.join(__dirname, 'public')));

This tells Express to look for static files in the public directory of the application.
Once you have specified this, simply point your browser to the location of the file and it should display.
If, however, you want to render the views, then you have to use the appropriate renderer for it. The list of renderers is defined in the consolidate.js library.
Once you have decided which library to use just install it. I use mustache so here is a snippet of my app file:
var engines = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

This tells Express to—

*

*Look for files to render in the views directory

*Render the files using mustache

*The extension of the file is .html (you can use .mustache too).

A: A simple way is to use the EJS template engine for serving .html files. Put this line right next to your view engine setup:
app.engine('html', require('ejs').renderFile);

A: Install consolidate and mustache by executing the below command in your project folder.
sudo npm install consolidate mustache --save

And make the following changes to your app.js file
var engine = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engine.mustache);
app.set('view engine', 'html');

And now HTML pages will be rendered properly.

A: I think you might need to declare a view engine. If you want to use a view/template engine:
app.set('view engine', 'ejs');

or
app.set('view engine', 'jade');

But to render plain HTML, see this post.

A: Use res.sendFile() instead of res.render(). What you're trying to do is send a whole file.

A: Install the ejs module from npm:
npm install ejs

Then just paste below two lines in your main file (app.js or main.js):
app.set('view engine', 'html');

app.engine('html', require('ejs').renderFile);

A: Try installing the html module from npm:
npm i html


text:
Q: How to send email using php mailer? i have installed php mailer using composer PHPMailer/PHPMailer and i got PHPMailer-Master directory but how and what files can i include to my mail file i.e sendEmail.php.
Here is my sendEmail.php-
include 'What is include paht?'
$mail = new PHPMailer;
$mail->setFrom($email, $name);
$mail->addAddress('dev5.veomit@gmail.com', 'Admin');
$mail->Subject  = 'First PHPMailer Message';
$mail->Body     = 'Hi! This is my first e-mail sent through PHPMailer.';
  if(!$mail->send()) {
   header("Location: https://m-expressions.com/test/voy/");
    }else {
   echo 'Mailer error: ' . $mail->ErrorInfo;
   }

Please help me to complete this code. thanks in advance.

A: If you have installed the PHPMailer via Composer, you should have a vendor folder in your project. Include /vendor/autoload.php


text:
Q: laravel 5.4 varchar field migration When you create a migration and you have a string field like varchar you set it like the code below but I get an error in a migration saying that it's too many bytes
Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('email')->unique();
    $table->timestamps();
});

So if I do this
$table->string('email', 255)->unique();

Setting it to it's maximum of 255 I still get the same error and I'm sure that 255 is the maximum for a varchar field but if I make the field 250 in the varchar field I get no errors. So what's going on with the migrations in laravel 5.4
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `users` add unique `users_email_unique`(`email`))

[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes

A:
Character Encoding

The problem is the Character Encoding on the database. Most likely, you are using a 4 byte encoding. utf8mb4 most likely. If so, 255 (characters) * 4 (byte per char) wont fit the 1000 byte index limit. You mentioned that using 250 removes the problem. That is because it fits the 1000 byte index limit. Try checking your character encoding.

A: There are two solutions for this: Upgrade to MySQL 5.7 or use shorter varchars. If you can't upgrade easily, put this to you AppServiceProvider.php file - it sets the default string length to a value that'll work.
use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

A: I dont think unique can be nullable.
how about this $table->string('slug')->unique();?


text:
Q: How to roll back or uninstall Microsoft patch using WSUS? Is it possible to use WSUS to roll back a patch? Specifically KB2501584?

A: Approve the update - counterintuitive, eh? - for removal.

A: It looks like you should be able to, just choose the Update and choose the Remove option rather than Install. http://technet.microsoft.com/en-us/library/cc720434(WS.10).aspx
However, I'm not sure if you will be able to do this based on the KB description

Note When you remove this security update, you may be prompted to insert the disc that contains Microsoft Office 2003. Additionally, you may not have the option of uninstalling this security update from the Add or Remove Programs item or from the Programs and Features item in Control Panel. There are several possible causes of this issue.


text:
Q: Removing paths from PYTHONPATH in PyCharm not working properly? I'm using PyCharm and I need to remove a few paths in my PYTHONPATH just for a specific conda environment that I already have created.
I followed the steps in this question, but instead of pressing plus (+), I pressed minus (-) on the paths I want to remove. After it, it says "removed by the user" in parentheses at the end of the (supposedly) removed paths.
However, when I call:
sys.path

the paths that sould've been removed are still there.
I tried removing the .idea folder of PyCharm, closing the project and creating a new one, but it seems that this option just doesn't work in PyCharm.
Am I doing something wrong?

A: The team from IntelliJ replied saying it is indeed a known bug. Here's the link to it:
https://youtrack.jetbrains.com/issue/PY-17969
It's 4 years old, so it doesn't seem it's going to be fixed anytime soon. Upvote it for visibility, if you'd like it fixed.


text:
Q: Identifiers in a Diamond Relationship between Tables I have four tables (A,B,C,D) where A is the parent of one to many relationships with B and C.  C and D are parents to a one to many relationship with table D.  Conceptually, the primary keys of these tables could be:

*

*A: Aid

*B: Aid, bnum (with foreign key to A)

*C: Aid, cnum (with foreign key to A)

*D: Aid, bnum, cnum (with foreign keys to B and C)

Where the 'num' columns auto increment based on each parent id in the relationship rather then on each record.   I used this approach on a previous application, and it was not an issue since the creation of B and C records was done by a sequential process by generating a new 'num' value via a 'select max()' query.  I was never really satisfied with the approach, but it got the job done.
For the specific case I am working on now, records in tables A and B are entered by users so auto-generation of id's is not an issue.  In the case of tables C and D, records in these tables are being generated by multiple concurrent batch processes so their identifiers will need to be generated some how.  The previous method I listed will not work do to the race condition.
Note that this is for an Oracle database so I will be using sequences and not auto-increment columns.
Given the constraints above, how you would you design tables to represent A,B,C, and D so that the relationships between the entities are properly enforced AND application code would not be required to generate any identifiers?

A: Sequences or Autonumbers should always be generated by the database system, and not by the application. For MSSQL, this can be done using a stored procedure and returning "select @@identity" from the stored procedure to give the app the ID of the inserted row.
Sequences are great for primary keys imo, but there are camps that worship the god of 'natural keys'.
The meaning of the data stored in the table, and the meaning of the relationship is important to answer your question fully, but relationships can allow for cascading deletions.
Personally, I would make the primary keys sequences in each table and allow for foreign keys that are not part of the primary key.  You would define your tables by the major objects (like employee, merchandise, store), and then the relationships between them would be made up of combinations  So an employee in a store would have a table 'storeemployee' and the primary key would be empid, storeid with no sequence defined. Normally I think about it in terms of things as objects (which always have sequences for primary keys), and relationships between objects (with use other table's IDs as combo-primary keys).
Hope that helps!
Edit: I should add that this nicely allows for diamond relationships.  Think about 'stores' and 'employees'.  One table can be storeemployees, and another can be 'storesales'.  Both would identify a store and an employee, but they mean drastically different things. One is maybe hours worked, and the other is sales made.

A: If I understand it right, you had a solution where you may have
Table A
-------
100
101
102

Table B
-------
100 1
100 2
101 1

Table C
-------
100 1
100 2
101 1

Table D
-------
100 1 1
100 2 1
100 1 2
101 1 1

etc.
Now, does it matter whether the 'num' values are small and in a gap-less sequence?
If not, then simply use sequences for those too. So you may get
Table B
-------
100 29125
100 29138
101 29130

Table D
-------
100 29125 401907
100 29138 404911
101 29130 803888

I'd use separate sequences for bnum and cnum.
On selecting you could (if desired) use something like
SELECT AID,
      RANK(BNUM) OVER (PARTITION BY AID ORDER BY BNUM) bnum_seq,
      RANK(CNUM) OVER (PARTITION BY AID ORDER BY CNUM) cnum_seq


text:
Q: get more data after some given id in firebase I'm new using firebase and I'd like to make an infinite scroll pagination to my posts.
Suppose I have this post IDS:
-M5HMGs3EnBv6O2NSxG
-M5HMGsA3YyW_NJ3fSV
-M5HMGsdfLOOEPPBR_s
-M5HMGsiH9HIZw9DNaz
-M5HMHFYoUX8kNolLrP
-M5HMHFZvDrV27S2hSt
-M5HMHFnrQ_l4mVQ0rX
-M5HMHFoaV8wbexwPCd
-M5HMJQaaFGxF450lJB
-M5HMJQe319R19Cvak6 // THE LAST ONE IN FIRST PAGINATION
-M5HMJQh2gWuah7GSht
-M5HMJQlrcfTTF3fbbI
-M5HMJQo6QT1HwWP2lz
-M5HMJQrIUiZyzhiqK3
-M5HMJQudSkFdvs42D1
-M5HMJRCmbFbxKp1NgA
-M5HMJRFwfo7yN8Is3-
-M5HMJRIsKT3YmoukQ0
-M5HMJRKDTq7XuqtshT
-M5HMJRNRabXbYQUMi6
-M5HMJRS1t9UBzH_3Jh
-M5HMJRXEv6BaPeQPMn
-M5HMJR_bRdxCBy-uma
-M5HMJRdOPBA-SMoMjB

So, first I get the first 10 posts till the id M5HMJQe319R19Cvak6 using this:
var starCountRef = firebase.database().ref('/posts/').limitToFirst(11);

it is ok. When I go to the last post my reactjs will call this function again sending the last loaded post ID (the M5HMJQe319R19Cvak6) in variable pageNumber.
What I'd like to do is get posts after this last id given to continue the pagination, like so:
-M5HMJQh2gWuah7GSht
-M5HMJQlrcfTTF3fbbI
-M5HMJQo6QT1HwWP2lz
-M5HMJQrIUiZyzhiqK3
-M5HMJQudSkFdvs42D1
...

I tried to use startAt(ID) but no result has shown:
var starCountRef = firebase.database().ref('/posts/').limitToFirst(11).startAt(pageNumber);

any ideas how can I get posts after an id in firebase?

A: Firebase Realtime Database queries consists of two steps:

*

*You call one of the orderBy methods to order the child nodes on a specific value.

*You then call one of the filtering methods (startAt, endAt, equalTo) to determine where to start and stop returning data.

Your code does that second step, but fails to do the first step. This means that you're using Firebase's default sort-order, which is by each node's priority. Priorities are a left-over from the days then this API didn't have any better sorting options. These days, you'll always want to call orderBy... before filtering.
With that knowledge, your query for getting the second page of results should look something like:
firebase.database()
  .ref('/posts/')
  .orderByKey()
  .startAt("-M5HMJQe319R19Cvak6")
  .limitToFirst(11)

I highly recommend calling the "-M5HMJQe319R19Cvak6" value something else than pagenumber as that variable name makes it seem as if Firebase queries are offset-based, which they aren't.


text:
Q: How to generate route to pass through polygons? A twist on a standard problem. I'm looking to plot a route through all the wards in London (649). I have all the wards as a shapefile and ideally i wanted to let the computer generate a spiral route staring at the outer edge of london working inward to the centre. My thoughts of how to approach;

*

*Assign each polygon a centroid.

*Generate route to pass though points, outputting a line

*Create a buffer round that line (to select all nearby minor roads)

*Generate final route by rerunning algorithm along the roads

Does that approach seem valid with the tool sets available?
Image of polygons as below


text:
Q: Call javascript on end loading page How to call javascript function at the end of loading page ? I add  at the end of page, but is there any other way ?

A: Use onload

A: Adding it to the end is actually wrong because of the way it may behave with different browsers.
You should add it to the onload event of the body tag.
e.g
<body onload="DoAfterPageLoad()">

A: If you're using jquery, you can use ready()


text:
Q: Python: mock patch a module wherever it is imported from I need to make sure that running unit tests won't trigger calling a heavy outer world function, say, this one:
# bigbad.py
def request(param):
    return 'I searched the whole Internet for "{}"'.format(param)

Multiple modules use this function (bigbad.request) and they import it differently (in real-life it may be imported from an external library as well). Say, there are two modules, a and b, where b depends on a and both use the function:
# a.py, from...import
from bigbad import request

def routine_a():
    return request('a')

# b.py, imports directly
import a
import bigbad

def routine_b():
    resp_a = a.routine_a()
    return 'resp_a: {}, resp_b=request(resp_a): {}'.format(resp_a, bigbad.request(resp_a))

Is there a way to make sure that bigbad.request is not ever called? This code mocks only one of the imports:
# test_b.py
import unittest
from unittest import mock
import b

with mock.patch('bigbad.request') as mock_request:
    mock_request.return_value = 'mocked'
    print(b.routine_b())

Obviously I could refactor b and change the imports but this way I cannot guarantee that someone during the future development is not going to break this provision. I believe tests should test behaviour than implementation details.

A: import bigbad
bigbad.request = # some dummy function

This will work as long as it runs before any module that does from bigbad import request is run/imported. That is, as long as they run after, they will receive the dummy function.

A: # a.py, from...import
from bigbad import request

To ensure that the original request is never called, you'll have to patch all the places where the reference is imported:
import mock
with mock.patch('a.request', return_value='mocked') as mock_request:
    ...

This is tedious, so if possible don't do from bigbad import request in your code, but use import bigbad; bigbad.request.
Another solution: if possible, change bigbad.py:
# bigbad.py
def _request(param):
    return 'I searched the whole Internet for "{}"'.format(param)

def request(param):
    return _request(param)

Then, even if some code does from bigbad import request, you'd be able to do with mock.patch('bigbad._request', return_value='mocked') as mock_request:.

A: For any people coming to this question from the future, I wrote a function to patch all imports of a given symbol.
This function returns a list of patchers for each import of the given symbol (a whole module, a specific function, or any other object). These patchers can then be started/stopped in your test fixture's setup/teardown areas (see the docstring for an example).
How it works:

*

*Iterate through every currently visible module in sys.modules

*If the module's name starts with match_prefix (optional) and does not contain skip_substring (optional), iterate through every local in the module

*If the local is target_symbol, create a patcher for it, local to the module it's imported in

I recommend using an argument like skip_substring='test' so that you don't patch things imported by your test suite.
from typing import Any, Optional
import unittest.mock as mock
import sys

def patch_all_symbol_imports(
        target_symbol: Any, match_prefix: Optional[str] = None,
        skip_substring: Optional[str] = None
):
    """
    Iterate through every visible module (in sys.modules) that starts with
    `match_prefix` to find imports of `target_symbol` and return a list
    of patchers for each import.

    This is helpful when you want to patch a module, function, or object
    everywhere in your project's code, even when it is imported with an alias.

    Example:

    ::

        import datetime

        # Setup
        patchers = patch_all_symbol_imports(datetime, 'my_project.', 'test')
        for patcher in patchers:
            mock_dt = patcher.start()
            # Do stuff with the mock

        # Teardown
        for patcher in patchers:
            patcher.stop()

    :param target_symbol: the symbol to search for imports of (may be a module,
        a function, or some other object)
    :param match_prefix: if not None, only search for imports in
        modules that begin with this string
    :param skip_substring: if not None, skip any module that contains this
        substring (e.g. 'test' to skip unit test modules)
    :return: a list of patchers for each import of the target symbol
    """

    patchers = []

    # Iterate through all currently imported modules
    # Make a copy in case it changes
    for module in list(sys.modules.values()):
        name_matches = (
                match_prefix is None
                or module.__name__.startswith(match_prefix)
        )
        should_skip = (
            skip_substring is not None and skip_substring in module.__name__
        )
        if not name_matches or should_skip:
            continue

        # Iterate through this module's locals
        # Again, make a copy
        for local_name, local in list(module.__dict__.items()):
            if local is target_symbol:
                # Patch this symbol local to the module
                patchers.append(mock.patch(
                    f'{module.__name__}.{local_name}', autospec=True
                ))

    return patchers

For this question specifically, the following code could be used:
from bigbad import request

patchers = patch_all_symbol_imports(request, skip_substring='test')
for patcher in patchers:
    mock_request = patcher.start()
    mock_request.return_value = 'mocked'

print(b.routine_b())

for patcher in patchers:
    patcher.stop()


text:
Q: Git reset --hard and push to remote repository I had a repository that had some bad commits on it (D, E and F for this example).

A-B-C-D-E-F master and origin/master

I've modified the local repository specifically with a git reset --hard.  I took a branch before the reset so now I have a repo that looks like:
A-B-C master
     \ D-E-F old_master

A-B-C-D-E-F origin/master

Now I needed some parts of those bad commits so I cherry picked the bits I needed and made some new commits so now I have the following locally:
A-B-C-G-H master
     \ D-E-F old_master

Now I want to push this state of affairs to the remote repo. However, when I try to do a git push Git politely gives me the brush off:
$ git push origin +master:master --force
Total 0 (delta 0), reused 0 (delta 0)
error: denying non-fast forward refs/heads/master (you should pull first)
To git@git.example.com:myrepo.git
! [remote rejected] master -> master (non-fast forward)
error: failed to push some refs to 'git@git.example.com:myrepo.git'

How do I get the remote repo to take the current state of the local repo?

A: If forcing a push doesn't help (git push --force origin or git push --force origin master should be enough), it might mean that the remote server is refusing non fast-forward pushes, via either  receive.denyNonFastForwards config variable (see git config manpage for description), or via an update/pre-receive hook.
With older Git you can work around that restriction by deleting git push origin :master (note the : before branch name) and then re-creating git push origin master given branch.
If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:
A-B-C-D-E-F-[(D-E-F)^-1]   master

A-B-C-D-E-F                origin/master

A: For users of GitHub, this worked for me:

*

*In any branch protection rules where you wish to make the change, make sure Allow force pushes is enabled

*git reset --hard <full_hash_of_commit_to_reset_to>

*git push --force
This will "correct" the branch history on your local machine and the GitHub server, but anyone who has sync'ed this branch with the server since the bad commit will have the history on their local machine. If they have permission to push to the branch directly then these commits will show right back up when they sync.
All everyone else needs to do is the git reset command from above to "correct" the branch on their local machine. Of course they would need to be wary of any local commits made to this branch after the target hash. Cherry pick/backup and reapply those as necessary, but if you are in a protected branch then the number of people who can commit directly to it is likely limited.

A: Instead of fixing your "master" branch, it's way easier to swap it with your "desired-master" by renaming the branches.  See https://stackoverflow.com/a/2862606/2321594. This way you wouldn't even leave any trace of multiple revert logs.

A: To complement Jakub's answer, if you have access to the remote git server in ssh, you can go into the git remote directory and set:
user@remote$ git config receive.denyNonFastforwards false

Then go back to your local repo, try again to do your commit with --force:
user@local$ git push origin +master:master --force

And finally revert the server's setting in the original protected state:
user@remote$ git config receive.denyNonFastforwards true

A: The whole git resetting business looked far to complicating for me.
So I did something along the lines to get my src folder in the state i had a few commits ago
# reset the local state
git reset <somecommit> --hard
# copy the relevant part e.g. src (exclude is only needed if you specify .)
tar cvfz /tmp/current.tgz --exclude .git  src
# get the current state of git
git pull
# remove what you don't like anymore
rm -rf src
# restore from the tar file
tar xvfz /tmp/current.tgz
# commit everything back to git
git commit -a
# now you can properly push
git push

This way the state of affairs in the src is kept in a tar file and git is forced to accept this state without too much fiddling basically the src directory is replaced with the state it had several commits ago.


text:
Q: Add element to XAML page whiles in Task.Delay() I'm building a chatbot app with chat bubbles for incoming and outgoing messages. For the incoming messages, I've given it a Task.Delay() and now I'd like to give it an ActivityIndicator every time before the message pops up (i.e. I want to show the activity indicator whiles the message is being delayed). I've added the activity indicator to the XAML of the incoming messages control;
IncomingMessageItemControl
<ViewCell
    x:Class="BluePillApp.Controls.IncomingMessageItemControl"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:pancake="clr-namespace:Xamarin.Forms.PancakeView;assembly=Xamarin.Forms.PancakeView"
    mc:Ignorable="d">

    <Grid x:Name="Gridoo">
        <pancake:PancakeView
            Margin="10,10,80,10"
            Padding="15"
            BackgroundColor="#53ffc6"
            CornerRadius="20,20,0,20"
            HasShadow="False"
            HorizontalOptions="StartAndExpand">

            <Label
                FontSize="Medium"
                Text="{Binding Text}"
                TextColor="#1a1a1a" />
        </pancake:PancakeView>

        <ActivityIndicator IsRunning="True" IsVisible="True" />
    </Grid>
</ViewCell>

The problem is, in the ChatbotMessagingPage, the send button is pressed then an outgoing message is sent before getting a reply/incoming message and I've done this in MVVM like so;
ChatbotMessagingPageViewModel
//This gets the chatbots response for each message
            chatbot.MainUser.ResponseReceived += async (sender, args) =>
            {
                await Task.Delay(1500);
                Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
            };
        }

        #region CLASS METHODS
        /// <summary>
        /// This function sends a message
        /// </summary>
        public void Send()
        {
            if (!string.IsNullOrEmpty(TextToSend))
            {
                var msgModel = new ChatMessageModel() { Text = TextToSend, User = App.User };

                //This adds a new message to the messages collection
                Messages.Add(msgModel);

                var result = chatbot.Evaluate(TextToSend);
                result.Invoke();

                //Removes the text in the Entry after message is sent
                TextToSend = string.Empty;
            }
        }

Everytime I press the send button the ActivityIndicator comes along with the IncomingMessage, I'd like the ActivityIndicator to come first, whiles the IncomingMessage is being delayed.

A: I'm guessing that that view cell is the message bubble.
When you do:
Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });

Your collection is updated and your ListView or whatever hold those ViewCelss is also updated. The ActivityIndicator is part of the ViewCell so it comes at the same time as the message.
[OPTION 1] Using an additional flag
What you can do is create a flag IsBusy or IsDelay or something and bind the visibility of the ActivityIndicator and Label to it:
<Grid x:Name="Gridoo">
    <pancake:PancakeView
        Margin="10,10,80,10"
        Padding="15"
        BackgroundColor="#53ffc6"
        CornerRadius="20,20,0,20"
        HasShadow="False"
        HorizontalOptions="StartAndExpand">

        <Label
            FontSize="Medium"
            Text="{Binding Text}"
            TextColor="#1a1a1a"
            IsVisible="{Binding IsBusy, Converter={Helpers:InverseBoolConverter}}""> />
    </pancake:PancakeView>

    <ActivityIndicator x:Name="activityIndicator" IsRunning="True" IsVisible="{Binding IsBusy}" />
</Grid>

Note that I've used a IValueConverter to negate the value for the label. In case you're not familiar with it, check this
What's left is to add the flag in your ViewModel:
IsBusy = true; // this will make the activity indicator visible, but not the Label
// Also note that you first need to add the message
Messages.Add(new ChatMessageModel() { Text = args.Response.Text, User = App.ChatBot });
await Task.Delay(1500);
IsBusy = false; // this will hige the activity indicator visible, and make Label visible

So basically the logic is the following:

*

*You add the message to your chat BUT the actual text is hidden when on the other hand, the activity indicator is visible.

*You apply the delay

*Delay ends, you change the visibility of both views.

Note that in my example I've not declared where that flag is since I'm not sure how the rest of your code looks like. It could be added to ChatMessageModel or ChatMessageViewModel since you would need a flag for each message.
[OPTION 2] in IncomingMessageItemControl.xaml.cs
A better solution could be to handle it in the code behind of your control. The issue is the same, the activity indicator and the label comes at the same time.
To fix this you can move the delay in IncomingMessageItemControl.xaml.cs.
First, you need to add x:Name to both the activity indicator and the label.
Then you could do:
private async Task ChangeVisibilityAsync()
{
    Label.IsVisibe= false;
    ActivityIndicator.IsVisible = true;
    await Task.Delay(1500);
    Label.IsVisibe = true;
    ActivityIndicator.IsVisible = false;
}


text:
Q: XML snippet with substitution crashing sublime text 3 I'm trying to write a sublime xml snippet but I have two problems.
First the completions aren't showing up for xml files so the only way I can activate the snippet is with cmd-shift-p. They work in other file types so not sure why this is.
More importantly though I'm using regex in the snippet to force input text to uppercase which I can get to work in the following scenario:
<content><![CDATA[
    lower: $1 and upper: ${1/(.*)/\U\1/}
]]></content>

but if I try to do it with uppercase only:
<content><![CDATA[
    upper only: ${1/(.*)/\U\1/}
]]></content>

ST3 crashes.
I assume you need to have text to replace and thats why it crashes but is there another way to do this?
Also I'm assuming this is a bug and sublime should throw an error instead of shutting down... (I have seen a bug report somewhere for this)

A: In default settings, the completion pop-up is not available for the text scope. You can add the scope (or only text.xml) to auto_complete_selector in your user settings.
About your main problem, I'd probably report this as a bug on the Sublime Text forums.


text: Q: Can CLT be invoked to perform T-tests and other parametric tests on samples from a population that has non-normal distribution? I have data (about 1150 data points) and it is not normally distributed. Within this sample I want to compare means of two groups and see if they are significantly different. Can I use T-test for it, considering the fact that sampling distribution is normally distributed?


text:
Q: Apache .htaccess How to convert to nginx htaccess? apache .htaccess
<IfModule mod_rewrite.c>
  Options +FollowSymlinks -Multiviews
  RewriteEngine On

  RewriteCond %{HTTP:Authorization} ^(.+)$
  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteRule ^(.*)$ index.php?/$1 [QSA,PT,L]
</IfModule>

Please help me. This problem has bothered me for 3 days. Thank you very much
I try to convert it into the following
if (!-e $request_filename){
    rewrite ^/(.*)$  /index.php/$1  last;
}

Authorization cannot be obtained correctly on nginx,Can cause CORS problems
I think it's because this sentence hasn't been converted successfully
  RewriteCond %{HTTP:Authorization} ^(.+)$
  RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

because I don't know how to convert it
Please help me
I expect to get the converted nginx htaccess

A: The .htaccess you're seeking to convert is quite standard "front controller" pattern. What it does is, for any URI, it will attempt to:

*

*serve the file matching the exact URI

*if the file wasn't found in the previous step, then check a directory, and attempt to serve from there (subject to index directives or further rewrites)

*if the directory wasn't found, route the request to index.php
The de-facto standard NGINX snippet that does the same, utilizes try_files directive.
You'll find this used for virtually all PHP-based CMS configs for NGINX:
location / {
    try_files $uri $uri/ /index.php$is_args$args;
}

The try_files directive, similar to if when being checked for file existence, has its performance pitfalls, so in fact, you may want to do as the article says is route unconditionally all request via PHP-FPM by default, then some (e.g. static assets) served by NGINX directly. Example bare-bones config for WordPress which illustrates the idea:
index index.html index.php;
location / {
    fastcgi_param SCRIPT_FILENAME $document_root/index.php;
    include fastcgi_params;
    # override SCRIPT_NAME which was set in fastcgi_params
    fastcgi_param SCRIPT_NAME /index.php;
    fastcgi_pass unix:/var/run/php-fpm/example.com.sock;
}
location /wp-content/ { }

In this case /wp-content/ is allocated as an empty location in order to ensure NGINX does not pass requests to files in it via PHP-FPM. It will serve everything directly for static files.
Thus the URL rewriting is actually eliminated, and all the performance penalty that comes with it is negated.

A: This is the answer
if (!-f $request_filename) {
    rewrite ^(.*)$ /index.php?s=/$1 last;
    break;
}

if (!-d $request_filename) {
    rewrite ^(.*)$ /index.php?s=/$1 last;
    break;
}


text:
Q: Configuring Jenkins and Perforce to automatically run my my junit tests I am trying the get Jenkins configured with Perforce so I can automate my junit tests build automatically.
See screen shot for my configuration.

This is Perforce Install Configuration:

But I get an exception:
Building in workspace <http://host:8080/job/Critical%20Events%20Tool/ws/>
Using master perforce client: FRA_Jenkins_CriticalTool [workspace] $ "C:\Program     Files\Perforce\p4.exe" workspace -o FRA_Jenkins_CriticalTool [workspace] $ "C:\Program Files\Perforce\p4.exe" login -a -p [workspace] $ "C:\Program Files\Perforce\p4.exe" -P AEA1F4274926EC4525326163DF42D5A4 workspace -o FRA_Jenkins_CriticalTool Changing P4 Client Root to: <http://localhost:8080/job/Critical%20Events%20Tool/ws/>
Changing P4 Client View from:
-//something/... //FRA_Jenkins_CriticalTool/...
//something/PPS/... //FRA_Jenkins_CriticalTool/PPS/...
-//something/* //FRA_Jenkins_CriticalTool/*

Changing P4 Client View to:
  //something/PPS/CriticalEventTool/ //FRA_Jenkins_CriticalTool/PPS/CriticalEventTool/
Saving modified client FRA_Jenkins_CriticalTool [workspace] $ "C:\Program Files\Perforce\p4.exe" -P AEA1F4274926EC4525326163DF42D5A4 -s client -i Caught exception communicating with perforce.  Error in client specification. Error detected at line 9. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'

    For Command: C:\Program Files\Perforce\p4.exe -P AEA1F4274926EC4525326163DF42D5A4 -s client -i With Data:
Client: FRA_Jenkins_CriticalTool
Owner: user1
Description: Created by user1.
Root: <http://localhost:8080/job/Critical%20Events%20Tool/ws/>
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
SubmitOptions: submitunchanged
LineEnd: local
View:
  //something/PPS/CriticalEventTool/ //FRA_Jenkins_CriticalTool/PPS/CriticalEventTool/

===================
com.tek42.perforce.PerforceException:  Error in client specification. Error detected at line 9. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'.
For Command: C:\Program Files\Perforce\p4.exe -P AEA1F4274926EC4525326163DF42D5A4 -s client -i
With Data:
===================
Client: FRA_Jenkins_CriticalTool
Owner: user1
Description: Created by user1.
Root: <http://localhost:8080/job/Critical%20Events%20Tool/ws/>
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
SubmitOptions: submitunchanged
LineEnd: local
View:
  //something/PPS/CriticalEventTool/ //FRA_Jenkins_CriticalTool/PPS/CriticalEventTool/

===================

at com.tek42.perforce.parse.AbstractPerforceTemplate.saveToPerforce(AbstractPerforceTemplate.java:270)
at com.tek42.perforce.parse.Workspaces.saveWorkspace(Workspaces.java:77)
at hudson.plugins.perforce.PerforceSCM.saveWorkspaceIfDirty(PerforceSCM.java:1790)
at hudson.plugins.perforce.PerforceSCM.checkout(PerforceSCM.java:895)
at hudson.model.AbstractProject.checkout(AbstractProject.java:1320)
at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:609)
at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:88)
at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:518)
at hudson.model.Run.execute(Run.java:1700)
at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
at hudson.model.ResourceController.execute(ResourceController.java:88)
at hudson.model.Executor.run(Executor.java:231)
ERROR: Unable to communicate with perforce.  Error in client specification. Error detected at line 9. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'. Null directory (//) not allowed in '//something/PPS/CriticalEventTool/'.
For Command: C:\Program Files\Perforce\p4.exe -P AEA1F4274926EC4525326163DF42D5A4 -s client -i
With Data
===================
Client: FRA_Jenkins_CriticalTool
Owner: user1
Description: Created by user1.
Root: <http://localhost:8080/job/Critical%20Events%20Tool/ws/>
Options: noallwrite clobber nocompress unlocked nomodtime rmdir
SubmitOptions: submitunchanged
LineEnd: local
View:
  //something/PPS/CriticalEventTool/ //FRA_Jenkins_CriticalTool/PPS/CriticalEventTool/

Whats wrong and How can I automate my junit tests build automatically?

A: I believe you just need to add "..." at the end of your ViewMap, so that it reads //something/PPS/CriticalEventTool/...


text:
Q: How to keep only one standard currency symbol ($) when changing cultures? How can I make the web app only to display currency in dollars, regardless of the language/country selected ?
SetCulture(string culture)
   {
     CultureInfo.DefaultThreadCurrentCulture = new CultureInfo(culture);
     CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(culture);
   }

Text = String.Format("{0:C}", item.TotCostDay);

A: You can try creating a Clone of current culture with NumberFormat.Currency... modified:
CultureInfo culture = CultureInfo.CurrentCulture.Clone() as CultureInfo;

CultureInfo usCulture = CultureInfo.GetCultureInfo("en-US");

// Dollar symbol - $
culture.NumberFormat.CurrencySymbol = usCulture.NumberFormat.CurrencySymbol;

// And (may be) some US currency patterns
culture.NumberFormat.CurrencyDecimalDigits = usCulture.NumberFormat.CurrencyDecimalDigits;
culture.NumberFormat.CurrencyPositivePattern = usCulture.NumberFormat.CurrencyPositivePattern;
culture.NumberFormat.CurrencyNegativePattern = usCulture.NumberFormat.CurrencyNegativePattern;

CultureInfo.CurrentCulture = culture;


text:
Q: Error 3033: Prblm in mapping fragments: EntitySets 'Entity1' and 'Entity2' are both mapped to table 'Addresses'. Their primary keys may collide Context. I want to separate a shipping table into two tables, the first one for general data about the shipping that are most frequently used and in the second table to store the pickup and destination addresses in different records with a selector field RecordType, in order to retrieve the addresses information only when is required. For that purpose, I created three entities, the entity Move for the shipping general information, the entity pick up address and the entity destination address, the last two entities have an additional field "address type" to distinguish which is pickup and which is destination.
With the mapping details screen in the model I mapped both entities, the PickupAddress, and DestinationAddress to the same table MoveAddresses, PickupAddress with codition recordtype ="P" and DestinationAddress with condition recordtype = "D".
When I rebuild the datalayer solution I got the following errors
Error   2   Error 3032: Problem in mapping fragments starting at line 625: Condition member 'MoveAddresses.AddressType' with a condition other than 'IsNull=False' is mapped. Either remove the condition on DestinationAddresses.AddressType or remove it from the mapping.

Error   4   Error 3033: Problem in mapping fragments starting at line 647: EntitySets 'PickupAddresses' and 'DestinationAddresses' are both mapped to table 'MoveAddresses'. Their primary keys may collide.

A: What you are trying to implement is Table per Hierarchy.  From your description, it sounds like you are using the Entity Framework Designer surface.  To model Table per Hiearchy in the Entity Framework Designer is a multiple step process.

*

*Create an Entity which represents the Table which will hold the multiple bound entities (in your case, create an Address entity with Addresses entity set, matching the entire Addresses Table).  Forget about the Move Table for the moment, you only care at the moment about the table sharing data.

*Right click the designer surface, Add -> Entity, set the Base type of each Derived entry to Address i.e. PickupAddress Derived from Address

*Cut and paste any specific entries that belong to each derived entity, removing them from the base entity and pasting them into the derived entity.  i.e. pickup date moved from Address to PickupAddress.

*Delete the Descriminator property from the base entity.  it isn't actually a property which can be used directly by the entities.

*Right click each derived entity, choose table mapping.  choose the base table for the mapping, and set the discriminator values.

*Now you are ready to create entity relationships between your derived classes and your other table as necessary.


text:
Q: I have the location in the HTML page. How to get the id or any other attributes of the element at that position I have the location of an object in a web page.
In selenium, we can get the location of an element as shown in the code below.
I want to know how the reverse could be done in python.
str = driver.find_elements_by_tag_name("input")

for i in str:

    print(i.location)

A: Using Java script I got this.
driver = webdriver.Chrome()
driver.execute_script('el = document.elementFromPoint(1285, 19); return el')
ele.wrapped_element.get_attribute("class")


text:
Q: How to deal with query parameter's encoding? I assumed that any data being sent to my parameter strings would be utf-8, since that is what my whole site uses throughout. Lo-and-behold I was wrong.
For this example has the character ä in utf-8 in the document (from the query string) but proceeds to send a B\xe4ule (which is either ISO-8859-1 or windows 1252) when you click submit. It also fires off a ajax request which also fails from trying to decode the non-utf8 character.
An in django, my request.POST is really screwed up :
>>> print request.POST
<QueryDict: {u'alias': [u'eu.wowarmory.com/character-sheet.xml?r=Der Rat von Dalaran&cn=B\ufffde']}>

How can I just make all these headaches go away and work in utf8?

A: Since Django 1.0 all values you get from form submission are unicode objects, not bytestrings like in Django 0.96 and earlier. To get utf-8 from your values encode them with utf-8 codec:
request.POST['somefield'].encode('utf-8')

To get query parameters decoded properly, they have to be properly encoded first:
In [3]: urllib.quote('ä')
Out[3]: '%C3%A4'

I think your problem comes from bad encoding of query parameters.

A: You should also add accept-charset="UTF-8" to the <form/> tag.

A: Although it's AFAIK not specified anywhere, all browsers use the character encoding of the HTML page, on which the form is embedded as the encoding for submitting the form back to the server. So if you want the URL parameters to be UTF-8-encoded, you have to make sure that the HTML page, on which the form is embedded, is also UTF-8 encoded.

A: According to Get non-UTF-8-form fields as UTF-8 in PHP?, you'll need to make sure the page itself is served up using UTF8 encoding.

A: Getting an utf-8 string from the submitted form should just be a matter of encoding the
unicode object:
next = request.POST['next'].encode('utf-8')
For the AJAX request, can you confirm that that request is also being sent as utf-8 and declared as utf-8 in the headers?


text:
Q: Sentiment analysis using bigrams So I have some reviews that I am trying to classify into positive or negative. I am trying to use NLTK and Stanford coreNLP to do so. I am able to do it on unigrams but its not working for bigrams. I tried the following for bigrams
def classifySentence(sen):
  wn_lem = WordNetLemmatizer()
  pos = 0
  neg = 0
  stop_words = set(stopwords.words('english'))
  filtered_review = [token for token in nltk.word_tokenize(sen) if not token in stop_words]

  for token in nltk.bigrams(filtered_review):
      #lemma = wn_lem.lemmatize(token)
      # print("lemma="+token)
      if len(wn.synsets(token))>0:
          synset = wn.synsets(token)[0]
          #print("synset.name="+synset.name())

          sent = swn.senti_synset(synset.name())

          #print("Sentiment of "+token+" "+str(sent))

          pos = pos + sent.pos_score()
          neg = neg + sent.neg_score()
          # print (token + "(pos_score): " + str(pos) +"\n")
          # print (token + "(neg_score): " + str(neg) +"\n")
  #print (filtered_review)
  JoinedTokens = ' '.join(wo for wo in filtered_review)
  return [JoinedTokens, pos, neg]

I was wondering if someone could suggest me ways to do this. I would like to use NLTK or can also use stanfordcoreNLP. I am also open to using other python packages but just need some guidance
I have written some code for using it but it didn't work either. The code I wrote
def StanfordBigrams():
  nlp = StanfordCoreNLP('http://localhost:9000')
  operations = {'annotators': 'tokenize,lemma,pos,sentiment', 'outputFormat': 'json'}
  string = "not bad"
  tok = nltk.word_tokenize(string)
  bigrams = nltk.bigrams(tok)
  res = nlp.annotate(str(bigrams),operations)
  for s in res["sentences"]:
          for token in s["tokens"]:
              print("Sentiment: "+str(s["sentiment"])+"SentimentValue: "+str(s["sentimentValue"]))
              print (token)

I would be grateful if someone could point me in the right direction.

A: Are you training a sentiment classifier, or just trying to use one? Technically, I suspect your error is in wn.synset(bigram) -- I doubt the thing returned from nltk.bigrams is a word that can be passed into WordNet.
But, more importantly, you probably want to pass your whole sentence into a sentiment classifier -- bigrams aren't going to have sentiments annotated on them in things like SentiWordNet, and the trained sentiment classifiers are going to have a much easier time on sentences than they are on short snippets. You should be able to get sentiment for some of the bigrams in the sentence from Stanford's sentiment tree (vs just the sentiment value at the root). See the sentimentTree field on the JSON output from the CoreNLP server.


text:
Q: Why is RSpec lying to me about errors on my active model object? code
class Foo
  include ActiveModel::Validations

  def bar
    errors.add(:base, 'WHAT THE HELL!?')
  end
end

spec
describe 'nonsense' do
  specify do
    foo = Foo.new
    foo.bar
    expect(foo).to have(1).error_on(:base)
  end
end

output
 Failure/Error: specify { expect(foo).to have(1).error_on(:base) }
   expected 1 error on :base, got 0

real proof of nonsense:
describe 'nonsense' do
  specify do
    foo = Foo.new
    foo.bar
    pus foo.errors.inspect
    expect(foo).to have(1).error_on(:base)
  end
end

===>
#<ActiveModel::Errors:0x00000109ba51a8 @base=#<Foo:0x00000109ba51f8 @errors=#<ActiveModel::Errors:0x00000109ba51a8 ...>>, @messages={:base=>["WHAT THE HELL!?"]}>

omg...

A: It appears that if you don't call the "valid?" method prior to using the "have(n).errors_on" matcher in a spec, it will always return false, even if your errors object has stuff in it!


text:
Q: Ajax dynamic S_SESSION generating doesnt update the SESSION values I have ajax autocomplete for search field that searches for related products. In order not to show a products already associated with the product I made this function:
function getRelatedProducts($pid){
$str='SELECT distinct related_id FROM related_products WHERE product_id="'.$pid.'" ';
$result=mysql_query($str) or die('Mysql Error:'.mysql_error().'<br /> Query:'.$query);
$num_rows=mysql_num_rows($result);
$str='';
for($i=0;$i<$num_rows;$i++){
    $row=mysql_fetch_row($result);
    if($i==0) $str=$row[0];
    else $str.=','.$row[0];
}
return $str;
}
$_SESSION['related_products']=getRelatedProducts($_GET['id']);

This way I am storing the new array values of products ids that are already assoc with the product..
After that here is the autocomplete search query:
$query = "SELECT id,bg_product_name,model FROM products WHERE
(bg_product_name LIKE '%".$q."%' or model LIKE '%".$q."%') AND
active='1' and id NOT IN ('".$_SESSION['related_products']."') group by id LIMIT 11";

but the query always shows same products - even they are already assoc with the product.. Please help me to find where I am wrong..
Thank you in advance

A: You're putting quotes around the entire related_products list, so it's not treating it as a list of things to exclude, it's just one value. Assuming related_id is an integer, use:
$query = "SELECT id,bg_product_name,model
          FROM products
          WHERE
            (bg_product_name LIKE '%".$q."%' or model LIKE '%".$q."%')
            AND
            active='1' and id NOT IN (".$_SESSION['related_products'].")
          group by id
          LIMIT 11";


text:
Q: forcing sudo on remote rsync server I'm setting up rsync to transfer files from ServerA to ServerB, and need to preserve timestamps and permissions.   They key here is the files are owned by a different account than the one performing the file transfer.
rsync transfers files using the example below:
rsync -a /colorschemes/ acoder@bu.my.box.net:/colorschemes/ --delete

The -a flag yields the following types of errors:
rsync: failed to set times on "/colorschemes/946/ex": Operation not permitted (1)
rsync: failed to set permissions on "/colorschemes/946/ex/blue.pdf": Operation not permitted (1)

On the remote system, the acoder account has a similar error when attempting to manually set permissions on a file:
[acoder@bu ~]$ chown apache:codingteam /colorschemes/946
chown: changing ownership of '/colorschemes/946': Operation not permitted

This works OK, though:
[acoder@bu ~]$ sudo chown apache:codingteam /colorschemes/946

Is there a way to make the remote rsync use sudo?

A: For using sudo with rsync in remote machine you can call it with --rsync-path="sudo rsync" but be aware of the require TTY, you skip it by removing Defaults requiretty from sudoers file.
If you want to change the permission for anything you don't own, you have to use sudo if you were not root
or there is a different way like setting a setuid on chmod, chown then any one can run the chmod, chown as a root, but that will be horrible.


text:
Q: applying CSS to the IDs that are created dynamically I have a problem applying CSS to ID that are created dynamically in my Javascript (using DOM). I have a code which creates 'div' blocks and their respective IDs. The IDs look something like this cg1cp1, cg2cp1, cg3cp2, cg3cp3etc... based on the user input (I have counters to generate them and it goes on indefinitely until the user stops clicking and creating new ones). In another section of 'div' blocks where the ID go like this cg1, cg2, cg2, cg4,... etc. I've managed to apply CSS specifically to these by using code that looks something like this
    <style>
        [id^="cg"]{
            position : relative;
            top : 10px;
        }
    </style>

So I was wondering if there are any CSS constructs that can be used to apply CSS to variable IDs.

A: Yes, you can use classes :) just add the same class to all ids of the same group:
element.id = 'cg' + i + 'cp' + j
element.classList.add('cgcp')

Then on your css:
.cgcp { color: red; }


text:
Q: Visual studio code is not stacking rows I am a begginer I have a problem with visual studio until now I have been working on my laptop on Windows 10 and all was great, now I have transferred to new pc and vs is not stacking rows, after I press save nothing happens. My code is not sorting out it just stays scattered.
Help pls.