text:
Q: how to use predicate into a join statement I am trying to allow my users to construct their own queries. I found this code which seems to solve this problem:
var predicate = PredicateBuilder.True<T1>();

if (a != "")
    predicado = predicado.And(e1 => e1.field1.Contains(a));

if (b!= "")
    predicado = predicado.And(e1 => e1.field2.Contains(b));

var TestQuery = db.T1.AsExpandable().Where(predicate).ToList();

These are my model classes:
public partial class T1
{
    public long id_t1 { get; set; }

    public string field1 { get; set; }

    public string field2 { get; set; }
}

public partial class T1
{
    public long id_t2 { get; set; }

    public string field1 { get; set; }

    public string field2 { get; set; }
}

But i need a way to use the PredicateBuilder in a join statement like this one:
var query = from f in db.T1
    where (f.T1field1.Equals("something") && f.T1field2.Equals("something"))
    join m in db.T2 on f.T1field1 equals m.T2field1
    where (m.T2fiel1 != null && m.T2field2 != null )
    select m;


text:
Q: JQuery + CKEditor calling stylesSet.add method Getting stumped trying to figure out how to call the stylesSet.add method when using CKEditor's jquery adapter.
Right now my initiation code is:
$( '.ckeditor' ).ckeditor(
    function() {
        /* callback code */
    },
    {
        ... config options
    }
);

I've tried adding this to both the config settings and callback with no luck. Not sure how to add this method in

redpajama_set_name: RedPajamaStackExchange


text:
Q: USB Linux Device Driver I'm  trying to learn Unix kernel development and I'm asked to "play around with the usb driver code and learn things".
where should I start?
Thanks in advance!

A: First go through basics of USB
Try to understand USB document from free electronic website
After that go to Linux kernel document
Continuously try to go through Linux kernel codes in USB module and corelate with document contains.
If any board is available then try to put debugs in kernel code, dump to board and observe the code flow for different USB devices.

A: I think you should start with learning USB protocol first and then analysing usb linux drivers. Read the usb specifications from www.usb.org.


text:
Q: dplyr: group mean centering (mutate + summarize) What is the efficient/preferred way to do group mean centering with dplyr, that is take each element of a group (mutate) and perform an operation on it and a summary stat (summarize) for that group.  Here's how one might do group mean centering on mtcars using base R:
do.call(rbind, lapply(split(mtcars, mtcars$cyl), function(x){
    x[["cent"]] <- x$mpg - mean(x$mpg)
    x
}))

A: You can try
library(dplyr)
mtcars %>%
      add_rownames()%>% #if the rownames are needed as a column
      group_by(cyl) %>%
      mutate(cent= mpg-mean(mpg))

A: It appears that the above code use the global mean to center the mpg; how should I do if I want to center at the within group mean, i.e. the mean values of each cyl group level are different.
> mtcars %>%
+   add_rownames()%>% #if the rownames are needed as a column
+   group_by(cyl) %>%
+   mutate(cent= mpg-mean(mpg))%>%
+   dplyr ::select(cent)
Adding missing grouping variables: `cyl`
# A tibble: 32 x 2
# Groups:   cyl [3]
     cyl   cent
   <dbl>  <dbl>
 1     6  0.909
 2     6  0.909
 3     4  2.71
 4     6  1.31
 5     8 -1.39
 6     6 -1.99
 7     8 -5.79
 8     4  4.31
 9     4  2.71
10     6 -0.891
# … with 22 more rows
Warning message:
Deprecated, use tibble::rownames_to_column() instead.
> mtcars$mpg[1:5]-mean(mtcars$mpg)
[1]  0.909375  0.909375  2.709375  1.309375 -1.390625

A: You can try this instead (although the name of the new variable displayed is different):
mtcars %>%
  group_by(cyl) %>%
  mutate(gpcent = scale(mpg, scale = F))


text:
Q: AWS Cloudwatch alarms in Datadog Looking through Datadog AWS integration documentation I found mention that AWS alarms can be streamed into Datadog. It's stated that you can choose two different methods how to send AWS CloudWatch alarms to the Datadog Event Stream right here in the Alarm collection section.
But there is no further explanation on how to do that or what should be set upped to do that. Moreover, trying to google something like "Datadog aws alarm polling" gives you vague descriptions of some other functionalities but not the AWS CloudWatch alarms.
My question is is it even possible ?
What I tried so far is set upped DataDog Lambda Forwarder that sends CloudWatch logs (metrics and alarms I suppose too?) to DD. I gave permission to that lambda. I created some AWS metric filter and AWS alarm to trigger when specific event occurs. I run some lambda code to throw exception and trigger CloudWatch alarm to change its status.
I clearly see lambda logs in DD, but I can't find anything related to my alarms in DD events. And I suppose it's not a problem with DD-AWS integration because we use it in big organization and it was configured long before I joined the company.
What am I doing wrong ?
Cloudformation script below (I removed some parts, so it's not working as is)
Resources:
  DatadogForwarderLambda:
    Type: AWS::Lambda::Function
    Properties:
      Description: Pushes logs, metrics and traces from AWS to Datadog.
      Role: !GetAtt "DatadogForwarderLambdaRole.Arn"
      Handler: lambda_function.lambda_handler
      Code:
        S3Bucket: config-sandbox
        S3Key: 'aws-dd-forwarder-3.38.0.zip'
      MemorySize: 1024
      Runtime: python3.7
      Timeout: 120
      Tags:
        - Key: "dd_forwarder_version"
          Value:  3.38.0
      Environment:
        Variables:
          DD_ENHANCED_METRICS: "false"
          DD_API_KEY_SECRET_ARN:
            Ref: DdApiKeySecret
          DD_S3_BUCKET_NAME: config-sandbox
          DD_SITE: datadoghq.com
          DD_: datadoghq.com
          DD_TAGS_CACHE_TTL_SECONDS: 300
          DD_FETCH_LAMBDA_TAGS: true
          DD_USE_TCP: false
          DD_NO_SSL: false
          REDACT_IP: false
          REDACT_EMAIL: false
          DD_USE_PRIVATE_LINK: false
          DD_USE_VPC: false
      ReservedConcurrentExecutions: 100

  DatadogReadonlyPolicy:
    Type: 'AWS::IAM::Policy'
    Properties:
      PolicyName: !Sub "DatadogReadonlyPolicy"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Action:
              - 'cloudwatch:Get*'
              - 'cloudwatch:List*'
              - 'cloudwatch:DescribeAlarmHistory'
              - 'cloudtrail:LookupEvents'
              - 'ec2:Describe'
              - 's3:GetObject'
              - 's3:PutObject'
              - 's3:DeleteObject'
              - 's3:ListBucket'
              - 'lambda:List*'
              - 'tag:GetResources'
              - 'tag:GetTagKeys'
              - 'tag:GetTagValues'
              - 'support:*'
            Resource: !GetAtt DatadogForwarderLambda.Arn
          - Effect: Allow
            Action:
              - secretsmanager:GetSecretValue
            Resource:
              - Ref: DdApiKeySecret
      Roles:
        - !Ref DatadogForwarderLambdaRole

  DatadogForwarderLambdaRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
              AWS:
                - Fn::Sub:
                  - "arn:aws:iam::${AccountId}:role/human-role/some-role-name"
                  - { AccountId: !Ref 'AWS::AccountId' }
            Action:
              - sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
        - arn:aws:iam::aws:policy/service-role/AWSLambdaVPCAccessExecutionRole
      Path: /
      PermissionsBoundary:
        Fn::Join:
              - ''
              - - 'arn:aws:iam::'
                - Ref: AWS::AccountId
                - ':policy/some-organisation-permission-boundary'
      RoleName:
        Fn::Sub:
        - 'a${AIID}-dd-forwarder-lambda-${StackID}'
        - { StackID: !Select [4, !Split ["-", !Ref 'AWS::StackId']],
            AIID: !Ref AIID }

  IncomingQueueHasMessagesExceptionAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      AlarmDescription: Incoming queue has unprocessed messages, new processing round can't be started
      AlarmName: !Sub "IncomingQueueHasMessagesExceptionAlarm"
      ComparisonOperator: GreaterThanThreshold
      Threshold: 0 # no messages are allowed in queue if new round started
      EvaluationPeriods: 1
      Period: 10
      Namespace: dev-logs
      MetricName: QueueHasMessagesException
      Statistic: Sum
      TreatMissingData: missing

  IncomingQueueHasMessagesExceptionMetricFilter:
    Type: AWS::Logs::MetricFilter
    Properties:
      LogGroupName:
        !Sub '/aws/lambda/${SomeLambdaName}'
      FilterPattern: "QueueHasMessagesException"
      MetricTransformations:
        -
          MetricNamespace: dev-logs
          MetricName: QueueHasMessagesException
          MetricValue: 1

A: Eventually I found that my AWS account was not completely integrated into DD.


text:
Q: Notation for the set $\{1,2,..,k\}$ I often find myself using the set $\{1,2,..,k\}$, sometimes on multiple occasions in a sentence. I've been told that $[k]$ is a short notation for this, but have never seen that in use. Could someone refer me to a textbook-like source that uses this notation so that I may cite it.

A: A very famous textbook using the notation $[n]=\{1,2,\dots,n\}$ is Enumerative Combinatorics (Volume 1) by Richard Stanley. It's in the list of notation at the beginning of the book, and is first used in Example 1.1.16.


text:
Q: Missing base case for Python recursion I recently found some code that did not seem to have base case defined for recursion, but it worked fine.
This is a solution for leetcode question 690. Employee Importance.
class Solution(object):
    def getImportance(self, employees, id):
        """
        :type employees: Employee
        :type id: int
        :rtype: int
        """

        employee_dict = {employee.id : employee for employee in employees}

        def helper(id):

            ans = employee_dict[id].importance

            for x in employee_dict[id].subordinates:

                ans += helper(x)

            return ans

        return helper(id)

All I know about recursion is that you must have a base case to return, otherwise it is going to run forever. But how come this one didn't come with the base case? Could some one explain it? Thanks!


text:
Q: Difference between 'sudo gem install something' and 'gem install something' In this case I'm using gem as an example, but I think it can be extended to any other program.
I use a Mac and I installed rails using command gem install rails from  directory /Users/myusername/workstation. Then I tried to run rails new somename and this is the output:
Rails is not currently installed on this system. To get the latest version, simply type:

    $ sudo gem install rails

I would expect being able to execute commands from the program I just installed from my 'domain' (username directory). Obviously it doesn't work like that, at least in this case. What am I missing? What is the proper way of installing and dealing with programs you are going to user frequently?
Thanks!


text:
Q: Terminal Control Escape Sequence: how can I catch row and column with "\e[6n"? How could I catch the row and the column in variables instead of printing out (here ^[[12;1R)?
#!/usr/bin/env perl
use warnings;
use 5.012;

print "\n" x 10;

say "\e[6n";

A: I've found this:
#!/usr/bin/env perl
use warnings;
use 5.012;
use Term::ReadKey;

ReadMode 4;

system( 'clear' ) == 0 or die $?;

print "\e[6n";
my ( $x, $y ) = getch();
say "Col: $x  -  Row: $y";

print "Hello world\n" x 6;

print "\e[6n";
( $x, $y ) = getch();
say "Col: $x  -  Row: $y";

print "String\n" x 5;
print "go to column 21 -> |";

print "\e[6n";
( $x, $y ) = getch();
say "Col: $x  -  Row: $y";

ReadMode 0;

sub getch {
    my $c = ReadKey 0;
    if ( $c eq "\e" ) {
        my $c = ReadKey 0.10;
        if ( $c eq '[' ) {
            my $c = ReadKey 0;
            if ( $c =~ /\A\d/ ) {
                my $c1 = ReadKey 0;
                if ( $c1 ne '~' ) {
                    my $y = 0 + $c;
                    while ( 1 ) {
                        last if $c1 eq ';';
                        $y = 10 * $y + $c1;
                        $c1 = ReadKey 0;
                    }
                    my $x = 0;
                    while ( 1 ) {
                        $c1 = ReadKey 0;
                        last if $c1 eq 'R';
                        $x = 10 * $x + $c1;
                    }
                    return $x, $y;
                }
            }
        }
    }
}

A: Sorry it took a while, I added this feature ages ago then forgot to update the question ;)
use Term::TermKey;

my $termkey = Term::TermKey->new( \*STDIN );

STDOUT->autoflush( 1 );
print "\e[6n";

while( $termkey->waitkey( my $key ) == RES_KEY ) {
   if( $key->type_is_position ) {
      printf "Position is %d, %d\n", $key->col, $key->line;
      last;
   }
}


text:
Q: Read from jQuery the value of a JSON array that only has an object I have a jQuery and a PHP file. If in PHP the process was done correctly, it returns 2 (by echo json_encode(2)). I catch it in the jQuery file, and I show a string on a HTM div. I can do This part without any problem.
The thing that is being difficult to me is to return the erorr to ajax, when it occurs, to show on the HTML div. I thought on return a JSON array {"error": "xxx"} where "xxx" was the error generated by php.
So the problem is that I can't get the value of the "error" key to show it.
I read a lot of similar topics on the website, but they are about reading values of more than one object.
jQuery file:
$('#log').submit(function(event) {
        event.preventDefault();
        var stuff = $(this).serializeArray();
        stuff.push({name:'tag', value:'login'});

    $.ajax({
        url: './php/logreg.php', //Como si fuera el action del form
        type: 'post', //Por defecto es get
        dataType: 'json',
        data: stuff,
        beforeSend: function(){
            $('#span-login-icon').css('display','inline');
        }
    })
    .done(function(data){
        if(data == 2){
            $('#span-login-resp').html('Correcto');
        }
        else{

            $('#span-login-resp').html(data);
        }

    });
});

PHP file:
if($object->queError()  === ''){
    echo json_encode(2);
}
else{

    echo json_encode('{"error"'.':"'.$object->queError().'"'.'}'); //output: {"error":"xxx..."}
}

A: Your code returning the error is calling json_encode on a string, which probably isn't what you want, as you'll end up returning a JSON string literal, not the object the text in it defines.
That is, you're currently returning this JSON:
"{\"error\":\"something went wrong\"}"

where you probably want to return this JSON:
{"error":"something went wrong"}

You probably want:
else {
    echo json_encode(array(
        'error' => $object->queError()
    ));
}

(Building JSON strings manually is almost always not your best option.)
Then in your ajax callback
.done(function(data) {
    if (data == 2){
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html(data.error);
        //                             ^^^^^^---------------- Note
    }
});

Or possibly:
.done(function(data) {
    if (data && data.error){
        $('#span-login-resp').html(data.error);
    }
    else if (data == 2) {
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html('Ocurrió un error inesperado');
    }
});

Alternately, in keeping with the style of your success return (just the number 2), you could just return a string:
echo json_encode('error: ' . $object->queError());

and then
.done(function(data) {
    if (data == 2){
        $('#span-login-resp').html('Correcto');
    }
    else {
        $('#span-login-resp').html(data);
    }
});

FWIW, even though it's no longer required, I would probably return an object with either an error property (containing the error) or a result property (containing the 2).

A: Try this:
PHP last line:
echo json_encode( array("error" => $object->queError()) );

JS last line:
$('#span-login-resp').html(data.error);


text:
Q: MacOS - One line command is working in terminal but not in .sh script? MacOS High Sierra
I have a command that I currently use in terminal:
find /private/my/tmp -mindepth 1 -maxdepth 1 -type d -not -name -specialfolder -exec rm -r {} \;

which searches the folder private/my/tmp and removes all folders except one that is named "specialfolder".
This is working perfectly from the terminal, but I cannot get it working as .sh shell script. I have used chmod +x /scripts/myscript.sh to make it executable but this has not made any difference.
The shell script is:
#!/bin/sh
find /private/my/tmp -mindepth 1 -maxdepth 1 -type d -not -name -specialfolder -exec rm -r {} \;

Running it from the terminal as "sh myscript.sh" does not produce any result, no errors, nothing.
What do I need to fix to get this to work as a .sh script?
PS - I had considered it may be a permissions issue, but I have set permissions with chmod -R 777 on the /private/my/tmp folder and still no difference.


text:
Q: Easier way to run a Java application from Maven? If I have understood correctly, I need to type this to run my project from maven:
mvn compile
mvn exec:java -Dexec.mainClass="com.foo.bar.blah.Main"

Is there a way I can make this simpler? Optimally I would like to just do
mvn run

A: 1) Create a new profile called "run" (or another name of your choice)
  <profiles>
    <profile>
      <id>run</id>

2) Set the profile's default goal to "verify" (or you can choose "install", choosing a phase after compile will ensure that the code will automatically be compiled before running the class)
 <profiles>
    <profile>
      <id>run</id>
      <build>
        <defaultGoal>verify</defaultGoal>

3) Add the exec-maven-plugin to this profile (see this), but configure it to run in the 'verify' phase.
   <execution>
    <phase>test</phase>

4) You can now run your class using the following:
mvn -Prun

A: A little more configuration, a little less command line parameters ;-)
using the very same exec:java plugin, you can configure your task in the pom.xml, then execute it in a simpler fashion by mapping your goal to the run step of the lifecycle, like this example shows.

A: As the above example shows, you can wrap that plugin into a separate profile. Take a look at the 3rd solution

A: Sadly, no `(as far as I know). If you ahve a web application you could use Jetty plugin to run it doing:
mvn jetty:run
but for standalone apps, you need the exec plugin.


text:
Q: How to execute a prepared statement that has timed out In case of PreparedStatement in Java, if we set the timeout and execute the query in this way:
int timeout = 100;
void func() {
    try {
        statement.setQueryTimeout(timeout);
        statement.executeQuery();
    } catch(SQLException e) {
        timeout = timeout * 2;
        func();
    }
}

If the query gets timed out and if you set the query timeout and try to run this code again, it fails:
statement.executeQuery();

It throws an error:

No statements may be issued when any streaming result sets are open.

Is there any workaround for this?


text:
Q: Dynamic SQL vs Static SQL In our current codebase we are using MFC db classes to connect to DB2. This is all old code that has been passed onto us by another development team, so we know some of the history but not all.
Most of the Code abstracts away the creation of SQL queries through functions such as Update() and Insert() that prepend something like "INSERT INTO SCHEMA.TABLE" onto a string that you supply. This is done through the recordset classes that sit on top of the database class
The other way to do the SQL queries is to execute them directly on the database class using dbclass.ExecuteSQL(String).
We are wondering what the pro's and cons of each approach is. From our perspective its much easier to do the ExecuteSQL() call, as we dont have to write another class etc, but there must be good reasons to do the other way. we are just not sure what they are.
Any help would be great!
Thanks Mark
Update----
I think I may have misunderstood Dynamic and Static SQL. I think our code always uses Dynamic, so my question really becomes, should I construct the SQL strings myself and do an ExecuteSQL() or should this be abstracted away in a class for each table in the database, as the recordset classes from mfc seem to do?

A: The ATL OLE DB consumer database classes are absolutely the way to go. Beyond the risks of injection (mentioned by Skurmedel), piles of string-concatenated queries will become impossible to maintain very quickly.
While the ATL classes can be initially tedious, they provide the benefit of strong-typed and named columns, result navigation, connection and session management, etc.

A: I would try to abstract it away if it's many SQL statements. Managing dozens of different SQL queries quickly become tedious. Also it's easier to validate input that way.


text:
Q: Sanitize a string with non-alphanum repetition I need to sanitize article titles when (creative) users try to "attract attention" with some non-alphanum repetition.
Exemples:

*

*Buy my product !!!!!!!!!!!!!!!!!!!!!!!!

*Buy my product !? !? !? !? !? !?

*Buy my product !!!!!!!!!.......!!!!!!!!

*Buy my product <-----------

Some acceptable solution would be to reduce the repetition of non-alphanum to 2.
So I would get:

*

*Buy my product !!

*Buy my product !? !?

*Buy my product !!..!!

*Buy my product <--

This solution did not work that well:
preg_replace('/(\W{2,})(?=\1+)/', '', $title)

Any idea how to do it in PHP with regex?
Other better solution is also welcomed (I cannot strip all the non-alphanum characters as they can make sense).
Edit: the objective is only to avoid most common issues. The other creative cases will be sanitized manually or sanitized with an other regex.

A: That's really an inefficient problem to solve with a regex, especially if the repeated expression is arbitrarily large. Practically, it shold be enough to just cap the length of the repeated expression at something like 3 to 5, and it should be a lot easier.
Something like
$title = preg_replace('/(\W{1,5})(?=\1+)/', '', $title);

should work.
Some preliminary testing shows that
$title = 'Buy my product !!!!!!!!!!!!!!!!!!!!!!!! Buy my product !? !? !? !? !? !? Buy my product !!!!!!!!!.......!!!!!!!! Buy my product <-----------';

$title = preg_replace('/(\W{1,5})(?=\1{2,})/', '', $title);

echo $title;

will output
Buy my product !! Buy my product !? !? Buy my product !!..!! Buy my product <--

This appears to pass all your test cases.

Re: Gordon
Your string:
¸·´`·¸·´`·¸·´`·¸ Human ·-> creativity << is endless !¡!¡! ☻☺

doesn't repeat anything but the first part more than two times. It seems to require:
$title = preg_replace('/(\W{1,9})(?=\1{2,})/', '', $title);

before it simplifies to
¸·´`·¸·´`·¸ Human ·-> creativity << is endless !¡!¡! ☻☺

(Which implies that preg_replace isn't Unicode-aware - oh well)
you can also adjust it to repeat only once:
$title = preg_replace('/(\W{1,9})(?=\1+)/', '', $title);

in which case it becomes:
¸·´`·¸ Human ·-> creativity < is endless !¡! ☻☺

If your point is that it's possible to create lots of "ASCII art" even if it's required to repeat less than two times, well, that's outside of the scope of this question. For the purposes of keeping ASCII art to a minimum, I would recommend simply using something like:
preg_replace('/(\W{5})\W+/', '$1', $title);

(i.e. just cap the number of non-alphanumeric characters that can be displayed in a row. Note that this would need to be adjusted for compatibility with languages with non-Latin alphabets, like Russian.)

A: I have an answer that's a little bit different
if (preg_match('/^[^\da-z\s_-]$/i', $str)) {

  // auto post, but flag to moderator to inspect title OR
  // instead of auto posting, put in 'waiting to be authorised' by a mod

}

I hope I have that regex correct, but I have not tested it. Basically it should detect when someone has in their title characters that are not 0-9, A-Z (case insensitive), whitespace, underscore and dash. Of course, you can modify this to suit your liking.
It would also be a good idea to inform the end user

"Titles that deliberately try to
  attract attention without benefiting
  the product description may be deleted without
  warning"

A: Use non-greedy search?
preg_replace('/(\W{2,}?)(?=\1+)/', '', '{{your data}}');

result is
  * Buy my product !!
  * Buy my product !?
  * Buy my product !!!...!!
  * Buy my product <---


text:
Q: Compare two files and store data in new file in python Sorry, I have updated my question. I have two files file1.txt and file2.txt and their respective data is as follow:
file1.txt:
admin:admin
admin:meunsm
admin:12345

sequence in file1.txt is:
username:password

file2.txt:
192.168.0.114:1137   >   192.168.0.193:21 csanders:echo

sequence in file2.txt is:
source ip:source port > destination ip:destination port username:password

Now, what I want from python is to just compare these files and extract the username only. If username in file1.txt doesn't exist in file2.txt, then that username must store in a new text file. Here I have updated my question with .txt files data. Also there can be hundred of thousands rows in these both files and for loop should be use in this case because I want to save the username in my database table.
I have picked this code sample from Stack overflow Where both files are compared at same time, if there is any common data in both files that data will write in a new file:
sample:
with open('file1.txt') as file1:
    with open('file2.txt') as file2:
        newfile = open('newfile.txt','w')
        common_lines = set(file1.readlines()) & set(file2.readlines())
        for line in common_lines:
          newfile.write(line)

        newfile.close()

but my scenario is quiet different. I want if data in file1.txt is not in file2.txt then that data must store in newfile.txt.
Just I want to compare two files at same time and I want if data in file1.txt doesn't exist in file2.txt, so that data must be stored in newfile

A: You can use symmetric_difference.
Something like:
with open('file1.txt') as file1, \
     open('file2.txt') as file2, \
     open('newfile.txt', 'w') as newfile:
    diff = set(file1.readlines()).symmetric_difference(file2.readlines())
    for line in diff:
        newfile.write(f"{line.strip().split(':')[0]}\n")

Note: using set does not guarantee the order of lines.

A: It is quite easy with a for loop.
with open('file1.txt') as file1:
with open('file2.txt') as file2:
    newfile = open('newfile.txt', 'w')
    f1_lines = file1.readlines()
    f2_lines = file2.readlines()
    different_lines = []

    for line1 in f1_lines:
        init = False
        for line2 in f2_lines:
            if line1 in line2:
                init = True
        if not init:
            different_lines.append(line1)

    for line in different_lines:
        newfile.write(line)

    newfile.close()

A: Here is the simple code and it will maintain the order (memory efficient), I will work on huge files also as it is using iterator
with open("file1.txt") as fp1, open("file2.txt") as fp2, open("newfile.txt", "w") as fp3:
    i = 0
    k = 0
    while True:
        try:
            if i == 0:
                # at first get line from both file
                l1 = next(fp1)
                l2 = next(fp2)
            # if both the line is equal get another line
            if l1 == l2:
                try:
                    l1 = next(fp1)
                except StopIteration:
                    break
                l2 = next(fp2)
            # if line are not equal then put l1 in new file
            else:
                fp3.write(l1)
                try:
                    l1 = next(fp1)
                except StopIteration:
                    break
            i += 1
        except StopIteration:
            k += 1
            if k == 2:
                break
        except Exception as e:
            print(e)
            break


text:
Q: Random long, can it be twice in a row the same number I was wondering with the current java 1.7 implementation of the Random class, is it possible for the code below to generate two times the same random long?
Random rand = new Random((long) "some seed".hashCode());
while(rand.nextLong() != rand.nextLong()){

}

System.out.println("Will this text ever be on the console?");

Java source for nextLong() and next();
public long nextLong(){
    return ((long) next(32) << 32) + next(32);
}

protected synchronized int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int) (seed >>> (48 - bits));
}

I would answer this question with false because I think the random method used by java does not repeat the same numbers for a 2^48 period, so it would never generate two the same numbers in a row. Is this correct?

A: No, getting two identical longs in a row with this algorithm is impossible.
While people were writing long posts about math and other wizardry, I went the code monkey route and brute forced the 2^48 possible seeds over the weekend. No two longs produced in a row were ever equal for any seed.

long int seed = 0;

int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int) (seed >> (48 - bits));
}
long int nextLong(){
    return ((long int) next(32) << 32) + next(32);
}

int main(int argc, char** argv) {
  long int step = atoi(argv[1]);
  long int i = step << 32;
  long int end = (step+1) << 32;
  while(i < end) {
    seed = i;
    if(nextLong() == nextLong()) {
      printf("Found seed %ld\n", i);
      return 0;
    }
    ++i;
  }
  printf("No seed in %ld\n", step);
  return 1;
}

then
echo {0..65535} | xargs -n 1 -P 12 ./executable

A: It depends on which question you're asking.
As others have said: The standard formulas for pseudo-random number generators fully explore their value space before repeating.
However: In most applications we don't use the full range of the PRNG's output. We reduce it by dividing or truncating it down to a range that matches the problem we're trying to solve. And most of the ways we do so will, in fact, result in a series of numbers which can include immediate repeats.
And that could be true even if you're simply using an integer random number when the underlying formula is using more bits for its calculations.
So: Theoretically, if you're looking directly at a PRNG's output, the answer is "probably not". Practically, the answer is "don't count on it either way."

A: To come up with an "longer" answer than my previous:
You already linked the implementation, it looks like:
public long nextLong(){
    return ((long) next(32) << 32) + next(32);
}

So, obviously, ONE random number calls 2 times next(32).
That means, 2 random numbers will be equal, if next(32) results
in 4 times THE SAME number because the rest of the function is "hardcoded".
Looking at the next() function, we can see the following:
protected synchronized int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    return (int) (seed >>> (48 - bits));
}

The return part can be simply ignored, because again: SAME seed would lead
to the SAME return value - otherwhise your CPU is broken.
So, in total: We only need to focus on the line
seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);

if that will result in the SAME seed, for four times, 2 random numbers have been generated,
that are equal.
(Note: Sequences like a,b,a,b can be excluded to produce the same result. Post is long enough, i skip that part.)

First, lets eliminate the << 48 part. What does that mean? The Number given (1) will be shifted left
48 times. So the binary 0...01 will turn into 1000000000000000000000000000000000000000000000000 (48 zeros)
then, one is subtracted, so what you will get is 0111111111111111111111111111111111111111111111111 (47 ones)
Lets have a look at the first part of that equation:
(seed * 0x5DEECE66D[L] + 0xB[L])

Note, that the ending [L] will only cause it to be a long value instead of a integer.
so, in binary words, that means:
seed * 10111011110111011001110011001101101 + 1011

After all, the function looks like
seed = (seed * 10111011110111011001110011001101101 + 1011) & (0111111111111111111111111111111111111111111111111)

(I left out the leading zeros on the first values)
So, what does & (0111111111111111111111111111111111111111111111111) do ?
The bitwise-and-operator and basically compares EVERY position of two binary numbers. And only if BOTH of them are "1", the position in the resulting binary number will be 1.
this said, EVERY bit of the equation (seed * 10111011110111011001110011001101101 + 1011) with a position GREATER than 48 from the RIGHT will be ignored.
The 49th bit equals 2^49 or 562949953421312 decimal - meaning that & (0111111111111111111111111111111111111111111111111) basically just says
that the MAXIMUM result can be 562949953421312 - 1.
So, instead of the result 562949953421312 - it would produce 0 again, 562949953421313 would produce 1 and so on.
All the stuff I wrote above could be easily verified:
While the following code will produce the random seed *11*:
private Long seed = 0L;

protected synchronized int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    System.out.println(seed);
    return (int) (seed >>> (48 - bits));
}

One can reverse engineer the seed and ALSO gets the seed 11 from a non-0 seed, using the number 562949953421312L.
private Long seed = 562949953421312L - 0xBL / 0x5DEECE66DL;

protected synchronized int next(int bits){
    seed = (seed * 0x5DEECE66DL + 0xBL) & ((1L << 48) - 1);
    System.out.println(seed);
    return (int) (seed >>> (48 - bits));
}

So, you see: Seed 562949953421312 equals Seed 0.
Easier proof:
Random r = new Random(0L);
Random r2 = new Random(562949953421312L);

if (r.nextLong()==r2.nextLong()){
    System.out.println("Equal"); //You WILL get this!
}

it continous of course:
Random r3 = new Random(1L);
Random r4 = new Random(562949953421313L);

if (r3.nextLong()==r4.nextLong()){
    System.out.println("Equal");
}

Why is this "magic number" (562949953421312L) important?
Assuming, we are starting with Seed 0.
The the first new-seed will be: 0 * 10111011110111011001110011001101101 + 1011 = 1011 (dec: 11)
The next seed would be: 1011 * 10111011110111011001110011001101101 + 1011 = 100000010010100001011011110011010111010 (dec: 277363943098)
The next seed (call 3) would be: 100000010010100001011011110011010111010 * 10111011110111011001110011001101101 + 1011 = 10000100101000000010101010100001010100010011100101100100111101 (dec 2389171320405252413)
So, the maximum number of 562949953421312L is exceeded, which will cause the random number to be SMALLER than the above calculated value.
Also, adding 1011 will cause the result to alternate between odd and even numbers. (Not sure about the real meaning - adding 1 could have worked as well, imho)
So, generating 2 seeds (NOT random numbers) ensures, that they are NOT equal, because a specific "overflow" point has been selected - and adding the MAXIMUM value (562949953421312L) is NOT enough to hit the same number within 2 generations.
And when 2 times the same seed is impossible, 4 times is also impossible, which means, that the nextLong() function could never return the same value for n and n+1 generations.
I have to say, that I wanted to proof the opposite. From a statistical point of view, 2 times the same number is possible - but maybe that's why it's called Pseudorandomness :)

A: I don't think so.  I believe that the generator uses the next number as the seed for the subsequent number.  So, if you get a value once, and if it were to repeat, your number generator would be stuck in a loop.
However, many applications are looking for a number in a certain range, which makes it possible to repeat since a subsequent number may have the same value modulo the range.
EDIT: Since you included the source code of next you can see that if ever it returned the same number, it would always return the same number.  Hence, you'd be stuck in a loop of one value.


text:
Q: Condition when I do not have a file in my list My script:
#!/bin/bash
NOW=$(date +"%Y%m%d%t%H%M%S")
# Pour chaque dossiers "log" trouvé.
for folder in $(find . -name "*log*" -type d )
    do :
        # Pour chaque dossier log contenant des fichiers ".log" vieux de +30jours.
            tar czf archive-log.$NOW.tar.gz $(find $folder -name "*.log" -mtime +30)
            # On supprime les anciens fichiers de log
            rm $(find $folder -name "*.log" -mtime +30)
    done

my question is: What test do I find out if I have files to be archived or not ?
Thx

A: If you want to skip the case in which there are no files to archive, this can help you:
if [ ! -z $(find $folder -name "*.log" -mtime +30) ]
then
   tar czf archive-log.$NOW.tar.gz $(find $folder -name "*.log" -mtime +30)
   rm $(find $folder -name "*.log" -mtime +30)
else
   echo "there are no files to archive"
fi

The syntax if [ -z "string" ] checks if a string is empty or not. Negating it, if [ ! -z $(find...) ] we check if the result returns results or not.


text:
Q: How does one upload a .txt file in PHP and have it read line by line on another page? My objective here is to upload a .txt file on a form (browse), post the file to another php page, and then have that file read line by line.
My code so far is here.
FILE 1: HTML UPLOAD:
<form action="TestParse.php" method="post" enctype="multipart/form-data">
   Filename: <input type="file" name="file" id="file"/>
<input type="submit" value="Submit">
</form>

FILE 2: READING THE FILE
    if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "
";
}
elseif ($_FILES["file"]["type"] !== "text/plain")
{
echo "File must be a .txt";
}
else
{
$file_handle = fopen($_FILES["file"]["name"], "rb");
}

As I see it, the second file would verify that there is no error and that the uploaded file is a .txt. It would then fopen() the file and I would then be able to read with fgets() (I have managed to get all this to work).
However, this code only works if the .txt file that is being uploaded happens to be in the same directory as the PHP file. Otherwise I get lots of error messages. And when you cannot upload a file that's not in the PHP file's folder, it defeats the purpose of having a file upload system in the first place.
Can someone tell me what is wrong with this code?

A: Use $_FILES["file"]["tmp_name"] instead. And get the contents of the file with
$contents = file_get_contents($_FILES['file']['tmp_name']);

A: You would need to move the file to where you want it to go first then you can work with it. See move_uploaded_file() for how this is done. See also, Handling File Uploads in the PHP docs particularly the page showing how to do with using POST which you are doing.
<?php
// In PHP versions earlier than 4.1.0, $HTTP_POST_FILES should be used instead
// of $_FILES.

$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo '
';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.\n";
} else {
    echo "Possible file upload attack!\n";
}

echo 'Here is some more debugging info:';
print_r($_FILES);

print "
";

?>

A: to read line by line, it worked for me this code:
$fp = fopen($_FILES['uploadFile']['tmp_name'], 'rb');
    while ( ($line = fgets($fp)) !== false) {
      echo "$line
";
    }

you do not need to save it.

A: You can read the whole text file into an array with php explode fn.
eg. $wholeTextFile = explode("\n", file_get_contents('textFileName.txt'));

Then get the total number of lines by counting sizeOf array.
eg. $totalLinesinFile = sizeOf($wholeTextFile);

Now when you iterate the array in a for loop or forEach loop, each iteration gives you 1 line.
eg.

for ($i = 0; $i < $totalLinesinFile ; $i++) {
   echo "Line number is ".$i."
";
   echo wholeTextFile[$i]."
";
}

A: Could it be that there is an open_basedir restriction?
open_basedir limits the files that can be opened by PHP within a directory-tree.
http://www.php.net/manual/en/ini.core.php#ini.open-basedir


text:
Q: Can't install Revel (Unrecognized import path) I'm a beginner in Go and I would like to use the Revel web framework.
I installed: Git; Mercurial and even: Bazaar and CVS.
I checked my environment variables. I set environment variable GOPATH to D:\Go and added D:\Go\bin to PATH.But I still get these errors when I go get The Revel Framework (go get github.com/revel/revel)
**

*

*package golang.org/x/net/websocket: unrecognized import path "golang.org/x/net/websocket"

*package gopkg.in/fsnotify.v1: unrecognized import path "gopkg.in/fsnotify.v1"**

A: For instalation of GO into your home folder you need this environment variables:
.
├── bin
├── go (GO)
└── src
    ├── revel.project
    │   ├── app
    │   │   ├── controllers
    │   │   ├── models
    │   │   ├── routes
    │   │   ├── tmp
    │   │   └── views
    │   │       ├── admin
    │   │       ├── App
    │   │       ├── errors
    │   │       └── users
    │   ├── conf
    │   ├── messages
    │   ├── public
    │   │   ├── css
    │   │   │   └── administrator
    │   │   ├── img
    │   │   ├── js
    │   │   └── uploads
    │   │       └── 1
    │   ├── resources
    │   ├── scripts
    │   ├── test-results
    │   └── tests
    ├── code.google.com
    ├── github.com
    │   ├── revel
    │   │   ├── cmd
    │   │   ├── modules
    │   │   └── revel

run this in your prompt path or modify if your folders are differents.
  export GOARCH=amd64
  export GOPATH=~/go
  export GOBIN=~/go/go/bin
  export GOROOT=~/go/go
  export PATH=$PATH:$GOPATH/go/bin
  export GOTOOLDIR=~/go/go/pkg/tool/linux_amd64
  export CC="gcc"
  export GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
  export CXX=g++
  export CGO_ENABLED=1

Where ~ is the name of you personal folder in the system (Bash Gnu Linux)


text:
Q: how to change domain in kiwiTCMS? I have been looking for a way to change the host in kiwiTCMS, but unfortunately i could not find any solution online
how can I change the domain in kiwiTCMS from localhost to another host

A: Login with superuser / administrator account to Kiwi instance and do the following:

*

*Click on Admin

*Click on Everything else

*Click on  Sites (or directly via https://localhost/admin/sites/site/1/change/ )

*Click on localhost

*Input Domain name and Display name

*Click on  Save
See documentation: https://kiwitcms.readthedocs.io/en/latest/admin.html#configure-kiwi-base-url


text:
Q: error on line 1 at column 1: Document is empty when I call a rest api I have the following code where I have an html template, I upload an xml file, read content of the file and I need to return a string value.
@Transactional
@Component
@RestController
public class ImportE125Controller  {

    @Autowired
    @Qualifier("jdbcImportE125")
    private JdbcTemplate template;

    @PostMapping(path = "/importE125", headers="Accept=application/xml; charset=utf-8", produces = "text/plain")
    public String getE125New(@RequestParam("file") MultipartFile file, ModelMap modelMap,
            HttpServletResponse response) throws ServletException, IOException
    {
        modelMap.addAttribute("file", file);
        String xmlString = new String (file.getBytes(), StandardCharsets.UTF_8);
        System.out.println("\n\nFILE: "+ xmlString);
        Document doc = convertStringToDocument(xmlString);
        //Normalize XML structure
        doc.getDocumentElement().normalize();

        //Parameters
        String institutionID = null;
        String institutionName = null;

        int total_rows_counter = 0;
        int insertions_counter = 0;
        String cases_not_inserted = null;

             int insert;
             try {
                 insert = template.update("INSERT INTO tblE125Details (ForeasCode, EYear, ArProtokolou)"
                    + " VALUES (?,?,?)",
                     "test", "2022", "1" );
             }
             catch (InvalidResultSetAccessException e)
             {
                 throw new RuntimeException(e);
             }
             catch (DataAccessException e)
             {
                 throw new RuntimeException(e);
             }

             total_rows_counter = total_rows_counter+1;

             if (insert == 1) {
                     System.out.println("\nInsert Value == "+ insert);
                     insertions_counter = insertions_counter+1;
             }
             else if (insert == 0) {
                 cases_not_inserted = cases_not_inserted + "IDno: " + pINPersonInCompetentMemberState + ", ";
             }
             System.out.println("\n\nNEW\n\n");
        }

        String str = convertDocumentToString(doc);
        //return str;
        String str_response = "Response: \n" + insertions_counter + " cases added out of " +  total_rows_counter;

        return str_response;
    }

Instead of str_response string in my browser I get the following screen:

I suppose that this controller returns an xml and not a string, even though I set public String. In case I change the headers to "text/plain" it's not working at all. I also tried consumes/produces without any luck. Any help please?
Edit:
I suppose that this controller returns an xml and not a string, even though I set public String. In case I change the headers to "text/plain" it's not working at all. I also tried consumes/produces without any luck.
This is an example that works, but returns an xml tree.
String str_response = "<response><message>" + insertions_counter + " cases added out of " +  total_rows_counter+"</message></response>";

A: Because of this headers="Accept=application/xml; charset=utf-8", your response will have the following content type application/xml;charset=utf-8.
You browser is attempting to parse an non XML response (although the content type indicates that is XML), and therefore you receive that error.
So, your response can be a String, if it is a XML string.
If you want to return text, remove the headers or change it to
headers="Accept=text/plain;charset=UTF-8"


text:
Q: Better to use 1 or multiple database tables? I am experimenting with databases (using Access currently, as i have it through work).  To get acquainted, I am making a database to log catches on my fishing trips.  There are several "categories" of information, such as "fish info" (which would include species, weight, and length) and "location info" (includes name of the lake and GPS coordinates).  Other conditions such as the date/time and various weather conditions would also be in there.
I understand that databases are especially good for situations where an entry in one table could relate to multiple entries in a second table.  However, in my use case, a single fish will not have multiple locations, or multiple datetimes/weather conditions.
So my question is, should I be using multiple tables, and break them up according to "category"?  Or is it best practice to use one table, since no entry in any table will ever correspond to multiple entries in another table?
Thanks!

A: I'd recommend reading up on database normalization. It should shed some light on how you can lay out your database.
For example: a single lake probably always has the same name and coordinates. Why store them separately for every fish caught? Extract lake information into a separate table. Give each lake a unique name and coordinates. Let fish records reference lakes in their respective table. Searching by lake will be easier. Making typos will be harder and easier to fix.


text:
Q: How to convert a reverse string function from the main function to its own independent function? I'm trying to learn C and understand the language...
See below this sample code, how would you create a function called "reverseString" which takes the "for" loop out of the "main" function?
#include <stdio.h>
#include <string.h>

#define NUMBER_OF_STRING 100
#define MAX_STRING_SIZE   50

void print_array(const char commonWords[NUMBER_OF_STRING][MAX_STRING_SIZE])
{
    int count = 1;
    for (int i = 0; i < NUMBER_OF_STRING; i++, count++) {
        printf("%_7s is word number: %d\n", commonWords[i], count);
    }
}

int main() {
    char commonWords[NUMBER_OF_STRING][MAX_STRING_SIZE] = {"the", "be", "to", "of", "and", "a", "in", "that", "have", "I", "it", "for", "not", "on", "with", "he", "as", "you", "do", "at", "this", "but", "his", "by", "from", "they", "we", "say", "her", "she", "or", "an", "will", "my", "one", "all", "would", "there", "their", "what", "so", "up", "out", "if", "about", "who", "get", "which", "go", "me", "when", "make", "can", "like", "time", "no", "just", "him", "know", "take", "people", "into", "year", "your", "good", "some", "could", "them", "see", "other", "than", "then", "now", "look", "only", "come", "its", "over", "think", "also", "back", "after", "use", "two", "how", "our", "work", "first", "well", "way", "even", "new", "want", "because", "any", "these", "give", "day", "most", "us"};

    printf("Before reverse:\n");
    print_array(commonWords);

    // *** reverse function which requires its own function ***
    for (int i = 0; i < NUMBER_OF_STRING; i++)
    {
        for (int j = 0, k = strlen(commonWords[i]) - 1; j < k; j++, k--)
        {
            char temp = commonWords[i][j];
            commonWords[i][j] = commonWords[i][k];
            commonWords[i][k] = temp;
        }
    }

    printf("\nAfter reverse:\n");
    print_array(commonWords);

    return 0;
}

Expected Output:
Before reverse:
    the is word number: 1
     be is word number: 2
     to is word number: 3
     of is word number: 4
    and is word number: 5
      a is word number: 6
     in is word number: 7
   that is word number: 8
   have is word number: 9
      I is word number: 10
     it is word number: 11
    for is word number: 12
    not is word number: 13
     on is word number: 14
   with is word number: 15
     he is word number: 16
     as is word number: 17
    you is word number: 18
     do is word number: 19
     at is word number: 20
   this is word number: 21
    but is word number: 22
    his is word number: 23
     by is word number: 24
   from is word number: 25
   they is word number: 26
     we is word number: 27
    say is word number: 28
    her is word number: 29
    she is word number: 30
     or is word number: 31
     an is word number: 32
   will is word number: 33
     my is word number: 34
    one is word number: 35
    all is word number: 36
  would is word number: 37
  there is word number: 38
  their is word number: 39
   what is word number: 40
     so is word number: 41
     up is word number: 42
    out is word number: 43
     if is word number: 44
  about is word number: 45
    who is word number: 46
    get is word number: 47
  which is word number: 48
     go is word number: 49
     me is word number: 50
   when is word number: 51
   make is word number: 52
    can is word number: 53
   like is word number: 54
   time is word number: 55
     no is word number: 56
   just is word number: 57
    him is word number: 58
   know is word number: 59
   take is word number: 60
 people is word number: 61
   into is word number: 62
   year is word number: 63
   your is word number: 64
   good is word number: 65
   some is word number: 66
  could is word number: 67
   them is word number: 68
    see is word number: 69
  other is word number: 70
   than is word number: 71
   then is word number: 72
    now is word number: 73
   look is word number: 74
   only is word number: 75
   come is word number: 76
    its is word number: 77
   over is word number: 78
  think is word number: 79
   also is word number: 80
   back is word number: 81
  after is word number: 82
    use is word number: 83
    two is word number: 84
    how is word number: 85
    our is word number: 86
   work is word number: 87
  first is word number: 88
   well is word number: 89
    way is word number: 90
   even is word number: 91
    new is word number: 92
   want is word number: 93
because is word number: 94
    any is word number: 95
  these is word number: 96
   give is word number: 97
    day is word number: 98
   most is word number: 99
     us is word number: 100

After reverse:
    eht is word number: 1
     eb is word number: 2
     ot is word number: 3
     fo is word number: 4
    dna is word number: 5
      a is word number: 6
     ni is word number: 7
   taht is word number: 8
   evah is word number: 9
      I is word number: 10
     ti is word number: 11
    rof is word number: 12
    ton is word number: 13
     no is word number: 14
   htiw is word number: 15
     eh is word number: 16
     sa is word number: 17
    uoy is word number: 18
     od is word number: 19
     ta is word number: 20
   siht is word number: 21
    tub is word number: 22
    sih is word number: 23
     yb is word number: 24
   morf is word number: 25
   yeht is word number: 26
     ew is word number: 27
    yas is word number: 28
    reh is word number: 29
    ehs is word number: 30
     ro is word number: 31
     na is word number: 32
   lliw is word number: 33
     ym is word number: 34
    eno is word number: 35
    lla is word number: 36
  dluow is word number: 37
  ereht is word number: 38
  rieht is word number: 39
   tahw is word number: 40
     os is word number: 41
     pu is word number: 42
    tuo is word number: 43
     fi is word number: 44
  tuoba is word number: 45
    ohw is word number: 46
    teg is word number: 47
  hcihw is word number: 48
     og is word number: 49
     em is word number: 50
   nehw is word number: 51
   ekam is word number: 52
    nac is word number: 53
   ekil is word number: 54
   emit is word number: 55
     on is word number: 56
   tsuj is word number: 57
    mih is word number: 58
   wonk is word number: 59
   ekat is word number: 60
 elpoep is word number: 61
   otni is word number: 62
   raey is word number: 63
   ruoy is word number: 64
   doog is word number: 65
   emos is word number: 66
  dluoc is word number: 67
   meht is word number: 68
    ees is word number: 69
  rehto is word number: 70
   naht is word number: 71
   neht is word number: 72
    won is word number: 73
   kool is word number: 74
   ylno is word number: 75
   emoc is word number: 76
    sti is word number: 77
   revo is word number: 78
  kniht is word number: 79
   osla is word number: 80
   kcab is word number: 81
  retfa is word number: 82
    esu is word number: 83
    owt is word number: 84
    woh is word number: 85
    ruo is word number: 86
   krow is word number: 87
  tsrif is word number: 88
   llew is word number: 89
    yaw is word number: 90
   neve is word number: 91
    wen is word number: 92
   tnaw is word number: 93
esuaceb is word number: 94
    yna is word number: 95
  eseht is word number: 96
   evig is word number: 97
    yad is word number: 98
   tsom is word number: 99
     su is word number: 100

Process finished with exit code 0

References:
https://www.codingame.com/playgrounds/14213/how-to-play-with-strings-in-c/array-of-c-string

A: char *reverseString(char *string)
{
        for (int j = 0, k = strlen(string) - 1; j < k; j++, k--)
        {
            char temp = string[j];
            string[j] = string[k];
            string[k] = temp;
        }
        return string;
}

from main

    // *** reverse function which requires its own function ***
    for (int i = 0; i < NUMBER_OF_STRING; i++)
    {
        reverseString(commonWords[i]);
    }


text:
Q: Consulta SQL onde WHERE tem 2 opções Pretendo fazer uma consulta SQL onde WHERE tenha 2 situações, exemplo:

SELECT * FROM products WHERE name = "%explosion%" OR tag =
  "%explosion%"

Nesta consulta precisaria que, primeiro a consulta verifica-se se existe algum produto com o nome de explosion se existir parasse por ai e retornaria o resultado sem pesquisa na tag se também existe, mas caso não encontre registro no name a query iria procurar na tag.
Dei uma pesquisada em formas de fazer isso e a única forma que me veio é fazer 2 consultas. Fazendo primeiro a pesquisa em name e verificar se retorna alguma coisa e depois fazer em tag se name não retornar nada.
Talvez utilizando a Cláusula join junto com a Cláusula outer deva conseguir mas não consegui compreender o uso de outer bem para desenvolver esta query correta.
Alguem teria uma ideia de fazer isto em apenas 1 consulta sem ter que fazer malabarismo fazendo com 2?

A: Não estou a ver uma forma de fazer sem fazer o uso de join ou subquery. Fica aqui uma solução usando a cláusula EXISTS.
SELECT *
  FROM products
 WHERE name = "%explosion%"      -- Devolve os produtos com nome = '%explosion%'
    OR (                         -- Devolve os produtos com tag = '%explosion' apenas se não existir qualquer produto com nome = '%explosion%'
           tag = "%explosion%"
       AND NOT EXISTS ( SELECT 1 FROM products WHERE name = '%explosion%' )
    )

Não indicou qual o SGBD, mas a solução proposta é portável e deverá funcionar em qualquer SGBD que implemente o standard.
Fiquei sem perceber se o nome e a tag do produto são mesmo '%explosion%' ou se pretende encontrar os registos que contêm essa palavra. Caso seja esse o objectivo deve trocar o = pelo LIKE.


text:
Q: Table partitions in different tablespaces I created a "master table" in one tablespace, then a partition in the same tablespace and a 2nd partition in another tablespace created in a mounted NFS share.
The master table is called documents_master, and I have two child tables called documents_current and documents_old.
So, here's the layout:
   table          | tablespace | location
------------------+------------+------------
documents_master  | public     | /var/lib/postgresql/data
documents_current | public     | /var/lib/postgresql/data
documents_old     | old_data   | /mnt/storage1

Then, I copy data from my "documents" table with the aim of filling documents_current and documents_old by issuing:
insert into documents_master select * from documents;

This fills both child tables as I expect, but when I check the disk space, everything looks like stored in the local disk.
Then, if I change the tablespace for documents_master and documents_current to the "old_data" tablespace, then insert everything again, the data is stored in the mounted partition.
Is this a bug, I'm doing something wrong?.
I'm using PostgreSQL 9.3.9 on x86_64-unknown-linux-gnu, compiled by gcc (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4, 64-bit


text:
Q: How to drag and drop Object3D elements with three.js? I took this example for drag&drop objects, it works perfect. But now I want to group some elements to drag&drop them together. I replaced the Cubes from the example with some Spheres and grouped them together in an Object3D().
var data = [[0,10],[50,20],[100,7],[150,18],[200,15],[250,3],[300,10],[350,25]];
var group = new THREE.Object3D();
    for(var i = 0; i< data.length; i++){
        var mesh = new THREE.Mesh( new THREE.SphereGeometry(data[i][1],20,20), sphereMaterial);
        mesh.position.y = data[i][0];
        mesh.updateMatrix();
        group.add(mesh);
    }
objects.push(group);
scene.add(group);

But I can't select this group of objects in my scene :( What I'm doing wrong? Isn't it possible to select a group? Or how must it look like?

A: It's hard to tell without the code, but i think you might be using .intersectObjects(objects), you should try using .intersectObjects(objects, true) instead.
Here is the documentation :
.intersectObjects( objects, recursive )
objects — The objects to check for intersection with the ray.
recursive — If set, it also checks all descendants of the objects. Otherwise it only checks intersecton with the objects.
checks all intersection between the ray and the objects with or without the descendants.
three.js Raycaster


text:
Q: Border values in table overwrite neighbours I am writing a C program, in which I try to dynamically allocate a 2-dim array (or an array of arrays.) After the table is allocated I try to iterate over it, but it throws an error about illegal memory access and creates a coredump.
After some investigation I've found out a curious thing: the array I experiment with is 4x4, but when I set array[0][3] = 123; it sets both [0][3] and [1][0] positions to be 123. Exactly the same thing happens if I assign array[1][0] = 123;, as it sets both [0][3] and [1][0] to the rightside value. Similar assignment is done for any "border values", like [2][0] and [1][3]. I guess something must be wrong with my allocation, but I can't figure it out. I was pretty sure that this is the way to dynamically allocate multi-dim arrays and a bit of research confirmed it. Here is my code (I know it should be SSSCE but I can't provide it shorter and still show the problem):
typedef struct {
    int rows;
    int columns;
    double **data;
} matrix;

matrix* allocateMatrix(int inputRows, int inputColumns) {
    matrix *matrixPointer = calloc(1, sizeof(matrix));
    matrixPointer->rows = inputRows;
    matrixPointer->columns = inputColumns;
    #ifdef DOUBLE
        matrixPointer->data = calloc(inputRows, sizeof(double*));
    #else
        matrixPointer->data = calloc(inputRows, sizeof(float*));
    #endif
    if (matrixPointer->data == NULL) {
        printf("Error - inputRows value appears to be wrong.");
        return NULL;
    }

    int i, j;
    for (i = 0; i < inputRows; i++) {
    #ifdef DOUBLE
        matrixPointer->data[i] = calloc(inputColumns, sizeof(double));
    #else
        matrixPointer->data[i] = calloc(inputColumns, sizeof(float));
    #endif
        if (matrixPointer->data[i] == NULL) {
            printf("Error - inputColumns value appears to be wrong.");
            return NULL;
        }
    }
    matrixPointer->data[2][0] = 123;    //TEST CODE;

    return matrixPointer;
}

And some code to see the contents of such created array:
matrix *lol = allocateMatrix(4, 4);
    int i, j;
    for (i = 0; i < lol->rows; i++)
            for (j = 0; j < lol->columns; j++)
                printf("%f ", lol->data[i][j]);

Is my memory allocation wrong, or maybe some other issue I fail to see. I would be grateful for any suggestions or help. Thank you in advance.

A: typedef struct {
    int rows;
    int columns;
    double **data;
} matrix;

This is the culprit. The DOUBLE macrodefinition was supposed to enable double precision through the code, but when the flag was not set the code still allocated double** data, causing possible segmentation faults. The correct code in this case should look like:
typedef struct {
    int rows;
    int columns;
    #ifdef DOUBLE
        double **data;
    #else
        float **data;
    #endif
} matrix;


text:
Q: How to make html_url into hyperlinks from fetch/json I am learning javascript and Json so please bear with me.
I have fetched certain json data and made it visible on my webpage. All this through my GitHub api. I have three repositories in total and each contain the name of the repository a description and a html_url. I would like to make the three html_url active. So the user can click directly on them and go to that repository. I've been trying and googling but have yet to have any success. Any tips would be hugely appreciated.
Below is my js code.
`
function load () {

    element = document.getElementById("gitRepos");
    element.classList.toggle("hide");

    const loadingStatus = document.querySelector('#gitRepos')

let url = "https://api.github.com/users/PaulEvans78/repos"

async function  getrepo() {

    let response = await fetch(url);

    const repoList = document.getElementById("gitRepos")
    const links = document.getElementById("gitRepos")

    if(response.ok) {
        let data = await response.json();
        loadingStatus.innerText = " "
        console.log(data);
        for (const item of data){
            createRepoLi(repoList, item.name, item.html_url, item.description)
        }

    } else {

        console.log("HTTP-Error: " + response.status);
        }
    }

    function createRepoLi(repoList, name, html_url, description){
        const li = document.createElement('li')
        li.innerText = name + "\n " +  html_url + "\n " + description
        li.classList.add("gitHubStyle");
        repoList.appendChild(li)
    }

    getrepo();

}

`


text:
Q: PHP 7 user sessions issue - Failed to initialize storage module A bug exists when using various PHP framework session drivers with PHP 7.0. I initially experienced this issue while using the CodeIgniter database driver and assumed it was a CodeIgniter issue but have since experienced it on multiple sessions drivers and multiple frameworks. At this point I have safely concluded that the type of  session driver is irrelevant - seemingly at random, the application will crash and the logs (I've tried both Apache and php-fpm + nginx) fill up with the following:

PHP Fatal error:  session_start(): Failed to initialize storage
  module: user (path: [whatever I have in my php.ini path])

The drivers I am using do not use the values set in php.ini and regardless of whether I set the session.save_handler to files, redis, etc in php.ini and regardless of the path I set (Redis server if redis, fully-writable folder with files enabled) the errors occur. The path here should never be hit unless a native "session_start()" is called in a php file outside of the framework. Also, calling "session_start()" outside of the framework works fine... so clearly PHP can access the path. It's as if at some point, the sessions driver becomes a hybrid of the framework driver and whatever is set in php.ini. The error message always has "user" for the session.save_handler so obviously that's not being pulled from php.ini... but the path is. Why would this be happening? This is one of those issues that is difficult to describe until you have experienced it... and it's difficult to reproduce because everything seems to work fine even for hundreds of sessions (until it suddenly stops working). Restarting Apache does not correct the issue either - there are a number of issues at play here and I end up just rebooting the machine to avoid the downtime. Obviously the PHP 7 machine will be pulled out of the load balancer rotation now... but I was hoping to have things figured out by now.
I have experienced the issue with PHP 7.0 RC5, RC6, & RC8 compiled on my own as well as the latest Ondřej Surý PPA on Ubuntu 15.10 Wily (7.0.0-2+deb.sury.org~wily+1). I have experienced the issue on CodeIgniter & Symfony, and have experienced the issue regardless of the type of driver used in the framework (files, database, redis) or the session.save_handler set in php.ini (which, again, should be irrelevant here but just thought it should be mentioned). I keep trying combinations and throwing things out in the wild and this issue happens every single time (sometimes it takes 12+ hours depending on the traffic to the website).
Thanks for any help you can provide! I'm open to suggestions and willing to try anything at this point.

A: This error occurs when the open() function of the session handler doesn't return boolean TRUE, which obviously means some kind of failure.
It could be failure to connect to a database, failure to open a file, a non-existent directory, etc. - that depends on what the session handler actually uses.

A: function _open should return true to avoid this error.
It can not be null or empty whatever we use either database or file.
When we use database to store session data, we keep it blank or no Boolean return. that is the main reason for this error.
class session_handler
{
    public function __construct()
    {
        session_set_save_handler(
            array($this, "_open"),
            array($this, "_close"),
            array($this, "_read"),
            array($this, "_write"),
            array($this, "_destroy"),
            array($this, "_gc")
        );
    }

    public function _open($savePath, $sessionId)
    {
        return true;
    }

    public function _close() {  }
    public function _read($id) {  }
    public function _write($id, $data) {  }
    public function _destroy($id) {  }
    public function _gc($max) {  }
}

It is only for PHP 7. I do not know it is a bug or not.

A: This is usually is due to the session not being able to connect to whichever driver it uses (file, database).
I resolved the issue by looking at the config.php file
    $config['sess_driver'] = 'database';
    $config['sess_cookie_name'] = 'ci_session';
    $config['sess_expiration'] = 7200;
    $config['sess_save_path'] = 'ci_sessions';
    $config['sess_match_ip'] = FALSE;
    $config['sess_time_to_update'] = 300;
    $config['sess_regenerate_destroy'] = FALSE;

So since I used a database it means that it doesn't connect for some reason!
(For files probably it doesn't have the permission to write the cached files )
Next I turned on the log
    $config['log_threshold'] = 4;

Where 4 = All Messages.. Then refresh the page, and now I have in application/logs a file called log-#.php where # is a date.
    INFO - 2017-08-30 10:05:41 --> Database Driver Class Initialized
    ERROR - 2017-08-30 10:05:41 --> Severity: Warning --> mysqli::real_connect(): (HY000/1045): Access denied for user 'user'@'localhost' (using password: YES) /var/system/database/drivers/mysqli/mysqli_driver.php 202
    ERROR - 2017-08-30 10:05:41 --> Unable to connect to the database
    ERROR - 2017-08-30 10:05:41 --> Severity: Warning --> mysqli::real_connect(): (HY000/1045): Access denied for user 'user'@'localhost' (using password: YES) var/system/database/drivers/mysqli/mysqli_driver.php 202
    ERROR - 2017-08-30 10:05:41 --> Severity: Error --> session_start(): Failed to initialize storage module: user (path: ci_sessions) /var/system/libraries/Session/Session.php 140

So I just make sure that the user can access the database and it worked.

A: I decided to migrate my system and do some much-needed updating. I ran into this issue using Codeigniter 3 and php 7.2. After I found the issue I realized how ridiculous it was and wonder how I didn't figure it out sooner.
Anyway here is the solution at least for me.
Obviously make sure memcacheD is installed:
sudo apt-get update
sudo apt-get install php7.2-memcached

If that is good to go then we can proceed to check everything else.
In Codeigniter's config file "/application/config/config.php" there is a section to to specify session options:
$config['sess_driver'] = 'memcached';
$config['sess_cookie_name'] = 'some_session_name';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

The line that needed to be changed for me was this line:
$config['sess_save_path'] = NULL;

Make sure you set this to a valid path as documented in CI3's manual.
The correct setting will look like this:
$config['sess_driver'] = 'memcached';
$config['sess_save_path'] = 'localhost:11211';

Make sure you change "localhost" to reflect your memcached servers location.
For more info see - Codeignier Session Manual
Also have a look here: php memcacheD Sessions support
In case the comment on the page is removed I am posting here:

If you want to use 'memcacheD' extention not 'memcache' (there are
  two diffrent extentions) for session control,  you should pay
  attention to modify php.ini
Most web resource from google is based on memcache because It's
  earlier version than memcacheD. They will say as following
session.save_handler = memcache session.save_path =
  "tcp://localhost:11211"
But it's not valid when it comes to memcacheD
you should modify php.ini like that
session.save_handler = memcached session.save_path = "localhost:11211"
Look, there is no protocol indentifier

For testing I did this to make user that php it's self wasn't having an  issue accessing memcacheD:
session_start();

    header('Content-Type: text/plain');
    session_start();
    if(!isset($_SESSION['visit']))
    {
        echo "This is the first time you're visiting this server\n";
        $_SESSION['visit'] = 0;
    }
    else
            echo "Your number of visits: ".$_SESSION['visit'] . "\n";

    $_SESSION['visit']++;

    echo "Server IP: ".$_SERVER['SERVER_ADDR'] . "\n";
    echo "Client IP: ".$_SERVER['REMOTE_ADDR'] . "\n";
    print_r($_COOKIE);

$servers = explode(",", ini_get("session.save_path"));
$c = count($servers);
for ($i = 0; $i < $c; ++$i) {
  $servers[$i] = explode(":", $servers[$i]);
}

$mem = new memcached();

$mem->addServer('127.0.0.1', '11211', '1');
$mem->set('011', 'Hello There');

print_r($mem->get('011'));

print_r($mem->getAllKeys());

This allowed me to see that memcacheD was working ok.
Also in your php.ini there are some options to look out for. Just search for [session] or session.save_path. CI3 stated it doesn't use this option from the php.ini file, but it's prob worth setting if you plan to use memcacheD outside the framework and for consistency.
This starts around line ~1327 in the php.ini file:
[Session]
; Handler used to store/retrieve data.
; http://php.net/session.save-handler
session.save_handler = memcached

; Argument passed to save_handler.  In the case of files, this is the path
; where data files are stored. Note: Windows users have to change this
; variable in order to use PHP's session functions.
;
; The path can be defined as:
;
;     session.save_path = "N;/path"
;
; where N is an integer.  Instead of storing all the session files in
; /path, what this will do is use subdirectories N-levels deep, and
; store the session data in those directories.  This is useful if
; your OS has problems with many files in one directory and is
; a more efficient layout for servers that handle many sessions.
;
; NOTE 1: PHP will not create this directory structure automatically.
;         You can use the script in the ext/session dir for that purpose.
; NOTE 2: See the section on garbage collection below if you choose to
;         use subdirectories for session storage
;
; The file storage module creates files using mode 600 by default.
; You can change that by using
;
;     session.save_path = "N;MODE;/path"
;
; where MODE is the octal representation of the mode. Note that this
; does not overwrite the process's umask.
; http://php.net/session.save-path
;session.save_path = "/var/lib/php/sessions"
session.save_path = "locahost:11211"

One other place to check settings is the mecacheD server config file. Depending on the system it's location may vary. For me, it was located under the /etc/ directory.
/etc/memcached.conf

Image for reference to the errors I was getting:

EDIT
If you are using socket i.e. unix:///some/place/memcached.sock to connect to Memcached server it's not documented on exactly how to make this work. You simply do the following in your config:
$config['sess_save_path'] = "/some/place/memcached.sock:11211";

A: Its working perfect.
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = sys_get_temp_dir();
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;

A: In my case I'm using PHP ver 5.6 with CI ver 3.4 (Codeigniter)
Server: BIGROCK
I found these problems in my live server.
Then after long time. I just tried to delete my Database and re Create it.
Then only I went know that I didn't give permission The User to Access the Database.
So When you have finished Creating your Database and User, You should probably give permissions ( previlleges ) to the user to access the Database.
Let me know if it useful in your case. Thank you.

A: Just changed the permissions of /your-Codeigniter-project/system/cache and its contents to 0777 and it worked. It's actually unable to create the session files due to missing permissions. Use the following command sudo chmod 0777 /your-Codeigniter-project/system/cache
sudo chmod 0777 /your-Codeigniter-project/system/cache/*
Note: Replace 'your-Codeigniter-project' above with your project path.

A: *

*Find default session tmp folder (session.save_path)  with phpinfo(); on yourdomain.com

*connect to your host via ssh

*go to tmp parent folder $ cd /home/abc/xyz

*chmod 777 -R tmp

A: i change on my php.ini:
session.save_path = "N;/path" **to** session.save_path = "/tmp"

and i restart my php7-fpm

A: I believe I have figured out the issue; I will close out this question. Basically, it appears that when an issue occured with the framework session driver/config (sql connections exceeded, out of memory issue with Redis, etc) it would revert to attempting to use the sess.save_path set in php.ini while still using the framework session driver. So unless the framework driver is compatible with the default sess.save_path in php.ini, this error occurs. To me, it would make more sense to also revert to the sess.save_handler in php.ini as well... but if this is a problem obviously there are bigger issues with the app configuration that need to be resolved.
It's not this error itself breaking sessions... it was an underlying issue with the framework session drivers. I feel dumb... but the logs basically sent me on a wild goose chase. Restarting nginx or Apache would not resolve the issue since the issue was elsewhere. I believe there are still kinks to be worked out with the available PHP 7 Redis libraries and the SQL issues were my fault. After seemingly trying a number of combinations and getting the same result, the issue appeared more cryptic. I still get strange errors using Redis sessions on PHP 7 but, like I said, the PHP 7 Redis library is not very mature.

A: We just ran into a similar issue, where we were setting our own custom handler with session_set_save_handler to go to memcached, but kept getting this error:
Warning: session_write_close(): Failed to write session data (user). Please verify that the current setting of session.save_path is correct (/var/lib/php/7.0/session) in Unknown on line 0
Turns out that the "write" function needs to return a boolean value (just like start), but it's the only function for session_set_save_handler that doesn't mention any return values in the official PHP docs. So while it looks like it's reverting to the default session handler, it's just giving the error for the default session handler.
The error nor the doc pages would never have led us to a solution...

A: This happens only if the session_save_path is not valid, if you are storing your session data in a database then the session table must be created so that CI saves the data else you will end up with this error. Hope helped someone

A: I had to upgrade my code ignitor to the latest version to solve this problem.
Running on:
CentoOS: 7.6.1810
Mysql: 8.0.15
PHP: PHP 7.3.4

I tried a lot of things like moving the session from the database to files and Memcached. Nothing worked. The only thing that fixed it was going from CI 3.0 to 3.1 and boom it just worked like it was supposed to.
Hope it helps someone.

A: This error is caused because of the undefined session path.
Open application/config/config.php line no. 383.
Replace the below line
$config['sess_save_path'] = NULL;
with
$config['sess_save_path'] = APPPATH . 'cache/session/';
Don't forget to give write permission to cache/session folder.


text:
Q: lstinline has Invalid UTF-8 byte 167 Possible duplicate of this question
MWE:
\documentclass[%
  parskip=full,% empty line after each paragraph.
  twoside=false% not a 2-sided print for a book.
]{scrbook}

% \usepackage[utf8]{inputenc} % For non-English languages
\usepackage[latin1]{inputenc} % listings needs this encoding instead!

\usepackage{listings, tcolorbox}

\usepackage{tcolorbox}
\tcbuselibrary{listings,skins,theorems,xparse}
\NewTotalTCBox{\inlinebox}{ O{white} v}
{ tcbox raise base,
  arc=2pt,
  nobeforeafter,% makes the box inline
  colback=#1!10!white,% pales given color for background
  boxsep=0pt,left=1pt,right=1pt,top=2pt,bottom=2pt,
  boxrule=0pt}
{\lstinline[style=tcblatex,texcsstyle=*\color{blue}\bfseries]§#2§}
\newcommand\cil{\inlinebox[green]}

\begin{document}

\cil|\TeX| (\TeX) is a control word because it is made up of letters. Any non-letter will end the sequence.

\end{document}

This all works if I do \UseRawInputEncoding, as per this answer.
Should I do that? Or is there something more correct that I should do?
\usepackage[latin1]{inputenc} also works, by the way.

A: The problematic part is:
\lstinline[...]§#2§

The character § is not an ASCII character.
8-bit TeX engines (TeX, pdfTeX)
Since package listings does not support multi-byte encodings, the text encoding is limited to an 8-bit encoding as latin1. This encoding should then
be declared by
\usepackage[latin1]{inputenc}

For greater portability, I recommend to use a different fence character from the ASCII range (|, &, ...). This avoids problems, when the input file encoding is changed to UTF-8.
Unicode engines (LuaTeX, XeTeX)
Here, the character § is just one character (big char) and it can be used as fence character for \lstinline of package listings.
However, the best supported input encoding for LuaTeX or XeTeX is UTF-8. Therefore, the input file should be re-encoded from Latin-1 to UTF-8.


text:
Q: Using awk to sum the values of a column, based on the values of another column, append the sum and percentage to original data This question is more or less a variant on
https://unix.stackexchange.com/questions/242946/using-awk-to-sum-the-values-of-a-column-based-on-the-values-of-another-column
Same input:
smiths|Login|2
olivert|Login|10
denniss|Payroll|100
smiths|Time|200
smiths|Logout|10

I would like to have the following result:
smiths|Login|2|212
olivert|Login|10|10
denniss|Payroll|100|100
smiths|Time|200|212
smiths|Logout|10|212

Hence, the sum of column 3 for all entries with the same pattern in column 1 should be appended.
In addition, append another column with the percentage, yielding the following result:
smiths|Login|2|212|0.94
olivert|Login|10|10|100
denniss|Payroll|100|100|100
smiths|Time|200|212|94.34
smiths|Logout|10|212|4.72

A: Here's one that doesn't round the percentages but handles division by zero errors:
Adding to test data a couple of records:
$ cat >> file
test|test|
test2|test2|0

Code:
$ awk '
BEGIN { FS=OFS="|" }
NR==FNR { s[$1]+=$3; next }
{ print $0,s[$1],$3/(s[$1]?s[$1]:1)*100 }
' file file

Output:
smiths|Login|2|212|0.943396
olivert|Login|10|10|100
denniss|Payroll|100|100|100
smiths|Time|200|212|94.3396
smiths|Logout|10|212|4.71698
test|test||0|0
test2|test2|0|0|0

A: gawk approach:
awk -F'|' '{a[$1]+=$3; b[NR]=$0}END{ for(i in b) {split(b[i], data, FS);
     print b[i] FS a[data[1]] FS sprintf("%0.2f", data[3]/a[data[1]]*100) }}' file

The output:
smiths|Login|2|212|0.94
olivert|Login|10|10|100.00
denniss|Payroll|100|100|100.00
smiths|Time|200|212|94.34
smiths|Logout|10|212|4.72


text:
Q: How to identify checked and unchecked exceptions in java? While reading about exception, I will always come across checked exceptions and unchecked exceptions, So wanted to know how to distinguish that which is what?
Edit: I want to know if i create any exception class then how can i create as a checked or as an unchecked?
and what is the significance of each?

A: See the Java Language Spec, chapter 11:

The unchecked exceptions classes are the class RuntimeException  and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers.

You could check this via instanceof at runtime, though I don't really see where this would be useful.
As to the second part of your question:

*

*checked exception represent expected error conditions, which can occur during normal program execution and therefore always have to be handled programatically (which the compiler enforces)

*unchecked exception represent unexpected error conditions and signify an abnormal state of your program, due to invalid input, bugs or runtime restrictions (eg memory); the compiler won't force the programmer to handle these, ie you only have to care for them if you know of their occurrence

A: Java checked vs unchecked exception

*

*Error is internal VM error and usually you can not manage it.

*Exception - you are able to catch and handle it

Checked vs Unchecked

*

*checked exception is checked by the compiler and as a programmer you have to handle it using try-catch-finally, throws

*unchecked exception is not checked by the compiler but you optionally can manage it explicitly

IntelliJ IDEA's Type Hierarchy tool is useful when you want to find more

A: All Throwables except subclasses of java.lang.RuntimeException or java.lang.Error are checked. Properly, in Java, "exceptions" are subclasses of java.lang.Exception, "errors" are subclasses of java.lang.Error and java.lang.Throwable is not usually subclassed directly.
Programs are not supposed to create their own Error subclasses (though the documentation is rather ambiguous on that) so generally you always create Exceptions, using a RuntimeException if you don't want it to be checked.
To know at run-time if you have a checked exception you could use:
if(throwable instanceof Exception && !(throwable instanceof RuntimeException)) {
    // this is a checked Exception
    }

A checked exception is one which must be either handled in a catch clause, or declared as being thrown in the method signature; the compiler enforces this.  Generally, one uses checked exceptions for exceptions which should be handled by the calling code, while unchecked exceptions are for conditions which are the result of a programming error and should be fixed by correcting the code.
That said there is much debate in the Java community about the efficacy of using checked exceptions vs. unchecked exceptions everywhere - a subject way to deep to discuss in this answer.
EDIT 2012-10-23: In response to comments (which are quite valid), to clarify, the following would be what is required to determine if a captured Throwable is a checked  Throwable as opposed to a checked Exception:
if(obj instanceof Throwable && !(obj instanceof RuntimeException) && !(obj instanceof Error)) {
    // this is a checked Throwable - i.e. Throwable, but not RuntimeException or Error
    }

If the object in question is known to be an instance of Throwable (e.g. it was caught), only the second part of the above 'if' is needed (e.g. testing for Throwable is redundant).

A: If the exception class is a subclass of RuntimeException, it's not checked and does not have to be declared for functions or caught, etc. Error exceptions also do not have to be declared/caught.  Is that what you're asking?

A: Quite sure this will have been asked and answered before, but for the sake of it, it is covered quite nicely here: http://www.javapractices.com/topic/TopicAction.do?Id=129.
Strictly speaking, unchecked exceptions will always extend RuntimeException whereas checked exceptions do not. The mentioned link explains when to use either.
As their name indicates, callers are obliged to deal with checked exceptions, typically handling them (try/catch) or passing them further up the stack. Unchecked exceptions are usually deemed to be caused by elements outside of the caller's control.

A: package practice;

import java.io.IOException;

class Practice
{
    public static void main(String args[])
    {
        Exception n=new NullPointerException();
        if(n instanceof RuntimeException)
        {
            System.out.println("this is a runtime(unchecked) exception");
        }
        else
        {
            System.out.println("this is not a compiletime(checked) exception");
        }

    }

}


text:
Q: How To define Command and CommandTarget in RibbonMenuButton Good morning; I my application WPF/C# i use Ribbon Control, i want to define a Cammand and CommandTarget for my RibbonMenuButton.
I have this code but my command don't work :(
 <RibbonMenuButton LargeImageSource="Resources/Images/new.png" Label="New" KeyTip="N" >
                    <RibbonMenuButton.ItemContainerStyle>
                        <Style TargetType="MenuItem">
                            <Setter Property="Command" Value="{x:Static ApplicationCommands.New}" />
                            <Setter Property="CommandTarget" Value="{Binding ElementName=MyDesigner}"/>
                        </Style>
                    </RibbonMenuButton.ItemContainerStyle>
                </RibbonMenuButton>

Can you help me !

A: my probleme solved like this:
<RibbonTab Header=" File ">
            <RibbonGroup Header="File">

                <RibbonButton  Command="{x:Static ApplicationCommands.New}" CommandTarget="{Binding ElementName=MyDesigner}"  LargeImageSource="Resources/Images/new.png" Label="New" KeyTip="N"></RibbonButton>

                <RibbonButton SmallImageSource="Resources/Images/Open-3.png" Label=" Open " Command="{x:Static ApplicationCommands.Open}" CommandTarget="{Binding ElementName=MyDesigner}"/>
                <RibbonButton SmallImageSource="Resources/Images/Save_black-128.png" Label=" Save " Command="{x:Static ApplicationCommands.Save}" CommandTarget="{Binding ElementName=MyDesigner}"/>
                <RibbonButton SmallImageSource="Resources/Images/Print-icon.png" Label=" Print " Command="{x:Static ApplicationCommands.Print}" CommandTarget="{Binding ElementName=MyDesigner}"/>
            </RibbonGroup>

i have changed the RibbonMenuButton to RibbonButton(with LargeImageSource to preserve the same presentation with RibbonMenuButton).... The RibbonButton alow to define Command and CommandTarget :)


text:
Q: Отменить автоматическое добавление блока комментариев при создании класса Когда создаю новый класс, по умолчанию перед объявлением класса появляется блок комментариев
/**
* Created by ...
*/

Как сделать так, чтобы эти комментарии не добавлялись при создании класса?

A: Ctrl+Alt+S -> File and Code Templates-> Other
Удалить #parse("File Header.java") в *.java


text:
Q: Does tensorflow allow LSTM deconvolution ( convlstm2d) as it does for 2D convolution? I am trying to augment a network. For the convolution part, I am using convlstm2d from keras. Is there a process to perform deconvolution ( i.e. lstmdeconv2d ? )

A: There is Conv3D for that, checkout this example used to predict the next frame

A: It should be possible to combine any model with the TimeDistributed wrapper. So you can create a deconv-model, and apply it on the output (which is a sequence of vectors) of the LSTM using the TimeDistributed wrapper.
An example. First create a deconv network using Conv2DTranspose layers.
from keras.models import Model
from keras.layers import LSTM,Conv2DTranspose, Input, Activation, Dense, Reshape, TimeDistributed

# Hyperparameters
layer_filters = [32, 64]

# Deconv Model
# (adapted from https://github.com/keras-team/keras/blob/master/examples/mnist_denoising_autoencoder.py )

deconv_inputs = Input(shape=(lstm_dim,), name='deconv_input')
feature_map_shape = (None, 50, 50, 64) # deconvolve from [batch_size, 50,50,64] => [batch_size, 200,200,3]
x = Dense(feature_map_shape[1] * feature_map_shape[2] * feature_map_shape[3])(deconv_inputs)
x = Reshape((feature_map_shape[1], feature_map_shape[2],feature_map_shape[3]))(x)
for filters in layer_filters[::-1]:
   x = Conv2DTranspose(filters=16,kernel_size=3,strides=2,activation='relu',padding='same')(x)
x = Conv2DTranspose(filters=3,kernel_size=3, padding='same')(x) # last layer has 3 channels
deconv_output = Activation('sigmoid', name='deconv_output')(x)
deconv_model = Model(deconv_inputs, deconv_output, name='deconv_network')

Then, you can apply this deconv-model to the outputs of your LSTM using the TimeDistributed layer.
# LSTM
lstm_input = Input(shape=(None,16), name='lstm_input') # => [batch_size, timesteps, input_dim]
lstm_outputs =  LSTM(units=64, return_sequences=True)(lstm_input) # => [batch_size, timesteps, output_dim]
predicted_images = TimeDistributed(deconv_model)(lstm_outputs)

model = Model(lstm_input , predicted_images , name='lstm_deconv')
model.summary()


text:
Q: 'node with name "rabbit" is already running on host' even after killing the processes Whenever I try to run a rabbit server, it meets me with this error:
ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R"

I've read that I should kill the processes of rabbit by using
rabbitmqctl stop

But I still get the error, What else can I do
I am on windows 10
Here is my full error
2022-11-11 16:46:03.015000-08:00 [error] <0.131.0>
2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> BOOT FAILED
2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> ===========
2022-11-11 16:46:03.015000-08:00 [error] <0.131.0> ERROR: node with name "rabbit" is already
running on host "DESKTOP-BKRTA3R"
2022-11-11 16:46:03.015000-08:00 [error] <0.131.0>
BOOT FAILED
===========
ERROR: node with name "rabbit" is already running on host "DESKTOP-BKRTA3R"

2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>     supervisor: {local,rabbit_prelaunch_sup}
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>     errorContext: start_error
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>     reason: {duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"}
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>     offender: [{pid,undefined},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {id,prelaunch},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {mfargs,{rabbit_prelaunch,run_prelaunch_first_phase,[]}},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {restart_type,transient},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {significant,false},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {shutdown,5000},
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>                {child_type,worker}]
2022-11-11 16:46:04.017000-08:00 [error] <0.131.0>
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>   crasher:
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     initial call: application_master:init/4
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     pid: <0.129.0>
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     registered_name: []
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     exception exit: {{shutdown,
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>                          {failed_to_start_child,prelaunch,
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>                              {duplicate_node_name,"rabbit",
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>                                  "DESKTOP-BKRTA3R"}}},
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>                      {rabbit_prelaunch_app,start,[normal,[]]}}
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>       in function  application_master:init/4 (application_master.erl, line 142)
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     ancestors: [<0.128.0>]
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     message_queue_len: 1
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     messages: [{'EXIT',<0.130.0>,normal}]
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     links: [<0.128.0>,<0.44.0>]
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     dictionary: []
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     trap_exit: true
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     status: running
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     heap_size: 376
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     stack_size: 28
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>     reductions: 167
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>   neighbours:
2022-11-11 16:46:04.017000-08:00 [error] <0.129.0>
2022-11-11 16:46:04.043000-08:00 [notice] <0.44.0> Application rabbitmq_prelaunch exited with reason: {{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"}}},{rabbit_prelaunch_app,start,[normal,[]]}}
{"Kernel pid terminated",application_controller,"{application_start_failure,rabbitmq_prelaunch,{{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,\"rabbit\",\"DESKTOP-BKRTA3R\"}}},{rabbit_prelaunch_app,start,[normal,[]]}}}"}
Kernel pid terminated (application_controller) ({application_start_failure,rabbitmq_prelaunch,{{shutdown,{failed_to_start_child,prelaunch,{duplicate_node_name,"rabbit","DESKTOP-BKRTA3R"}}},{rabbit_prelaunch_app,start,[normal,[]]}}})

A: Try removing the process with a PID and using taskkill.
set /p pid=<%~dp0rabbitmq.pid
taskkill /F /PID %pid%
del /F /Q %~dp0rabbitmq.pid


text:
Q: Are there any non-trival sequences which satisfy these conditions? Suppose $a_k$ is a sequence of real numbers such that $$\sum_{k = 1}^{\infty} a_k = \sum_{k = 1}^{\infty} a_k^2 = \sum_{k = 1}^{\infty} a_k^3 = \cdots = \sum_{k = 1}^{\infty} a_k^n < + \infty$$ for all $n \in \mathbb{N}$.
Are there any sequences other than $a_k = 0$ that satisfy this condition?
I suspect not, but I have not figured out how to show this.