text:
Q: Why are POSIX mandatory utilities not built into the shell? The purpose of this question is to answer a curiosity, not to solve a particular computing problem. The question is: Why are POSIX mandatory utilities not commonly built into shell implementations?
For example, I have a script that basically reads a few small text files and checks that they are properly formatted, but it takes 27 seconds to run, on my machine, due to a significant amount of string manipulation. This string manipulation makes thousands of new processes by calling various utilities, hence the slowness. I am pretty confident that if some of the utilities were built in, namely grep, sed, cut, tr, and expr, then the script would run in a second or less (based on my experience in C).
It seems there would be a lot of situations where building these utilities in would make the difference between whether or not a solution in shell script has acceptable performance.
Obviously, there is a reason it was chosen not to make these utilities built in. Maybe having one version of a utility at a system level avoids having multiple unequal versions of that utility being used by various shells. I really can't think of many other reasons to keep the overhead of creating so many new processes, and POSIX defines enough about the utilities that it does not seem like much of a problem to have different implementations, so long as they are each POSIX compliant. At least not as big a problem as the inefficiency of having so many processes.

A: From the BASH reference manual,

Builtin commands are necessary to implement functionality impossible or inconvenient to obtain with separate utilities.

As I'm sure you've heard, the UNIX philosophy relies heavily on multiple applications  that all have limited functionality. Each built-in has a very good reason why it is built in. Everything else is not. I think a more interesting class of questions is along the lines of, "why exactly is pwd built-in?"

A: The guys at AT&T asked themselves the same thing
If you look at the history of the AT&T Software Toolkit (currently lying dormant on github since the core team left), this is exactly what they did with the AT&T Korn shell, a.k.a. ksh93.
Performance was always part of the motivation for the ksh93 maintainers, and when building ksh you can choose to build many common POSIX utilities as dynamically loaded libraries. By binding these commands to a directory name like /opt/ast/bin, you could control which version of the command would be used, based on the position of that directory name in $PATH.
Examples:
cat chmod chown cksum cmp cp cut date expr fmt head join ln
mkdir mkfifo mktemp mv nl od paste rm tail tr uniq uuencode wc

The full list can be found in the github ast repository.
Note that most of the ast tools have their own provenance and would differ strongly from the more common gnu implementations. The AT&T Research team abided by official standards, which was the way to achieve interoperability when you could not share code.

A:
Why are POSIX mandatory utilities not built into shell?

Because to be POSIX compliant, a system is required1 to provide most utilities as standalone commands.
Having them builtin would imply they have to exist in two different locations, inside the shell and outside it. Of course, it would be possible to implement the external version by using a shell script wrapper to the builtin, but that would disadvantage non shell applications calling the utilities.
Note that BusyBox took the path you suggested by implementing many commands internally, and providing the standalone variant using links to itself. One issue is while the command set can be quite large, the implementations are often a subset of the standard so aren't compliant.
Note also that at least ksh93, bash and zsh go further by providing custom methods for the running shell to dynamically load builtins from shared libraries. Technically, nothing then prevents all POSIX utilities to be implemented and made available as builtins.
Finally, spawning new processes has become quite a fast operation with modern OSes. If you are really hit by a performance issue, there might be some improvements to make your scripts run faster.
1 POSIX.1-2008

However, all of the standard utilities, including the regular
  built-ins in the table, but not the special built-ins described in
  Special Built-In Utilities, shall be implemented in a manner so that
  they can be accessed via the exec family of functions as defined in
  the System Interfaces volume of POSIX.1-2008 and can be invoked
  directly by those standard utilities that require it (env, find, nice,
  nohup, time, xargs).

A: So we didn't marshal resources into optimizing the original tool, to meet every specific desire.  I guess what we need to explain is how much this specific desire would have cost to implement.

POSIX defines enough about the utilities that it does not seem like much of a problem to have different implementations.

this is a bad assumption :-P.
Post-POSIX systems continue to become more powerful and convenient for good reasons; as an after-the-fact standard it never actually catches up.
Ubuntu started an effort to switch to a stripped-down POSIX shell for scripts, to optimize the old System V init boot process.  I'm not saying it failed, but it did trigger many bugs that had to be cleaned up: "bashisms", scripts which ran under /bin/sh while assuming that bash features were available.
POSIX sh is not a good general-purpose programming language.  Its primary purpose is to work well as an interactive shell.  As soon as you start to save your commands to a script, be aware that you approach a Turing tarpit.  E.g. it's not possible to detect failures in the middle of a normal pipeline.  bash added set -o pipefail for this, but this is not in POSIX.
Similar useful but unstandardized features are provided by almost every  utility more complex than true.
For the class of task you outline, you can draw a rough line to Awk, Perl, and nowadays Python.  Different tools were created, and evolved independently.  Would you expect e.g. GNU Awk to be subsumed into a libutilposixextended?
I'm not saying we now have one universally better approach I can point you to.  I have a soft spot for Python.  Awk is surprisingly powerful, although I've been frustrated by some features being specific to GNU Awk.  But the point is that processing large numbers of strings individually (presumably from lines of the files) was not a design goal of the POSIX shell.

A: There is also the question of: Which shell would you build it into?
Most Unix/Linux systems have multiple different shells which are developed independently(sh/bash/korn/???). If you build the tools into the shell, you would end up with a different implementation of these tools for each shell. This would cause overhead, and you might end up with different features/bugs in for example grep, depending on which shell you used to invoke it.

A: Shell scripts are not expected to run with that type of speed. If you want to improve the speed of your script, try it in perl. If that is still too slow, then you'll have to move to a statically typed language such as java or c, or write a C module for perl that runs the parts which are too slow.
Shell is the first level of prototyping, if you can prove the concept with shell, then move to a better scripting language which can do more bounds checking which would take acres of shell.
A Unix OS is expected to include many small programs which do well defined tasks which make up a larger picture. This is a good thing as it compartmentalises bigger programs. Take a look at qmail, for example and compare that with sendmail. qmail is made of many programs:
http://www.nrg4u.com/qmail/the-big-qmail-picture-103-p1.gif
Exploiting the network daemon would not help you exploit the queue manager.

A: Many have answered well.  I intend only to compliment those answers.  I think the UNIX philosophy is that a tool should do one thing and do it well.  If one tries to make an all encompassing tool, that's lot's more places for failure.  Limiting functionality in this way makes a tool set that's reliable.
Also, consider, if functionality like sed or grep were built into the shell, would it be as easy to invoke from the command line when you'd like it?
In closing, consider, some of the functionality you're desiring to be in BASH, is in BASH.  For example, the ability for RE matching in BASH is implemented using the =~ binary operator (see Shell Grammar in the Manual Page for more, specifically, reference the discussion of the [[ ]] construct for if).  As a very quick example, say I'm searching a file for 2 hex digits:
while read line; do
    if [[ $line =~ 0x[[:xdigit:]]{2} ]]; then
        # do something important with it
    fi
done < input_file.txt

As for sed-like functionality, look under Parameter Expansion in the Expansion heading of the same man page.  You'll see a wealth of things you can do that are reminiscent of sed.  I most often use sed to make some substitution type change to text.  Building off of the above:
# this does not take into account the saving of the substituted text
# it shows only how to do it
while read line; do
    ${line/pattern/substitution}
done < input_file.txt

In the end though, is the above "better" than?
grep -E "[[:xdigit:]]{3}" input_file.txt
sed -e 's/pattern/substitution/' input_file.txt

A: This is, I guess, a historical accident.
When UNIX was created in the late 1960s and early 1970s, computers did not have nearly as much memory as they do today. It would have been possible, at the time, to implement all this functionality as shell builtins, but due to memory limitations, they would have had to limit the amount of functionality that they could implement, or risk out of memory and/or swap trashing problems.
On the other hand, by implementing the given functionality as separate programs, and by making the two required system calls for starting a new process as light as possible, they could create a scripting environment that does not have those problems and that still runs at reasonable speed.
Of course, once those things are implemented as separate processes, people will start them from programs that are not shells, and then they have to remain like that, or suddenly all this software starts breaking.
That's not to say you can't implement some functionality twice, however, and indeed some shells implement some functionality that's supposed to be an external program as a shell builtin; e.g., bash implements the echo command as a builtin, but there's also a /usr/bin/echo


text:
Q: difference between 2 columns (array of strings) and show where the difference is I have created a query to capture Comments by teachers from two different databases. The teachers are adding comments to the front end and they are sent to two different databases. I am able to show the comments for the student for a subject from both the databases. But, I also have to find the minor differences between the two comments coming from both the databases.
I am so far able to compare the two columns (containing the teachers comments). and show null if the two columns are the same. But, I am not able to show where the difference between the two column values is.
Select distinct t1.SStudentID as SStudent, t2.AStudentId as AStudent , t1.Result as Result1,  t2.EnteredValue as Result2,
  COALESCE(NULLIF(t1.Result COLLATE Latin1_General_CI_AI, t2.EnteredValue COLLATE Latin1_General_CI_AI),NULLIF(t2.EnteredValue COLLATE Latin1_General_CI_AI, t1.Result COLLATE Latin1_General_CI_AI)) as NULL_IF_SAME
 from
 (SELECT  distinct r.ID as SStudentID,r.ClassCode,r.TopicComment as Result
  FROM [Database1].[dbo].[StudentAssessmentMarkBook] r
   where r.classcode like '9%' and r.TopicComment != ''
  ) t1
  join
  (SELECT  distinct a.Code as AStudentId ,c.code as ClassCode, ar.EnteredValue
  FROM [Database2].[dbo].[AssessmentItem] a
  join [Database2].[dbo].[ClassGroup] c on c.SubjectId=a.SubjectId
  join [Database2].[dbo].[Result] ar on ar.AssessmentItemId = a.Id
  where c.code like '9%' and a.code like '%COM%') t2 on (t1.ClassCode COLLATE Latin1_General_CI_AI = t2.code COLLATE Latin1_General_CI_AI )
   where (t1.SStudentID = t2.AStudentId)

I now want to show the difference between Result1 and Result2 columns and display in new column where the difference is.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to display a connection between 2 elements of 2 different ListViews in the same screen? Imagine that I have 2 ListViews on the same screen, like this:

So, now I want to connect one element from the left to one element in the right. That connection should be represented using a line.
Any item from the left can be connected to a item from the right. And one item from the left can be connected to multiple rights and one right can only have one left (although this kind of restrictions It should be simple if the first problem is solved).
I can't see a way to do this considering that an user can scroll both lists and that connection should be redrawn after a scroll. Also a connection with a item that is not on the screen (that was scrolled) should have some kind of representation.
Any suggestion on how to do this?
EDIT
The size of each item will be larger so connections will not be that confusing. In max we will have 5-6 connections at a time.

A: You can get the center point of each item you want to connect, and then use drawLines() in android.graphics.canvas
drawLines
view.getLocationOnScreen

A: Mapping every connection, with or without scrolling, sounds like there will be lines going every where and difficult to read. If you set a clickListener on each item that will highlight each connection to the opposing column, that would be easier to read, but you would have to click on every item to see all the connections one at a time.


text:
Q: Add Class To Elements With Specific CSS Property I am creating a script that'll iterate each element under 'body' and will check for its 'background-color'. If this background color matches to '#eb2c33', then the script will add a class to that element or else it'll move to the next element.
I am using this so to avoid going into the html and put that class to elements manually.
Here is my code.
$(document).ready(function (e) {

  $('body *').each(function(index) {

         var rgbg = $(this).css('background-color');
         if(rgbg == "#eb2c33")
         {
                $(this).addClass('jcbg');

              }

      });
});

Now, this function works perfectly if i iterative over a specific div like header or footer etc. But when i iterate over the whole DOM, this function is not working at all.
Please note that i am using a csshook that'll give me color values in Hex rather than rgb so please don't go for that. Any help?
Update:
I know the problem now. It was in that css hook from this post that i was using. i just removed that hook and directly have used rgb value and it started working perfectly. Here is my updated code
$(document).ready(function (e) {

     $('body *').each(function(index) {

         var rgbg = $(this).css('background-color');
         if(rgbg == "rgb(235, 44, 51)")
         {
                $(this).addClass('jcbg');

             }

    });

});

Thanks @Guffa for your fiddle. It helped me.

A: The problem is that jquery returns rgb(...) even if you declare as HEX so i just added a function to translate hex to rgb:
function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

and than just adapted your code:
$(document).ready(function (e) {

    // Color to change
    var targetHex = hex2rgb('#eb2c33');

    $('body *').each(function(index) {
        var rgbg = $(this).css('background-color');

        if(rgbg == 'rgb('+targetHex[0]+', '+targetHex[1]+', '+targetHex[2]+')'){
            $(this).addClass('jcbg');
        }

    });
});

Here is the Fiddle


text:
Q: Install XPDF in Mac/OS How we can install XPDF via Mac Ports? Or if another methods for the installation of XPDF in the Mac/OS platform exists?

A: You can install it using homebrew too.
First you need to tap homebrew/x11:
$ brew tap homebrew/x11

Then you can easily install it with:
$ brew install xpdf

A: That might look too easy an answer :):
/usr/bin/sudo port install xpdf

A: xpdf is available through the Homebrew project. Once brew is installed, you can install xpdf using the command:
brew install homebrew/x11/xpdf


text:
Q: How to run tslint using Angular Cli? I am facing issue when I am trying to run tslint from Angular Cli.
> ng lint
Error

Failed to load E:\Projects\lsp-ui\node_modules\ng2-slimscroll\tslint.json: Could not find custom rule directory: E:\Projects\lsp-ui\node_modules\ng2-slimscroll\node_modules\codelyzer

[Error while running]

A: Run npm install or npm install codelyzer first.
Also check the file path of tsconfig.json in the Angular Cli configuration lint section, the configuration of rules directory in tslint.json, such as:
"rulesDirectory": [
        "../node_modules/codelyzer"
    ]

A: Here is official guide for you.

Codelyzer should work out of the box with Atom but for VSCode you will
  have to open Code > Preferences > User Settings, and enter the
  following config:
{   "tslint.rulesDirectory": "./node_modules/codelyzer",
  "typescript.tsdk": "node_modules/typescript/lib" }

https://github.com/mgechev/codelyzer#editor-configuration


text:
Q: How to set custom build cause on invoke() in Python JenkinsAPI I am trying to set custom causes for Jenkins builds using the jenkins api.
The jenkins api has an invoke() method for invoking new builds that receives the cause parameter.
# this is a jenkinsapi.Job method
invoke(self, securitytoken=None, block=False,
           build_params=None, cause=None, files=None, delay=5):

The cause param is dealt with like this:
if cause:
        build_params['cause'] = cause

I am trying to find out what format to use when defining a custom cause. In order to do this I first extracted the cause of a build to see what it looks like using jenkinsapi.Build method get_causes().
This yields a list of dictionaries as expected (only 1 cause), example:
[{'shortDescription': 'description of cause',
  'userId': 'userid',
  'userName': 'username'}]

With this knowledge, I tried invoking builds while specifying cause as a list of dictionaries in the same format, but this didn't work, upon collecting the causes from this new build, only the normal default cause was there.
So, my question is what do I need to do to create a custom cause?

A: I've found two ways to add in the custom cause but only one way which works with the Jenkin's API. I'm still hoping there's an alternative solution.
To get the custom cause setting to work I had to enable this setting in each Jenkin's job:

After enabling that setting, I was able to trigger the Job with a custom cause which would show up in the console.
job.invoke(securitytoken="asecuretoken", cause="A custom cause.")

The main trouble I have with this route is that it doesn't fill out the amount of information I see from custom plugins. That's the alternative I've found to using the cause in this manner but it requires more work to implement.
I've found a good example which customizes the build messages based on a REST request is the GitLab Jenkin's Plugin.


text:
Q: How to save data in temp table from my query I have the following query. I want to save result in my Temp Table and  isWithInCircle value in variable also, how do this?
declare @source geography = geography::Point(30.221101852485987, 71.575927734375, 4326), @target geography = geography::Point(29.9358952133724, 71.817626953125, 4326);

declare @radius_in_miles int = 100;

declare @radius_in_meters float = @radius_in_miles * 1081.7316;

select @target.STBuffer(@radius_in_meters).STContains(@source) AS [isWithinCircle],
 @target.STDistance(@source) AS [distance_in_meters],
 @target.STBuffer(@radius_in_meters).STDisjoint(@source) AS [isPastCircle];

A: Based on my limited understanding of what you are trying to do, but this should work...
IF OBJECT_ID('tempdb..#MyTempTable', 'U') IS NOT NULL DROP TABLE #MyTempTable;

declare @source geography = geography::Point(30.221101852485987, 71.575927734375, 4326), @target geography = geography::Point(29.9358952133724, 71.817626953125, 4326);

declare @radius_in_miles int = 100;

declare @radius_in_meters float = @radius_in_miles * 1081.7316;

declare @isWithinCircle int;

select @target.STBuffer(@radius_in_meters).STContains(@source) AS [isWithinCircle],
 @target.STDistance(@source) AS [distance_in_meters],
 @target.STBuffer(@radius_in_meters).STDisjoint(@source) AS [isPastCircle]
 into #MyTempTable;

 select @isWithinCircle = isWithinCircle from #MyTempTable

 select @isWithinCircle


text:
Q: Second bit of javascript that changes a setting in a previous block of javascript I'm trying to modify some javascript on a Squarespace site but I don't have access to it – I can only add additional code after the original block of script. The original code is as follows:
<script>
    Static.SQUARESPACE_CONTEXT = {
        "appDomain": "squarespace.com",

...

        "tweakJSON": {
            "gallery-auto-play": "false",
            "gallery-style": "Center",
            "gallery-transition": "Slide",
            "galleryPlaySpeed": "3.0",
            "index-aspect-ratio": "Auto",
            "navigation-position": "Bottom",
            "product-gallery-auto-crop": "true",
            "product-image-auto-crop": "true"
        },

...

        }
    };
    SquarespaceFonts.loadViaContext();
    Squarespace.load();
</script>

I've removed a bunch of additional code to shorten things up but if you need the full code I can post it. I'm trying to change the "gallery-style": "Center" to "gallery-style": "Full Bleed"
If you need further info just let me know. Any help would be much appreciate. Also, I'm not a programmer so if you could keep it dumbed down for me that would be great.
-- Additional info:
Thought this might help. Here's the site I'm referring to: architechstairs.squarespace.com What I'm looking to do is have the home page "Full Bleed" while all other gallery pages on the site will be "Center". Unfortunately Squarespace only allows me to set one overall gallery style.

A: Static.SQUARESPACE_CONTEXT.tweakJSON["gallery-style"] = 'Full Bleed';


text:
Q: How can I make a full-screen table in android I am working on a program for Android, and I want to make a 3x7 (3 columns, 7 rows) table, where each cell holds a button.
I have tried using tableLayout, but every time the width of the tables are always too short or too long, meaning that there is either blank space or the buttons go off of the page.  I am not having a problem with the height, just the width.
This problem could also be solved easily with a layout like GridLayout from java.  Is there an equivalent to that in Android?
any ideas are greatly appreciated.

A: You have to use linear layouts with weights.
Try this out, I think that does it, though it might take a little work, but it should get you pointed in the right direction.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width:"fill_parent" android:layout_height:"fill_parent" android:orientation="vertical">
    <LinearLayout android:layout_width:"fill_parent" android:layout_height:"fill_parent" android:orientation="vertical">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1">
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
            <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
                    android:text="ButtonText"/>
        </LinearLayout>
    </LinearLayout>
</LinearLayout>
</LinearLayout>

A: maybe set android:layout_width on you button in fix size  "185dp"


text:
Q: How can i open and write in cron file task using symfony2 I'm creating an application in Symfony2.4. I also have the command, I want to add the command  in cron a task using symfony2, not manually namely, the via symfony2, open and write. Any suggestions to get this done.

A: *

*Create a console command (doc)

*Add to cron execution of your command. For example, run a command at 2 a. m. every day:
$ crontab -e
0 2 * * * php /var/www/example.com/app/console mybundle:mycommand

A: faost thanks. but I know how to add in cron manually via the console, I was interested how it do  through the controller. In short, I found the solution :)

$output = shell_exec('crontab -l');
file_put_contents('/crontab.txt', $output.'* * * * * command'.PHP_EOL, FILE_APPEND | LOCK_EX);
echo exec('crontab /crontab.txt');


text:
Q: JavaScript - Clicking on an image I am programming a browser game in JavaScript and need to create a Card Class.
This class has (with other variables) an image, which should be displayed when I create an object. How do I display the object's image and call a function when the image is clicked?
With this code I can display the image wherever I want, but the OnClick function is called instantly when I open the .htm file instead of when I click in the image.
<html>
<head> </head>
<body>
<script type="text/javascript">
  function Card(photo){ // this is my object
      this.randomVariable=42;
      this.pic = new Image(); // creating an Image object inside my Card class.
        this.pic.src=photo;
        this.pic.height = 300;
        this.pic.width = 200;
        this.pic.style.position="absolute";  // this 3 lines should set the image's position, and it does.
        this.pic.style.top = 50 + "px";
        this.pic.style.left = 50 + "px";
        this.OnClick = document.write("lala");
  }

  var myObject = new Card("cardback.jpg");
  myObject = document.body.appendChild(coso1.pic); // is this how I should create the image? It appears where I want, but it doesn't seem a "clean" programming.
  myObject.OnClick = document.write("lala" + coso1.pic.offsetLeft + coso1.pic.offsetTop); // this is casted when I open the file, and not when I click on the image. *sadface*

</script>
</body>
</html>

Please, some help with detecting when I click on the image and displaying the image in a less dirty way (if it's possible)?
Thanks in advance!

A: http://jsfiddle.net/CTWWk/1/
var image = new Image();
image.src = 'https://www.google.co.il/images/srpr/logo4w.png';

image.onclick = function(){
      alert('I Clicked an image now !');
};

var divy = document.getElementById('divy');
divy.appendChild(image);

A: Made some changes to your code. Hope it helps!
<html>
<head> </head>
<body>
<script type="text/javascript">
  function Card(photo){
     var cardInstance = new Image();
     cardInstance.src = photo;
     cardInstance.addEventListener('click', function (e) {
          alert(1);
      });
     return cardInstance;
  }

  var myObject = new Card("cardback.jpg");
  document.body.appendChild(myObject);

</script>
</body>
</html>


text:
Q: How to get multidimensional array grouped by multiple columns in PHP from single MySQL table? I have table called "guids" that looks like this:
id |survey_type |guid |guid_type |table_id |created_at |
2 |TYPE 1 |6C7251E3-2151-4754-A413-51899FAAF6C2 |question |2 |2022-03-20 16:14:09 |
3 |TYPE 1 |EF5AFA93-C74D-4920-A13A-17A9B43239CD |question |3 |2022-03-20 16:14:09 |
4 |TYPE 1 |5C059148-94BE-4225-B5C2-551A81B65F16 |question |4 |2022-03-20 16:14:09 |
5 |TYPE 1 |356B8A5C-1072-47A5-A508-D9BDCBA92CCC |answer |5 |2022-03-20 16:14:09 |
6 |TYPE 1 |E0CE4C26-7ABD-4162-9C8C-B4DD540AE268 |answer |6 |2022-03-20 16:14:09 |
7 |TYPE 1 |BFBC50FC-892D-43E9-A235-D76E0D0BEF29 |answer |7 |2022-03-20 16:14:09 |
8 |TYPE 2 |B9DCC5C1-CBFB-4589-98EF-4524F3958968 |survey |8 |2022-03-20 16:14:09 |
9 |TYPE 2 |C98FBFF9-6FE3-414E-BB14-08EDC8281E66 |survey |9 |2022-03-20 16:14:09 |
10 |TYPE 2 |8A780B6E-EAE0-47D6-9D05-F52B795AE617 |question |10 |2022-03-20 16:14:09 |
11 |TYPE 2 |E3818D30-BB69-4F03-B56D-B31691F8007E |question |11 |2022-03-20 16:14:09 |
12 |TYPE 2 |24C81BEF-BFCE-4964-AB01-F3579251313D |answer |12 |2022-03-20 16:14:09 |
13 |TYPE 3 |59381701-AFBC-48F8-AECE-DB3702EE2B15 |answer |13 |2022-03-20 16:14:09 |
14 |TYPE 3 |7F4AC694-74DC-4BEA-ACFB-D8F070769FEE |answer |14 |2022-03-20 16:14:09 |
15 |TYPE 3 |B5C405B9-BA7E-471A-87DD-B69D9757276F |survey |15 |2022-03-20 16:14:09 |

From that I would like to get data in this format:
Array
(
    [survey_type] => Array
        (
            [guid_type] => Array
                (
                    [table_id] => guid
                    ...
                )
            ... // all guid types
        )
    ... // all survey types
)

Basically, I need to use multiple columns to build a nested array with grouped data.
I know that I can achive that structure using foreach loop like this:
// select existing guids
$this->db->select('*')
      ->from('guids');
$query = $this->db->get();
$existing_guids = $query->result_array();
$formated_guids = [];

foreach($existing_guids as $key => $guid_data) {
    $formated_guids[$guid_data['survey_type']][$guid_data['guid_type']][$guid_data['table_id']] = $guid_data['guid'];
}

But if possible I would like a more optimized solution on the database layer as this table is expected to have millions of rows and looping through the entire table doesn't seem to be the most optimized way to do it.
I have played around with GROUP_CONCAT mysql command for a bit but failed to produce the desired structure
SELECT `survey_type`, GROUP_CONCAT(`guid_type`) AS `guid_types` FROM guids GROUP BY `survey_type`

Desired result with mock data:
Array
(
    [TYPE 1] => Array // survey type column
        (
            [question] => Array // guid_type column
                (
                    // table_id => guid
                    [1] => C8D21BD8-DA62-43C6-8E0D-0524D4F093B6
                    [2] => 6C7251E3-2151-4754-A413-51899FAAF6C2
                    ...
                )

            [survey] => Array
                (
                    [14] => B8B1F361-34A2-430E-9C0E-EB0C515B4E79
                    ...
                )

            [answer] => Array
                (
                    [2906] => 1A2F133E-0491-4117-AE2E-E3A823B66FBD...
                )

        ),
    [TYPE 2] => Array
        (
        ... // same structure as above
)

A: First, I would recommend you stick with your code solution. Run a simple SQL query, and process the results, collating them into the nested array structure you want. You already have that coded, it's easier to debug and easier to change in the future if you need to change it.
I've implemented something like you describe, to create a nested structure in an SQL query. It was pretty hard, and the SQL query was complex enough that it will be a maintenance problem in the future if we ever need to modify the contents of the nested structure.
The solution I used in the SQL query was to use multiple levels of derived table subqueries, and generate aggregate JSON results at each level using JSON functions. This requires using MySQL 5.7 or later, because these JSON functions are not implemented in earlier versions of MySQL.
Demo test data:
create table if not exists mytable ( id int primary key, survey_type varchar(20), guid char(36), guid_type varchar(20), table_id  int, created_at datetime );
insert into mytable values
(2 ,'TYPE 1','6C7251E3-2151-4754-A413-51899FAAF6C2','question','2','2022-03-20 16:14:09'),
(3 ,'TYPE 1','EF5AFA93-C74D-4920-A13A-17A9B43239CD','question','3','2022-03-20 16:14:09'),
(4 ,'TYPE 1','5C059148-94BE-4225-B5C2-551A81B65F16','question','4','2022-03-20 16:14:09'),
(5 ,'TYPE 1','356B8A5C-1072-47A5-A508-D9BDCBA92CCC','answer','5','2022-03-20 16:14:09'),
(6 ,'TYPE 1','E0CE4C26-7ABD-4162-9C8C-B4DD540AE268','answer','6','2022-03-20 16:14:09'),
(7 ,'TYPE 1','BFBC50FC-892D-43E9-A235-D76E0D0BEF29','answer','7','2022-03-20 16:14:09'),
(8 ,'TYPE 2','B9DCC5C1-CBFB-4589-98EF-4524F3958968','survey','8','2022-03-20 16:14:09'),
(9 ,'TYPE 2','C98FBFF9-6FE3-414E-BB14-08EDC8281E66','survey','9','2022-03-20 16:14:09'),
(10 ,'TYPE 2','8A780B6E-EAE0-47D6-9D05-F52B795AE617','question','10','2022-03-20 16:14:09'),
(11 ,'TYPE 2','E3818D30-BB69-4F03-B56D-B31691F8007E','question','11','2022-03-20 16:14:09'),
(12 ,'TYPE 2','24C81BEF-BFCE-4964-AB01-F3579251313D','answer','12','2022-03-20 16:14:09'),
(13 ,'TYPE 3','59381701-AFBC-48F8-AECE-DB3702EE2B15','answer','13','2022-03-20 16:14:09'),
(14 ,'TYPE 3','7F4AC694-74DC-4BEA-ACFB-D8F070769FEE','answer','14','2022-03-20 16:14:09'),
(15 ,'TYPE 3','B5C405B9-BA7E-471A-87DD-B69D9757276F','survey','15','2022-03-20 16:14:09');

Example query:
select json_pretty(json_objectagg(survey_type, g)) as j
from (
  select survey_type, json_objectagg(guid_type, t) as g
  from (
    select survey_type, guid_type, json_objectagg(table_id, guid) as t
    from mytable
    group by survey_type, guid_type
  ) as t
  group by survey_type
) as g;

Output:
{
  "TYPE 1": {
    "answer": {
      "5": "356B8A5C-1072-47A5-A508-D9BDCBA92CCC",
      "6": "E0CE4C26-7ABD-4162-9C8C-B4DD540AE268",
      "7": "BFBC50FC-892D-43E9-A235-D76E0D0BEF29"
    },
    "question": {
      "2": "6C7251E3-2151-4754-A413-51899FAAF6C2",
      "3": "EF5AFA93-C74D-4920-A13A-17A9B43239CD",
      "4": "5C059148-94BE-4225-B5C2-551A81B65F16"
    }
  },
  "TYPE 2": {
    "answer": {
      "12": "24C81BEF-BFCE-4964-AB01-F3579251313D"
    },
    "survey": {
      "8": "B9DCC5C1-CBFB-4589-98EF-4524F3958968",
      "9": "C98FBFF9-6FE3-414E-BB14-08EDC8281E66"
    },
    "question": {
      "10": "8A780B6E-EAE0-47D6-9D05-F52B795AE617",
      "11": "E3818D30-BB69-4F03-B56D-B31691F8007E"
    }
  },
  "TYPE 3": {
    "answer": {
      "13": "59381701-AFBC-48F8-AECE-DB3702EE2B15",
      "14": "7F4AC694-74DC-4BEA-ACFB-D8F070769FEE"
    },
    "survey": {
      "15": "B5C405B9-BA7E-471A-87DD-B69D9757276F"
    }
  }
}

Fetch that result into your client app. It's a single long string, so I hope your data is not longer than MySQL's max_allowed_packet length.
Convert the string into your desired nested array with json_decode().


text:
Q: How to figure out the exact package name of a `.so` file, so that it can be installed through `zypper`? anisha@linux-dopx:~/tarBalls/qtFlash/bin> ./flashscript
./flashscript: error while loading shared libraries: libqtnmedia.so.2: cannot open shared object file: No such file or directory

anisha@linux-dopx:~/tarBalls/qtFlash/bin> cnf libqtnmedia.so.2
libqtnmedia.so.2: command not found

Is there a pattern somewhere?
How do YOU install a .so file through the package manager?

A: Maybe with :
zypper what-provides libqtnmedia.so.2

A: I think zypper wp libqtnmedia.so.2  will do the trick.
zypper wp searches in packages by filename and displays where it is contained.


text:
Q: Calculate FPS in opengl game for iphone ( EAGLView ) I used the apple's crash landing example as base to program some small games for iphone. Now i would like to meassure the frames per second in my games.
I'm curious about how can I calculate the FPS per second, can anyone help me to understand or point me to any way to do It ?.
Thanks.

A: You need the time the last frame took to draw in milliseconds, the rest is easy: 1.0f/deltaTime


text:
Q: Conditional probability for Poisson process Give this question:

For a Poisson process with rate λ, find P(N(s) = k|N(t) = n) when s > t.

What is the difference if it was given that s < t?
If s > t, do the two events become independent? Why?


text:
Q: list directory recursively, with subpath, and leaf nodes (files) first (for batch renaming part of filenames)? Before declaring this a duplicate, consider that I'd need this for a specific reason: batch renaming (or copying to a new name) of a tree structure that contains a common string in file and directory names. Here's an example (tried on Ubuntu 14.04, so GNU tools):
cd /tmp
mkdir myproj
mkdir -p myproj/myproj_AA/myproj_BB
touch myproj/myproj_AA/myproj_BB/myproj_CC.dat
mkdir myproj/myproj_AA/myproj_DD
touch myproj/myproj_AA/myproj_DD/myproj_EE.dat
mkdir -p myproj/myproj_XX/myproj_YY
touch myproj/myproj_XX/myproj_YY/myproj_ZZ.dat
mkdir -p myproj/myproj_XX/myproj_WW
touch myproj/myproj_XX/myproj_WW/myproj_QQ.dat
tree myproj # to visualise

This directory structure's tree looks like this:
myproj
├── myproj_AA
│   ├── myproj_BB
│   │   └── myproj_CC.dat
│   └── myproj_DD
│       └── myproj_EE.dat
└── myproj_XX
    ├── myproj_WW
    │   └── myproj_QQ.dat
    └── myproj_YY
        └── myproj_ZZ.dat

6 directories, 4 files

So, I'd want all the entries in myproj/, including myproj itself, renamed to myTESTproj instead of myproj (wherever it may occur as a name). So, first I need to obtain a listing with relative paths in respect to the current directory - and then I need to have it sorted such that the outermost children (I think this is equivalent to files with the longest relative pathnames, but not sure) are first (because if I rename/mv the directory first, and then try to rename a file in it, it will likely use the old dir name as first argument, and fail since the name is now changed).
I'm aware there is ls -R --group-directories-first myproj/ to use ls recursively and group directories first, but its output is like this:
$ ls -R --group-directories-first myproj/
myproj/:
myproj_AA  myproj_XX

myproj/myproj_AA:
myproj_BB  myproj_DD

myproj/myproj_AA/myproj_BB:
myproj_CC.dat

myproj/myproj_AA/myproj_DD:
myproj_EE.dat

myproj/myproj_XX:
myproj_WW  myproj_YY

myproj/myproj_XX/myproj_WW:
myproj_QQ.dat

myproj/myproj_XX/myproj_YY:
myproj_ZZ.dat

... that is, it is not a plain list with subpaths, that I could easily feed to while read f; do ...
Closest I came to is to use find instead:
$ find myproj/
myproj/
myproj/myproj_AA
myproj/myproj_AA/myproj_DD
myproj/myproj_AA/myproj_DD/myproj_EE.dat
myproj/myproj_AA/myproj_BB
myproj/myproj_AA/myproj_BB/myproj_CC.dat
myproj/myproj_XX
myproj/myproj_XX/myproj_YY
myproj/myproj_XX/myproj_YY/myproj_ZZ.dat
myproj/myproj_XX/myproj_WW
myproj/myproj_XX/myproj_WW/myproj_QQ.dat

So, here I do have a plain list of subpaths, however it is sorted root node first towards leaf nodes - and I need leaf nodes first. And I'm trying stuff like find myproj/ | sort -n, but it seems to make no difference. So if I do something like:
$ find myproj/ | sort -n | while read f; do mv -v $f $(echo $f | sed 's/myproj/myTESTproj/g'); done
'myproj/' -> 'myTESTproj/'
mv: cannot stat 'myproj/myproj_AA': No such file or directory
mv: cannot stat 'myproj/myproj_AA/myproj_BB': No such file or directory
mv: cannot stat 'myproj/myproj_AA/myproj_BB/myproj_CC.dat': No such file or directory
...

... then the intended recursive rename fails immediately, as the root node (directory) is renamed first, and thus all further references to it are invalid.
So, how can I obtain a proper recursive listing of a subdirectory with leaf nodes first, to use it in a batch rename like this?

A: If you're aiming on just renaming, isn't it enough that the contents of each directory are processed before the directory itself, that is, you don't need all leaves (from all directories) first? find -depth does exactly that.
$ mkdir -p a/b c/d
$ find -depth
./a/b
./a
./c/d
./c
.

Then you could use find -exec and Bash to rename the files:
$ find -depth ! -name . -name "*myproj*" -execdir bash -c '
    for f; do mv "$f" "${f/myproj/myTESTproj}" ; done' bash {} +

A: If you have the Perl version of the rename command installed (sometimes known as prename) this will work for you
find myproj -depth -name '*myproj*' -exec rename -n 's!(.*)myproj!$1myTESTproj!' {} +

The -depth option to find ensures that children in any directory are listed before the directory itself. The + suffix to the -exec action allows multiple {} insertions for a single invocation of the specified command. At the cost of reduced efficiency you can replace it with \;.
When you are sure it will do what you want, remove the -n or replace it with -v.

A: I remembered what to look for once I posted the question - if the leaf nodes are those with the longest relative pathnames (which I'm not sure if it's true always, but seems to be in the OP example at least), then one simply needs a way to sort a list of strings by string length; unfortunately sort does not seem to have such an option.
But, I found https://stackoverflow.com/questions/5917576/sort-a-text-file-by-line-length-including-spaces - and from there, chose the perl solution:
$ find myproj/ | perl -e 'print sort { length($b) <=> length($a) } <>'
myproj/myproj_AA/myproj_DD/myproj_EE.dat
myproj/myproj_AA/myproj_BB/myproj_CC.dat
myproj/myproj_XX/myproj_YY/myproj_ZZ.dat
myproj/myproj_XX/myproj_WW/myproj_QQ.dat
myproj/myproj_AA/myproj_DD
myproj/myproj_AA/myproj_BB
myproj/myproj_XX/myproj_YY
myproj/myproj_XX/myproj_WW
myproj/myproj_AA
myproj/myproj_XX
myproj/

However, the trivial sed 's/myproj/myTESTproj/g' replacement does not work here either:
$ find myproj/ | perl -e 'print sort { length($b) <=> length($a) } <>' \
> | while read f; do mv -v $f $(echo $f | sed 's/myproj/myTESTproj/g'); done
'myproj/myproj_AA/myproj_DD/myproj_EE.dat' -> 'myTESTproj/myTESTproj_AA/myTESTproj_DD/myTESTproj_EE.dat'
mv: cannot move 'myproj/myproj_AA/myproj_DD/myproj_EE.dat' to 'myTESTproj/myTESTproj_AA/myTESTproj_DD/myTESTproj_EE.dat': No such file or directory
...

... so we need a sed to replace only last match in a line, which is sed -E 's/(.*)myproj/\1myTESTproj/g':
$ find myproj/ | perl -e 'print sort { length($b) <=> length($a) } <>' \
| while read f; do mv -v $f $(echo $f | sed -E 's/(.*)myproj/\1myTESTproj/g'); done
'myproj/myproj_AA/myproj_DD/myproj_EE.dat' -> 'myproj/myproj_AA/myproj_DD/myTESTproj_EE.dat'
'myproj/myproj_AA/myproj_BB/myproj_CC.dat' -> 'myproj/myproj_AA/myproj_BB/myTESTproj_CC.dat'
'myproj/myproj_XX/myproj_YY/myproj_ZZ.dat' -> 'myproj/myproj_XX/myproj_YY/myTESTproj_ZZ.dat'
'myproj/myproj_XX/myproj_WW/myproj_QQ.dat' -> 'myproj/myproj_XX/myproj_WW/myTESTproj_QQ.dat'
'myproj/myproj_AA/myproj_DD' -> 'myproj/myproj_AA/myTESTproj_DD'
'myproj/myproj_AA/myproj_BB' -> 'myproj/myproj_AA/myTESTproj_BB'
'myproj/myproj_XX/myproj_YY' -> 'myproj/myproj_XX/myTESTproj_YY'
'myproj/myproj_XX/myproj_WW' -> 'myproj/myproj_XX/myTESTproj_WW'
'myproj/myproj_AA' -> 'myproj/myTESTproj_AA'
'myproj/myproj_XX' -> 'myproj/myTESTproj_XX'
'myproj/' -> 'myTESTproj/'
$ tree myTESTproj/
myTESTproj/
├── myTESTproj_AA
│   ├── myTESTproj_BB
│   │   └── myTESTproj_CC.dat
│   └── myTESTproj_DD
│       └── myTESTproj_EE.dat
└── myTESTproj_XX
    ├── myTESTproj_WW
    │   └── myTESTproj_QQ.dat
    └── myTESTproj_YY
        └── myTESTproj_ZZ.dat

6 directories, 4 files

I guess this does what I want it to - but, I'm not sure if the assumption of longest pathname == leaf file node is always correct; and even if it is - is there an easier way of doing this?

EDIT: this definitely fails in a case of structure like this:
myproj/somespecdir/someotherdir/myproj_CC.dat
myproj/myproj_AA/myproj_DD/myproj_EE.dat
myproj/somespecdir/someotherdir
myproj/myproj_AA/myproj_DD
myproj/somespecdir
myproj/myproj_AA
myproj/

... that is, if the first occurrence of the substring to search for and replace in the renamed path is also the last (the only one); and it occurs in the list before a path that has multiple occurrences of the substring.


text:
Q: Ruby on Rails Routing with Comments I am trying to create a comment model for my posts and the question is how am I able to create comments but not have the routes nested inside of the posts...
That is, there is no route to posts/comment/:comment_id and instead just have the user enter a comment and let the user stay on the page without having to transfer the user. I want the user to have no interaction with a different route and just have them say where they are.

A: Not sure I understand correctly, but if you don't want the user to be taken to a new page after creating a comment just remove the "render" method in the action for the comment controller.


text:
Q: Why do I need a 00 time zone offset to display values correctly in d3v4? I'm trying to parse the following dates with d3:
20-06-18 01-02-35
20-06-18 09-13-01

using:
var parseTime = d3.timeParse("%d-%m-%y %H-%M-%S");

However, the console.log shows me these parsed values:
Date 2018-06-19T23:02:35.000Z
Date 2018-06-20T07:13:01.000Z

which are off by two hours.

Okay, I thought, after all, I'm sitting in the CEDT, I should probably add an offset. So I added -02 to the dates to parse and %Z to the timeParse argument, but it's still not what I want:
var parseTime = d3.timeParse("%d-%m-%y %H-%M-%S %Z");
parseTime("20-06-18 01-02-35 -02") // Date 2018-06-20T03:02:35.000Z
parseTime("20-06-18 09-13-01 -02") // Date 2018-06-20T11:13:01.000Z

Long story short, asking for a -00 offset gives me the correct values. But it seems a bit redundant to me. Why does this happen?
EDIT: Only happens in Firefox, Chrome gives me
Wed Jun 20 2018 09:13:01 GMT+0200

Still no idea why, tho.

A: You're probably looking for d3.utcParse instead of d3.parseTime in order to avoid using the local time zone:

var parser = d3.utcParse("%d-%m-%y %H-%M-%S");
console.log(parser("20-06-18 01-02-35"));
<script src="https://d3js.org/d3.v5.min.js"></script>

And to go back to string, you can use d3.utcFormat instead of d3.timeFormat.


text:
Q: Windows Azure Parameters Folks, Good Night! Can you halp me in this situation ?
I search for two days, but I cant't find a way to do this ...
How can I pass parameters to read function in Windows Azure mobile service ?
In code bellow I call the read function , but I want pass Parm1 to manipulate in Windos Azure.
[itemTable readWhere:predicate completion:^(NSArray *items, NSInteger totalCount, NSError *error) {

I want in Windows Azure make something like this...
function read(query, user, request) {
var parm1 = query.parameters.Parm1;

request.execute();
}

Tks for help me.
Paulo

A: If you're doing a read, this can be accomplished by calling MSTable's readWithQueryString method.  For example:
NSString *queryString = [NSString stringWithFormat:@"param1=%@", @"myparam"];

[self.myTable readWithQueryString:queryString completion:^...

and then in your server side scripts you would acces sit using request.parameters.param1.
Chris


text:
Q: Docker service exposed publicly though made to expose ports to localhost only I have created one service and exposed it to run only on localhost in one of my docker swarm node but I can access the service publicly too easily.
I have deleted and redeployed the docker stack but still same issue.
Here is my docker-compose.yml I have used to deploy the service in stack
version: "3"
networks:
    api-net:
        ipam:
            config:
                - subnet: 10.0.10.0/24

services:
    health-api:
        image: myprivateregistry:5000/healthapi:qa
        ports:
            - "127.0.0.1:9010:9010"
        networks:
            - api-net
        depends_on:
            - config-server
        deploy:
            mode: replicated
            replicas: 1
            placement:
                constraints:
                    - node.role == manager

I haven't added the service on which it depends as I don't think that is the problem.

Few says its not supported in docker swarm mode. Than what is solution in that case.

A: Quoting https://github.com/moby/moby/issues/32299#issuecomment-290978794:

On swarm mode, if you publish something (ports for stack deploy), it is published on the ingress network, and thus it is public. There is a few ways to get around, but putting kind/bug on that because we should at least warn people about that when doing a stack deploy with ports that have this notation (i.e. host:port:port).
To work around this, there is a few ways:

*

*first, you should publish mongo ports only if you want it to be public, otherwise, it is available through the name discovery bundle in docker (another container/service on the same network will be able to reach it through mongo dns name).

*If you want to publish it in the host and not in ingress (so not swarm public, just on the host it is running, same way as without swarm mode), you need to use ports expanded syntax.

ports:
  - mode: host
    target: 80
    published: 9005

So, the reason is Swarm's ingress network, which makes every port publicly available. The workaround using the extended syntax doesn't bind to the loopback interface, but to the host's 0.0.0.0 interface, which is still an improvement compared to an externally exposed port via the ingress network.


text:
Q: How to use the output of ls to open the last modified file? Would there be a way to use the output of ls -ltr with xargs?
Assume that the result of ls is one file as below.
ls -ltr | tail -1 | xargs -I{} open {}

For comparison, I use the following command to use find to move files:
find ~/Downloads/ -iname '*hello*' -print0 | xargs -0 -I{} mv {} ./

Can we somehow use NUL character?

[Solved]
As mentioned in the @illkachu's comments, the following works but is not suggested.
somecmd "$(ls -tr | tail -1)"
What Stéphane suggests seem be alternatives.

A: Generally, you wouldn't as the output of ls is not post-processable reliably.
For instance:
open -- "$(ls -t | head -n 1)"

doesn't work if the name of newest file contains newline characters.
Ideally, you'd want:
ls -zt | head -zn1 | xargs -r0 open --

But unfortunately, I don't know of any ls implementation that supports a -z/-0 option, and the maintainers of GNU ls at least declined several times to add it.
Now, there are other ways with some implementations.
With the GNU and ast-open implementations of ls, in the C locale, the output with the --quoting-style=shell-always option is post-processable by zsh, ksh93 or bash:
export LC_ALL=C
eval "files=($(ls --quoting-style=shell-always -t))"

open -- "${files[0]}" # $files[1] with zsh

Though in zsh, you'd just do
open ./*(om[1])

or:

open ./Ctrl+Xm

as zsh has built-in support to sort files by modification time (and many other criteria that go far beyond ls capabilities).
FreeBSD ls has a --libxo option to generate json or xml output, so you could do:
ls --libxo=json -t | perl -MJSON::PP -0777 -l0 -ne '
  print decode_json($_)
    ->{"file-information"}
    ->{directory}->[0]
    ->{entry}->[0]
    ->{name}' | xargs -r0 open --

But then it would be simpler to do the whole thing in perl.

A: As you already have been told: In general this is not the approach you want to chose. However, as a start:
ls -ltr | awk '/^-/ { print $9; }' | xargs


text:
Q: Ensure that a popup has been closed with Capybara/Selenium I am attempting to write a capybara spec which opens a popup, and then asserts that the popup has closed itself.
visit "/my_page"

click_button "Open My Popup"

within_window("MyPopup") do
  # test things on MyPopup
end

sleep 1 # long enough that window.close() has been called in the popup

# ensure that MyPopup is closed

Things I've tried so far...
Counting the window handles:
page.driver.browser.window_handles.length
This remains at 2 even after the popup is closed
As this post suggests, check for the visibility of an element on the popup.  This doesn't seem to work.  Even though the popup has been closed, I can run assertions against the window as if it's still there, just as before:
within_window("MyPopup") do
  # test things on MyPopup
end

I'm ensured that window.close is firing from the popup (by adding some JS that modifies the popup's DOM after the window.close() and asserting on those changes).
I'm fairly stumped here; anyone out there know the secret sauce for asserting that the window actually closed?

A: Maybe you should wait for your page has no some specific css?
It may look like this:
def wait_for(timeout = 10)
  Timeout.timeout(timeout) do
    loop do
      break if yield
    end
  end
end

wait_for { page.first(:css, 'your.specific.css').nil? }


text:
Q: PHP Screen Scraping and Sessions Ok still new to the screen scraping thing.
I've managed to log into the site I need but now how do I redirect to another page?
After I login I'm trying to do another GET request on the page that I need but it has a redirect on it that takes me back to the login page.
So I'm thinking the SESSION variables are not being passed, how can I over come this?
Problem:
Even if I post the 2nd page URL it still redirects me back to the login page, unless I'm logged in already, but the screen scrape code is not allowing the SESSION data to be passed?
I found this code from another screen scraper question here @stack
class Curl {

    public $cookieJar = "";

    public function __construct($cookieJarFile = 'cookies.txt') {
        $this->cookieJar = $cookieJarFile;
    }

    function setup() {
        $header = array();
        $header[0]  = "Accept: text/xml,application/xml,application/xhtml+xml,";
        $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        $header[]   = "Cache-Control: max-age=0";
        $header[]   = "Connection: keep-alive";
        $header[]   = "Keep-Alive: 300";
        $header[]   = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
        $header[]   = "Accept-Language: en-us,en;q=0.5";
        $header[]   = "Pragma: "; // browsers keep this blank.

        curl_setopt($this->curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7');
        curl_setopt($this->curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($this->curl, CURLOPT_COOKIEJAR, $cookieJar);
        curl_setopt($this->curl, CURLOPT_COOKIEFILE, $cookieJar);
        curl_setopt($this->curl, CURLOPT_AUTOREFERER, true);
        curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, true);
    }

    function get($url) {
        $this->curl = curl_init($url);
        $this->setup();

        return $this->request();
    }

    function getAll($reg, $str) {
        preg_match_all($reg, $str, $matches);
        return $matches[1];
    }

    function postForm($url, $fields, $referer = '') {
        $this->curl = curl_init($url);
        $this->setup();
        curl_setopt($this->curl, CURLOPT_URL, $url);
        curl_setopt($this->curl, CURLOPT_POST, 1);
        curl_setopt($this->curl, CURLOPT_REFERER, $referer);
        curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fields);
        return $this->request();
    }

    function getInfo($info) {
        $info = ($info == 'lasturl') ? curl_getinfo($this->curl, CURLINFO_EFFECTIVE_URL) : curl_getinfo($this->curl, $info);
        return $info;
    }

    function request() {
        return curl_exec($this->curl);
    }
}

Calling the class
include('/var/www/html/curl.php');
$curl = new Curl();

$url = "here.com";
$newURL = "here.com/newpage.php";

$fields = "usr=user1&pass=PassWord";

// Calling URL
$referer = "http://here.com/index.php";

$html = $curl->postForm($url, $fields, $referer);
$html = $curl->get($newURL);

echo $html; // takes me back to $url instead of $newURL

A: The following lines do not use "$this" and $cookieJar isn't in local scope:
curl_setopt($this->curl, CURLOPT_COOKIEJAR, $cookieJar);
curl_setopt($this->curl, CURLOPT_COOKIEFILE, $cookieJar);

So it should look like:
    curl_setopt($this->curl, CURLOPT_COOKIEJAR, $this->cookieJar);
    curl_setopt($this->curl, CURLOPT_COOKIEFILE, $this->cookieJar);

If that doesn't fix the issue try and only do the post:
$curl->postForm($url, $fields, $referer);
and not
$curl->get($newURL)
Then check if the cookie.txt file contains anything? Does it get created? Let us know the results as it's hard to quickly test your code without the actual URL being hit.
If it isn't creating a cookie.txt file than you can almost guarantee that the session isn't being kept between requests.

A: maybe the example isnt correct .. but from the looks of it the domain is changing .. so here.com session wont exist on there.com

A: The site is probably trying to store the session id in a cookie.  You have curl set up to use cookies via a "cookies.txt" file though.  So, my first thought would be - what's in the cookies.txt file?  Does the script have permissions to actually create that file?

A: This is working fine by using $curl->get($newURL) instead of $curl->postForm($url, $fields, $referer);


text:
Q: Is there any way to add a abstract method for JPA repository : findByEnumContaining(String enum) [enum is subString for possible ENUM values] This is my JPA @Repository, here we can get list<Person> with findByFullNameContaining(String query) - by providing just substring of fullName in query
@Repository
public interface PersonRepository extends CrudRepository<Person,String> {
    Optional<Person> findByFullName(String fullName);
    List<Person> findByDepartment(Department department);
    List<Person> findByFullNameContaining(String query);

}

Similarly, Can we perform something for ENUM values - by providing sub-string value of ENUM? How?
Eg.
public enum Department {
    NORTH,
    SOUTH,
    EAST,
    WEST
}

List<Person> findByDepartmentContaining(String query);
JPA @Entity Person:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "Person")
public class Person {

    @Id
    @NotNull(message = "Mobile number is required")
    @Size(min = 10, max = 10, message = "Mobile no. must be 10 digits")
    @Column(name = "person_id", unique = true, length = 10)
    private String mobileNum;

    @Transient
    @NotNull(message = "Password is required")
    @Size(min = 1, message = "Password cannot be empty")
    private String password="****";

    @NotNull(message = "Name cannot be empty")
    @Size(min = 1, max = 255, message = "fullName must be 1-255 characters long")
    @Column(name = "full_name")
    private String fullName;

    @Column(name = "department")
    @Enumerated(EnumType.STRING)
    @NotNull(message = "Department must be specified")
    private Department department = Department.UNKNOWN;

    public Person() {
    }

    public Person(String mobileNum, String fullName, String password, Department department) {
        this.mobileNum = mobileNum;
        this.password = password;
        this.fullName = fullName;
        this.department = department;
    }

    public String getMobileNum() {
        return mobileNum;
    }

    public void setMobileNum(String mobileNum) {
        this.mobileNum = mobileNum;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    @Override
    public String toString() {
        return "Person [fullName=" + fullName + ", mobileNum=" + mobileNum + ", password=" + password + ", department=" + department + "]";
    }

}

A: The question does not specify what exactly the issue is when declaring such a method.
But having tried with spring boot 2.7 with PostgreSql Database the application throws the following runtime error:
java.lang.IllegalArgumentException: Parameter value [%some value%] did not match expected type [com.Department (n/a)]
    at org.hibernate.query.spi.QueryParameterBindingValidator.validate(QueryParameterBindingValidator.java:54) ~[hibernate-core-5.6.5.Final.jar:5.6.5.Final]

The issue at least with hibernate is that it will expect a Department field in an entity to be always passed as parameter in it's own object type which is Department.
I don't think there is a way to avoid this, as this is an out of the box functionality for Hibernate.
I think however that the correct approach would not be to define this type of method but the following. Department already exists in application code so it is known at the time the query needs to be invoked. So I think that the following solution would be considered a better practice:
//Repository method to be used in PersonRepository
List<Person> findByDepartmentIn(List<Department> departments);

And then the repository could be invoked in the following way from the service layer.
//Service method to be used
public List<Person> findByDepartmentIn(String searchBy) {

    List<Department> departments = Arrays.stream(Department.values()).filter(dep -> dep.getName().contains(searchBy)).collect(Collectors.toList());

    return personRepository.findDepartmentIn(departments);
}


text:
Q: `grid-auto-rows: 1fr` doesn't have the expected effect My HTML and CSS code are in this jsfiddle page
According to this topic, as the element  has grid-auto-rows: 1fr;, the two  items should have equal heights.
On my browsers, it's not the case at all (and it's quite visible in Firefox).
Does anyone know why?


text:
Q: How to change favicon in coreui? I use vue.js version of coreui template, but I find difficulty in inserting a custom favicon for the present project.
file path: "coreui-free-vue-admin-template/public/index.html"

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,shrink-to-fit=no">
    <meta name="description" content="CoreUI Vue.js Admin Template">
    <meta name="author" content="creativeLabs Łukasz Holeczek">
    <title>CoreUI Vue.js Admin Template</title>

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="192x192" href="/android-icon-192x192.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="96x96" href="/favicon-96x96.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
    <link rel="manifest" href="/manifest.json">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
    <meta name="theme-color" content="#ffffff">

      We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

I tried changing the image path in the above index.html but no luck any suggestions will be helpful.


text:
Q: jQuery Datatable search option ( alphabetical ) I use jQuery Datatables Plugin.
When I type a in search box Datatables filters all data in table contains a letter
But I want to search (alphabetical ) like this
when I type 'a' just filters all data starts with 'a'

A: You need to modify the DataTables initialization and customize how the filtering works. Check the link below, same exact situation. You'll need to grab the data from the filter box and filter on a stricter RegEx focusing on the beginning of the data in the cells.
http://www.datatables.net/forums/discussion/255/customising-the-way-the-filter-works/p1

A: give this a try then:
oTable.fnFilter( '^a.*', yourColumn, true );

'^a.*' the regex searching for, replace the a with your filter
yourColumn speaks for itself
true needed to treat the first string as a regex, check the api


text:
Q: Looping a number count in Edge Animate I am creating a banner in Adobe Edge Animate with a number count going from 0 to 1000, then slowly going to 1001... 1002... 1003... and then restarting/looping.
I have searched multiple online forums and I am using a code that I found in a previous post that works for the number count (see below), but I cannot get it to loop. Usually when I want to loop a banner I go to a specific time in the timeline and insert a trigger with
this.play (0);

This still loops the banner but not the loop count - it only displays the number 1000 until looping again. Any tips on how to go about this?
Here is link to my banner, when the flashing colors appear is when the banner is looping:
Banner
Here is the code I'm using:
    var counter_delay = 0;
    var max_count = 1000;
    var present_count = 0;

    var timer = window.setInterval(stepUp,counter_delay);
    function stepUp(){
    present_count++;
    // Change the text of an element
    sym.$("Text").html(present_count);
    if(present_count==max_count)
    clearInterval(timer);
    }

A: The variables are not working like this. You have to set and get Variables in Edge.
On Composition Ready
sym.setVariable("variablename", 0);

Get Value
var myVariable = sym.getVariable("variablename");

Change Value and Set it again
myVariable++;
sym.setVariable("variablename", myVariable);

For your Loop i think you can use "onupdate" and just use: get variable, increase variable, set the Value for your Variable again.
Then, if your number is high enough, just set the variable to 0 again.


text:
Q: Cloud sql down and required restart I am using Google CloudSQL and the instance is down for the first time today. Can I find out the reason why in the logs, etc.?
This has happened during high load. I believe CloudSQL should be able to recover automatically. Do I need to set up something for auto-recovery?

A: You should expect occasional CloudSQL instance restarts due to maintenance, etc. There is no detailed information available in the logs at the moment.
And yes, CloudSQL instances should be able to auto-recover in a reasonable amount of time (up to a few minutes).


text:
Q: Alternating sums of the non-trivial zeros of $\zeta(s)$. It is known that the infinite sum of the non-trivial zeros $\rho_n =\beta + \gamma_ni$ of $\zeta(z)$, when taken in pairs that are either conjugated or reflexive (they give the same outcome), converges:
$$Z_1(s):=\displaystyle \sum_{n=1}^\infty \frac{1}{\rho_n^s} + \sum_{n=1}^\infty \frac{1}{\overline{\rho_n^s}}$$
For $s \ge 1, s \in \mathbb{R}$ the sum can be described analytically for integer values e.g. $Z(1)= 1 + \frac{\gamma}{2}-\frac{\ln(4\pi)}{2}$. For $s<1$ the sum diverges.
However the individual sums $\dfrac{1}{\rho_n^s}$ and $\dfrac{1}{\overline{\rho_n^s}}$ do not converge. Even though the real parts do, their imaginary parts diverge and are annihilated by adding both sums together.
I believe there exists an alternative 'alternating' way to split up the total sum into subtotals that each do converge:
Take $\mu_n =\beta + (-1)^n \gamma_ni$ and:
$$Z_2(s):= \sum_{n=1}^\infty \frac{1}{\mu_n^s}+\sum_{n=1}^\infty \frac{1}{\overline{\mu_n^s}}$$
and the individual sums seem to nicely converge for all $\beta \in \mathbb{R}$ and $s \ge 1$. Obviously $Z_1(s)=Z_2(s)$, however I found that contrary to $Z_1(s)$ the domain $Z_2(s)$ can be expanded towards $0 \lt s \lt 1$ by taking:
$$Z_{2-}(s):= \sum_{n=1}^\infty \frac{1}{\mu_n^s}-\sum_{n=1}^\infty \frac{1}{\overline{\mu_n^s}}$$
The difference converges towards an imaginary value and the diverging real parts are annihilated.
Question:
1) Can it be proven that $\displaystyle \sum_{n=1}^\infty \frac{1}{\mu_n^s}$ converges for all $s\ge1$ ?
2) Is there anything known about analytic (closed form) values of  $\displaystyle \sum_{n=1}^\infty \frac{1}{\mu_n^s}$ ?


text:
Q: Chronological order of the Drizzt series A long time ago, when I was a wee child I read some of the Drizzt Do'Urden books, they really captured my imagination. I'd like to continue reading, but I've lost track of which books contain him, and indeed what order they should be read in.
I'm specifically interested in the chronological order (not publication order).

A: In chronological order, they are:

*

*The Dark Elf Trilogy (Homeland, Exile, Sojourn)

*The Icewind Dale Trilogy (The Crystal Shard, Streams of Silver, The Halfling's Gem)

*Dark Mirror, a short story in the Realms of Valor anthology.

*The Legacy of the Drow series (The Legacy, Starless Night, Siege of Darkness, Passage to Dawn)

*The Paths of Darkness series (The Silent Blade, The Spine of the World, Servant of the Shard*, Sea of Swords)

*The Hunter's Blade trilogy (The Thousand Orcs, The Lone Drow, The Two Swords)

*The Transitions trilogy (The Orc King, The Pirate King, The Ghost King)

*The Neverwinter series (Gauntlgrym, Neverwinter, Charon's Claw, The Last Threshold)

*The Sundering (The Companions, Book 1)

*The Companions Codex series (Night of the Hunter, Rise of the King, Vengeance of the Iron Dwarf).

*Homecoming (Archmage, Maestro, Hero).

*Generations (Timeless, Boundless, Relentless).

*The Way of the Drow (Starlight Enclave, Glacier's Edge).

My actual recommendation is to read them in publication order (swap the first two series) as Drizzt changes significantly between the first series and later ones.  To my mind he is more an atypical drow rather than the pure force for good he ends up being in later series.
And if you want my really harsh recommendation, speaking as someone who read up to the Hunter's Blade trilogy, read the Icewind Dale Trilogy and stop there.

*Servant of the Shard is also the first book of The Sellswords series

A: The books that feature Drizzt as a primary character, listed in the in-universe chronology, should be:
The Dark Elf Trilogy

*

*Homeland

*Exile

*Sojourn

The Icewind Dale Trilogy

*

*The Crystal Shard

*Streams of Silver

*The Halfling's Gem

Legacy of the Drow Tetralogy

*

*Legacy

*Starless Night

*Siege of Darkness

*Passage to Dawn

Paths of Darkness

*

*The Silent Blade

*The Spine of the World

*Sea of Swords

The Hunter's Blades Trilogy

*

*The Thousand Orcs

*The Lone Drow

*The Two Swords

Transitions

*

*The Orc King

*The Pirate King

*The Ghost King

The Neverwinter Saga

*

*Gauntlgrym

*Neverwinter

*Charon's Claw

*The Last Threshold

The Sundering:

*

*The Companions

The Companions Codex:

*

*Night of the Hunter

*Rise of the King

*Vengeance of the Iron Dwarf

Homecoming:

*

*Archmage

*Maestro

*Hero

Generations:

*

*Timeless

*Boundless


text:
Q: could not be resolved to an installable set of packages I tried to install package zendmail but I got the error below
k15@k15-Aspire-4732Z:~/Documents/strawberry$ composer require zendframework/zend-mail
Using version ^2.8 for zendframework/zend-mail
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
    - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
    - phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.
    - Installation request for phpunit/php-code-coverage (locked at 4.0.8) -> satisfiable by phpunit/php-code-coverage[4.0.8].

  To enable extensions, verify that they are enabled in your .ini files:
    - /etc/php/7.0/cli/php.ini
    - /etc/php/7.0/cli/conf.d/10-mysqlnd.ini
    - /etc/php/7.0/cli/conf.d/10-opcache.ini
    - /etc/php/7.0/cli/conf.d/10-pdo.ini
    - /etc/php/7.0/cli/conf.d/20-calendar.ini
    - /etc/php/7.0/cli/conf.d/20-ctype.ini
    - /etc/php/7.0/cli/conf.d/20-exif.ini
    - /etc/php/7.0/cli/conf.d/20-fileinfo.ini
    - /etc/php/7.0/cli/conf.d/20-ftp.ini
    - /etc/php/7.0/cli/conf.d/20-gettext.ini
    - /etc/php/7.0/cli/conf.d/20-iconv.ini
    - /etc/php/7.0/cli/conf.d/20-json.ini
    - /etc/php/7.0/cli/conf.d/20-mysqli.ini
    - /etc/php/7.0/cli/conf.d/20-pdo_mysql.ini
    - /etc/php/7.0/cli/conf.d/20-phar.ini
    - /etc/php/7.0/cli/conf.d/20-posix.ini
    - /etc/php/7.0/cli/conf.d/20-readline.ini
    - /etc/php/7.0/cli/conf.d/20-shmop.ini
Linter
Severity  Provider  Description Line

I don't know what I should do with the error. Please help me to solve this problem.

A: You need to install the DOM capabilities for php (as shown by the error message phpunit/php-code-coverage 4.0.8 requires ext-dom * -> the requested PHP extension dom is missing from your system.)
This looks (from the output of extensions) like a Debian based machine. apt install php7.0-xml should allow you to continue.

A: In Zend framework 2, by default mail package will be there, you can just use this piece of code.,
use Zend\Mail;

$mail = new Mail\Message();
$mail->setBody('This is the text of the email.');
$mail->setFrom('Freeaqingme@example.org', 'Sender\'s name');
$mail->addTo('Matthew@example.com', 'Name o. recipient');
$mail->setSubject('TestSubject');

$transport = new Mail\Transport\Sendmail();
$transport->send($mail);

for reference, you can visit this page, https://framework.zend.com/manual/2.1/en/modules/zend.mail.introduction.html


text:
Q: Do we need to delete cookies after session has ended? Sorry, I'm new to php and I'm just wondering are Cookies during sessions terminated after the session ends and if yes, why ?
Thankyou.

A: While a session is supposed to terminate when the user leaves the website, the cookie is meant to store data for the next visit as well. So, no you should not terminate a cookie.
This is not only the case for PHP, it's just what cookies are for:

An HTTP cookie, is a small piece of data sent from a website and stored in a user's web browser while the user is browsing that website. Every time the user loads the website, the browser sends the cookie back to the server to notify the website of the user's previous activity. Cookies were designed to be a reliable mechanism for websites to remember stateful information. - Wikipedia


text:
Q: Broadcast Calendar plugin for Jquery mobile? I'm developing an application in Jquery mobile which requires calendar-business format. i.e Broadcast calendar. I searched for it, but got only normal calendar plugin. Is Broadcast calendar plugins available?
Broadcast calendar

A: I would suggest

*

*dev.jtsage.com/jQM-DateBox

A: I forked jquery-ui datepicker some time ago to do this. It does not have the latest jquery-ui changes, but might get you closer.


text:
Q: PostgreSQL: Why is NOT NULL not working here? I'm developing my first ever application with PostgreSQL.
The Scenario
This is what my table "person" looks like:
   Column   |            Type             |                      Modifiers
------------+-----------------------------+-----------------------------------------------------
 id         | bigint                      | not null default nextval('person_id_seq'::regclass)
 first_name | character varying(255)      | not null
 last_name  | character varying(255)      | not null
 email      | character varying(255)      | not null
 password   | character varying(255)      | not null
 created_at | timestamp without time zone |
 updated_at | timestamp without time zone |
Indexes:
    "person_pkey" PRIMARY KEY, btree (id)
    "person_email_unique" UNIQUE CONSTRAINT, btree (email)
    "person_id_unique" UNIQUE CONSTRAINT, btree (id)
Referenced by:
    TABLE "access" CONSTRAINT "access_person_id_foreign" FOREIGN KEY (person_id) REFERENCES person(id)

This was created using migrations in knex.schema.
If I run the following query in psql...
insert into person (first_name, last_name, email, password) values ('Max', 'Mustermann', '', '123123123');
I get back INSERT 0 1 and the row is successfully inserted:
id | first_name | last_name  |               email               |    password    |       created_at        |       updated_at
----+------------+------------+-----------------------------------+----------------+-------------------------+-------------------------
12 | Max        | Mustermann |                                   | 123123123      |                         |

My Question:
I expect the operation to fail, because no e-mail (NOT NULL) was specified. Why does it not fail?
Thank you very much for your help!
Max

A: Some DBMS (like Oracle) treats empty string ('') as NULL. Others (like MySQL, PostgreSQL, etc) treat empty string and NULL as different.
PostgreSQL treats '' as empty string, not NULL, so your insert statement executed successfully.

A: null and an empty string are not the same values, by passing in an empty string you have satisfied the requirement.
If you query was
insert into person (first_name, last_name, password)
values ('Max', 'Mustermann', '123123123');

then an error would be thrown because you are not passing in a value for email

A: Because you didn't pass a null value.  You passed an empty string.


text:
Q: How to build exe with pyinstaller from python script which uses cvxpy and CBC? I am trying to build exe from a python script to solve LP problem using cvxpy and CBC (through cylp) with pyinstaller. The code is like this:
import numpy as np
import cvxpy as cp

if __name__ == "__main__":
    A = np.array([[2, 0, 0],
                  [1, 0, 2],
                  [0, 3, 1]])
    b = np.array([4, 8, 6])
    c = np.array([3, 4, 2])

    # Define and solve the problem.
    x = cp.Variable(3)
    prob = cp.Problem(cp.Maximize(c.T @ x),
                      [A @ x <= b, x >= 0])
    prob.solve(solver=cp.CBC)
    print(f"solver: {prob.solver_stats.solver_name}")

    # Print result.
    print("The optimal value is", prob.value)
    print("A solution x is")
    print(x.value)

this works correctly with python interpreter
> python .\LP.py
solver: CBC
The optimal value is 16.0
A solution x is
[2. 1. 3.]

but exe made by pyinstaller throws error
> pyinstaller .\LP.spec
> .\dist\LP.exe
Traceback (most recent call last):
  File "LP.py", line 15, in <module>
    prob.solve(solver=cp.CBC)
  File "cvxpy\problems\problem.py", line 396, in solve
  File "cvxpy\problems\problem.py", line 745, in _solve
  File "cvxpy\problems\problem.py", line 500, in get_problem_data
  File "cvxpy\problems\problem.py", line 651, in _construct_chain
  File "cvxpy\problems\problem.py", line 576, in _find_candidate_solvers
cvxpy.error.SolverError: The solver CBC is not installed.
[18960] Failed to execute script LP

Is there a way to fix this?
I cannot avoid using CBC because what I actually want to do is to make an exe solving a Mixed-Integer Programming problem.

My environment:
     numpy: 1.19.1
     cvxpy: 1.1.4
     cylp: 0.91.0
     PyInstaller: 4.0
     Python: 3.7.9
     Platform: Windows 10 v1909 64bit
My spec file (made by pyinstaller .\LP.py -F and I modified datas):
# -*- mode: python ; coding: utf-8 -*-

block_cipher = None

a = Analysis(
    ['LP.py'],
    pathex=['C:\\Users\\aaa\\Desktop\\LP'],
    binaries=[],
    datas=[
        ('C:\\Users\\aaa\\AppData\\Local\\Programs\\Python\\Python37\\Lib\\site-packages\\cylp\\*',
         '.\\cylp\\')],
    hiddenimports=[],
    hookspath=[],
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
          cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          [],
          name='LP',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True)

A: I'm running into the same problem.  I've tried both of the following commands to build, with the same result:
    pyinstaller name_of_my_package.py
    pyinstaller --hidden-imports=cylp name_of_my_package.py

But I still get the same error.  Since I'm building mine with multiple files, I can just go into the dist/name_of_my_package/cylp/ directory and I can see that the cylp module folder exists, but it only has a cy subfolder in that directory.  When I delete dist/name_of_my_package/cylp/cy/ from the build and copy the contents of my cylp folder directly from my python virtual environment into dist/name_of_my_package/cylp/, my exe works.  But you can only do this if you aren't building with the --onefile flag.
I see the following folder structure when I'm done:
    dist/name_of_my_package/cylp/
    |--cpp/
       |--<a bunch of stuff in here>
    |--cy/
       |--<a bunch of stuff in here>
    |--py
       |--<a bunch of stuff in here>
    |--__init__.py
    |--VERSION

The original folder structure that pyinstaller built only looks like this:
    dist/name_of_my_package/cylp/
    |--cy/
       |--<a bunch of stuff in here>

It appears that pyinstaller knows to get the cylp package, but it doesn't copy all of the required pieces.  I'm not sure what the real answer is here, but this workaround works for me for now.  Hopefully, someone can point us to the correct answer.

A: As per the documentation, the "--add-data" option or "Analysis/datas" first string is "relative to the location of the spec file."
pyinstaller Read Doc Using Data File from a Module
I used the console line in Windows (double quotes and semicolon separator) to add the cpp entire directory and the VERSION file (do not need anything else).

pyinstaller --add-data "cylp\cpp;cylp\cpp" --add-data "cylp\VERSION;cylp" LP.py

Add -F if you want the "onefile" build.
Since the first string path is relative, you first need to copy the entire cylp package-site folder from the original python directory into the directory of LP.py
PS: This is my first answer in Stackoverflow!


text:
Q: How to create a new repo at Github using git bash? How can I create a new repository from my machine using git bash?
I followed the below steps:
mkdir ~/Hello-World

cd ~/Hello-World

git init

touch README

git add README

git commit -m 'first commit'

git remote add origin https://github.com/username/Hello-World.git

git push origin master

But I'm getting "Fatal error: did you run update-server-info on the server? "

A: Probably the easiest way to create a repo on github is somewhere before this line:
git remote add origin https://github.com/username/Hello-World.git

go to https://github.com/new and create a repository on github, then  run your last two lines and everything should work.

A: I have created this bash file to do it all automatically.
#!/bin/sh
reponame="$1"
if [ "$reponame" = "" ]; then
read -p "Enter Github Repository Name: " reponame
fi
mkdir ./$reponame
cd $reponame
curl -u USERNAME https://api.github.com/user/repos -d "{\"name\":\"$reponame\"}"
git init
echo "ADD README CONTENT" > README.md
git add README.md
git commit -m "Starting Out"
git remote add origin git@github.com:USERNAME/$reponame.git
git push -u origin master

So how:
copy the code above. save it as NAME.sh, add it to your PATH. restart terminal or open a new one.
$ NAME newreponame
$ NAME
$ Enter Github Repository Name:

Thanks.

A: First, try to do this right before the git push:
git pull repo branch

Then try to do the following:
$ git init --bare yourreponame.git

Then do what you were doing before:
touch README

git add README

git commit -m 'first commit'
git remote add origin https://github.com/username/Hello-World.git
git push origin master

A: I think it is doable.
You can do it using curl (if you are on Windows, you'll have to install it)
curl -u USER https://api.github.com/user/repos -d '{ "name": "REPO" }'

Make sure to replace USER and REPO with your github username and the name of the repository you want to create respectively
It asks for password, input your github admin password and you are good to go.
Actually answered by James Barnett here https://teamtreehouse.com/community/how-does-one-add-a-repository-to-github-using-git-commandline-calls-only

A: You cannot create a repo on github using git bash. Git and github are different things. Github is a platform that let's you host and collaborate on code while git is the version control tool used. You can read more about them on wikipedia articles: github and git.
However if your intention is to create a github repo using terminal, you can do it using the github api and curl.

A: Overview
Command 'git' do not allow you to create repo but it's possible to create new repo at github from BASH script. All solutions use user/password authentication which is deplicated but stil in use. Authentication must be done using personal access token.
Below there are solutions:
3rd party application
https://github.com/github/hub
sudo apt install hub;
cd <folder with code>;
hub init;
hub create -p -d "<repo description>" -h "<project site>" \
"user_name>/<repo_name>";

More options: https://hub.github.com/hub-create.1.html
Pure BASH
REPONAME="TEST";
DOMAIN="www.example.com";
DESCRIPTION="Repo Description";
GITHUB_USER="github_user";

FOLDER="$HOME/temp/$REPONAME";
mkdir -p "$FOLDER"; cd "$FOLDER";

read -r -d '' JSON_TEMPLATE << EOF
{
  "name" : "%s",
  "description" : "%s",
  "homepage" : "%s",
  "visibility" : "private",
  "private" : true,
  "has_issues" : false,
  "has_downloads" : false,
  "has_wiki" : false,
  "has_projects" : false
}
EOF

JSON_OUTPUT=$(printf "$JSON_TEMPLATE" "$REPO_NAME" \
  "$DESCRIPTION" "http://$DOMAIN");

# https://developer.github.com/v3/repos/#create-an-organization-repository
curl -u ${GITHUB_USER} https://api.github.com/user/repos \
  -d "$JSON_OUTPUT"

A: just try to add -u in your last line:
git push -u origin master

A: Maybe you are getting this error because you didn't set your identity:
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
Here you can find the steps to create and put your repository on github:
http://programertools.blogspot.com/2014/04/how-to-use-github.html


text: Q: Invalid character in UTF-8 when geocoding in QGIS I am using QGIS 2.18. As suggested, I installed the MMQGIS plugin to help me geocode the csv file containing a list of addresses. I converted the file to utf-8 encoding format. But when i was trying to import the file, it said my file contains invalid characters. I checked my file and could't spot any.


text:
Q: Found nil while unwrapping an optional value while setting textColor of label I am new in ios and I am making an app using XCode 9.2 with swift 3.2.I am facing a problem which is i am setting textColor of label but it show an error which is: Found nil while unwrapping an optional value in line titleBar.textColor = UIColor.white
    this happens for all IBOutlet in viewController of this class but in same project other view controller work fine Please help me.
    My code is :
    @IBOutlet weak var titleBar: UILabel!
    override func viewDidLoad()
    {
        super.viewDidLoad()
        titleBar.textColor = UIColor.white
    }

A: Add self.titleBar.textColor = UIColor.white and also make sure that you have properly bind the IBOutlet in to your class file

A: The cause of the app crash or found nil is the @IBOutlet is not connected with the storyboard.. somehow the @IBOutlet connection is broken... please check and connect it and then try the code.
*After the connection is done you can use this code -
@IBOutlet weak var titleBar: UILabel! {
   didSet {
   titleBar.textColor = UIColor.white
  }
}


text:
Q: jarsigning using a keystore whose password includes a space I'm signing an APK using a keystore whose password includes spaces, using jarsigner. I'm specifying -storepass and then putting the password in quotes, e.g. -storepass "my password 123".
The sign always goes wrong though, because the key hash is not what I expect it to be. This is crucial for automating the build of my Android app without any user input.

A: jarsigner seems to have an issue with passwords that contain spaces. When entering them after being prompted, it is fine, but using the parameter does not work. So, rather than generating a whole new keystore, change the password to something without spaces like so (taken from this answer)
For the store password:
keytool -storepasswd -keystore my.keystore

And you probably also want to change the key's password:
keytool -keypasswd  -alias <key_name> -keystore my.keystore


text:
Q: Removing CSS from JavaScript? I have CSS style properties "sprinkled" through out my JavaScript code.
Here is an example line:
label_element.style.opacity = 0;

I was planning on moving all CSS out of the code except className changes.
For example if I need to dynamically change some CSS dynamically with JavaScript, I plan to consolidate the changes to a className change as such:
.new_class{
    label_element.style.opacity = 0;
}

Therefore to dynamically change CSS all changes are made with class changes as such:
div_el.className = "new_class";

All CSS remains in the CSS file this way.  JavaScript only has access to class names.
I wanted to verify/validate this is a good way to do it.

A: I would like to suggest using some simple helper functions to add/remove classes instead of appending a classname:
Element.prototype.hasClass = function(name){
    return RegExp('(\\s|^)' + name, 'g').test(this.className);
};
Element.prototype.addClass = function(name){
    if(!this.hasClass(name))
        this.className += (this.className ? ' ' : '') + name;
};
Element.prototype.removeClass = function(name){
    this.className = name ? this.className.replace(RegExp('(\\s|^)' + name, 'g'), '') : '';
};

Demo here: http://jsfiddle.net/EdAEB/

A: Yes, as you probably get from the comments, it's the preferred thing to do. One slight remark, though:
elem.className = 'foobar';

Might not prove ideal when working with multiple classes, best play it safe and go for:
elem.className += ' foobar';

Of course, in cases like this:
window.addEventListener('click', function(e)
{
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (target.tagName.toLowerCase() === 'p' && target.className.test(/\btoggle\b/))
    {
        target.style.display = target.style.display === 'hidden' ? 'block' : 'hidden';
    }
}, false);

You could use a class for that, but I get the feeling that toggles will be doable in CSS3, and you could just leave code like this as is, to support older browsers, for now.

A: About 6 months ago, I was using the following process:

*

*Declare an array called classes

*Use a function to add, remove items from the array. Each item of the array is a css class

*Then join the elements of the array with an space to get an string like:
"class1 class2 class3 class4".

*Apply directly or indirectly, the class string to the className attribute of an element, like this:

document.getElementById('anyElementID').className = classesArray.join(" ");
Now, you don't have to do this, you can simply use the almost recently added DOM classList  API, which has the add, remove, toggle  and contain methods.
Here you go: http://davidwalsh.name/classlist
Have a nice day!

A: I need to go against the grain here..
One of the major disadvantages of having all style in the CSS file, is in situations where style values need to be calculated. One real world example we encountered, was that of a resizable dialog box. As we changed the size of the browser window, then style values (width, and height), need to be calculated. There are many other situations we encountered where style values needed to be calculated, so in the end we had a situation where some CSS was in the CSS files, and some was in the Javascript. This is NOT pretty.
On a more personable level, i find that storing all the style in the CSS file breaks the OO principle of encapsulation. If I have specific styles for a specific object, then those specific styles should be kept with that specific object. As our projects have gotten bigger our CSS files have gotten horrendously ugly.

A: I can't agree...
It depends what javascript has to do. Sometimes it is better to have a class, but not every time. Complicated layout can spam your css file. You are trying to clean your javascript code, but think about it a little. Efect can be also inverted.
For example widgets and plugins. Some plugins require theirs own css file. Some require more then one file. It can make a lot of mess in file structure. And when more people work on one project then it is harder to maintain, modify or repair bugs, because of too complicated file structure and too many class references ...
I solve this seperatly for each style change that I do in javascript. It is more important for me to make code easy to read and maintain then be strict.


text:
Q: How to add a HttpResponse to a C# class I'm generating an Excel file and I want to download it like this in my ASP.NET MVC 5 application:
var ef = new ExcelFile();
var ws = ef.Worksheets.Add("Worksheet 1");

ef.Save(this.Response, "asd.xlsx");

In the last line, it gives error because there is no HttpResponse, how can I add HttpResponse to my class? Thanks.

A: If you want to return a file in ASP.Net MVC5 you can use the File method in your action :

public FileStreamResult MyExcelFile()
{
    // Create your excel filestream

    // ...
    return File(fileStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}