text:
Q: How to change password for logged in user Is there any solution how to make change password for logged in user? i want to make a change password for logged in user, the code i made only change user password with user id number 1. it doesn't change for logged in user. so any idea?
this is my controller:
    public function update(){
$this->form_validation->set_rules('password', 'Current Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('newpass', 'New Password', 'required|alpha_numeric|min_length[6]|max_length[20]');
$this->form_validation->set_rules('confpassword', 'Confirm Password', 'required|alpha_numeric|min_length[6]|max_length[20]');

if($this->form_validation->run()){
    $cur_password = $this->input->post('password');
    $new_password = $this->input->post('newpass');
    $conf_password = $this->input->post('confpassword');
    $this->load->model('queries');
    $userid = '1';
    $passwd = $this->queries->getCurrPassword($userid);
    if($passwd->password == $cur_password){
        if($new_password == $conf_password){
            if($this->queries->updatePassword($new_password, $userid)){
                echo 'Password updated successfully';
            }
            else{
                echo 'Failed to update password';
            }
        }
        else{
            echo 'New password & Confirm password is not matching';
        }
    }
    else{
        echo'Sorry! Current password is not matching';
   }
}else{
echo validation_errors();
}

This is my model:
public function getCurrPassword($userid){
 $query = $this->db->where(['id'=>$userid])
                ->get('users');
if($query->num_rows() > 0){
    return $query->row();
} }
 public function updatePassword($new_password, $userid){
$data = array(
  'password'=> $new_password
  );
  return $this->db->where('id', $userid)
                  ->update('users', $data); }

A: When someone logs in, you must set a $_SESSION to store your user information, such as username, id, email,... to use when you need. Then you can check the $_SESSION['session_name']['id'] to change user password. $_SESSION is important and must be set when user logs in.


text:
Q: Bootstrap Tabs does not work correctly inside jQuery-UI dialog window I am trying to create an MDI like UI for my application. To achieve this, I am using jQuery UI library's dialog.
I have the following helper function to dynamically create a dialog window on the fly:
function createDialog(title, content, options) {
    var defaults = {
        minWidth: 600,
        minHeight: 400,
        width: 600,
        height: 400,
        position: { my: "left top", at: "left top"}
    };
    return $("
" + content + "
")
        .dialog($.extend({}, defaults, options));
}

I create dialog using the above function via the response from my ajax server like this:
function showOrder(order_id)
{
    // Load order info
    $.getJSON('/full_orders/ajaxInfo/'+ order_id)
        .done(function(response) {
            if (!response.isError) {
                createDialog('Order Summary', response.data);
            } else {
                handleError(null, null, response.errorMessage);
            }
        })
        .fail(handleError);
}

So, where ever I have orders on my app, I'd like to be able to bring up the summary details inside a dialog window. The contents of response.data comes from my ajax server, which typically looks like this:

Info

Lines

Customer

Delivery Address

order info here

order lines here

customer info here

delivery address

When the whole thing runs, I am able to click on an order, which fires the showOrder() function and it creates a dialog window dynamically and loads content from ajax server, which contains bootstrap tabs and I am able to switch between all the tabs.
If I were to close the dialog and click the link again, the tabs stop working. I am no longer able to switch between the tabs. If I refresh the page and click on the order again, it works. So, it only appears to work once.
Any idea why this is?

A: Okay, I have figured out why this issue is occurring.
When you closed the dialog, it simply hide the dialog with "display: none". The DOM element remained on the page and was stacking up, each time I opened a dialog.
The way to solve this is by destroying/removing the dialog via the on close event handler.
So, I have updated my createDialog function like this and it has solved my problem:
function createDialog(title, content, options) {
    var defaults = {
        minWidth: 600,
        minHeight: 400,
        width: 600,
        height: 400,
        position: { my: 'left top', at: 'left top' },
        close: function()
        {
            $(this).dialog('destroy').remove();
        }
    };
    return $("
" + content + "
")
        .dialog($.extend({}, defaults, options));
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Need help converting this piece of code to jQuery Anyone jQuery experts here can help me convert the follwing javascript codes to jQuery? Although it works I'd rather see hows it's done with jQuery
function loadit(element)
{
    document.getElementById('container').src = element.rel;
    var tabs = document.getElementById('tabs').getElementsByTagName("a");

    for (var i=0; i < tabs.length; i++)
    {
        if(tabs[i].rel == element.rel)
        {
            tabs[i].className = "selected";
        }
        else
        {
            tabs[i].className = "";
        }
    }
}

Here is the HTML

A

B

C

And here is how I populate the container on windowload:
function startit()
{
    var tabs = document.getElementById('tabs').getElementsByTagName("a");
    document.getElementById('container').src = tabs[0].rel;
}

window.onload=startit;

A: Assuming the parameter passed in (element) is itself a jQuery object, it could look like this.
Note that where ii'm dealing with a jQuery object, I tend to prefix the variable with $ to distinguish it
function loadit($element)
{
    var rel = $element.prop('rel');
    $('#container').prop('src',rel);
    $('#tabs a').each(function(){
        var $a = $(this);
        $a.toggleClass('selected',$a.prop('rel') == rel);
    });
}

edit: I noticed a typo in my code above. I was missing a # from the line
$('#tabs a').each(function(){

Here is a very simplified live example in lieu of your HTML: http://jsfiddle.net/FKf9L/1/
Ive assumed that you're calling loadit when clicking one of the a's which form the tabs. If this is the case it's a bit redundant, you should just latch onto the click event of the a in jQuery. Making the code:
$('#tabs a').click(function(){
   var $this = $(this);
   var rel = $this.attr('rel');
   $('#container').prop('src',rel);
   $this.siblings().removeClass('selected');
   $this.addClass('selected');
});

See this live example: http://jsfiddle.net/p99Q2/
edit2: You may as well do away with the startit method and just issue a click on the first a within the tabs:
$(document).ready(function(){
    $('#tabs a').click(function(){
        ...
    });

    $('#tabs a:first').click();
});

Live example: http://jsfiddle.net/p99Q2/2/

A: This is very basic. Reading a jQuery tutorial for fifteen minutes should teach you enough to do this by yourself in another fifteen minutes.

A: so many ways to do it. this is using more jquery constructs.
function loadit(element)
{
    $('#container')[0].src = element.rel;
    $('#tabs a').each(function(idx){
      var tab = $(this);
      tab.attr('class','');
      if( tab.rel == element.rel )
      {
         tab.attr('class','selected');
      }
    }
}

A: function loadit(element) {

    var rel = element.rel;

   $("#container").attr("src") = rel;
   var $tabs = $("#tabs a");

  $tabs.each(function() {
      var $tab = $(this);

      $tab.removeClass("selected");

      if ($tab.attr("rel") == rel) {
        $tab.addClass("selected");
      }
   });
}


text:
Q: unixODBC 2.3.0 "_S_create_c_locale name not valid" error I am attempting to setup HANA Smart Data Access on an SLES 11 sp3 environment.  For HANA to communicate with external data sources unixODBC 2.3.0 is used along with Microsoft ODBC Driver 11 for SQL Server 2012 (as I am attempting to connect to a MS SQL server db).  I have my odbc.ini and odbcinst.ini in my /etc directory and .odbc.ini in my home directory.  Based on all examples to date these appear to be configured correctly (at one point they were not and I received an appropriate error for them, this has been resolved.)
I am now receiving a new error, which is only returned when I attempt to connect to a datasource listed in my odbc.ini files:
"terminate called after throwing an instance of 'std::runtime_error'
     what():  locale::facet::_S_create_c_locale name not valid
Aborted"
So far my attempts to resolve this include altering the ssh_config file to prevent ssh sending my local environment variables, setting LC_ALL to en_US.UTF-8 and LANG=en_US, setting LC_ALL to c, and various combinations in between.  I have verified with locale -a that en_US.UTF-8, POSIX, and c are all installed.  I found a reference to an issue with boost here https://svn.boost.org/trac/boost/ticket/4688 however this is 5 years old and the impact is listed to sles 10, not 11.

A: I had this problem and it went away when I installed the en_US.UTF-8 locale.
ensure you have that installed on the machine where you are running unixodbc and sqlcmd
https://community.spiceworks.com/how_to/78224-install-the-ms-sql-odbc-driver-on-debian-7


text:
Q: Javascript save settings to one or more cookies? On a blog I am working on, I use a cookie to save a user preference on which side of the layout that the sidebar should show, so I have a cookie something like this...
name: sidebar_switcher
value: right or left
No wI just built a Modal/screen overlay DIV that shows on users first visit, I made it set a DIV once this Modal window is hidden/closed so that I don't nag the user on every visit with it.  SO I now have another cookie being saved like this...
name: subscribe
value: yes or no
So my question, since each Cookie is a new HTTP request as far as I know, should I instead be storing these values into 1 cookie?  If that is the case, then should I do it as a JSON string?
Thanks for advice

A: You could store it as one cookie, or you could use localStorage() with a fallback on cookies.
That way, your users with modern browsers don't need to parse any cookies around.


text:
Q: Finding the location of point P Is it possible to find the location of point $P$ such that the angles $\theta_1=\theta_2$ or $\alpha_1=\alpha_2$?
I know only the locations of $O$, $C_1$, and $C_2$.

A: Here's a geometric construction for $P$. On $OC_1$ as base construct an isosceles triangle $OBC_1$ such that $\angle BC_1O=\angle BOC_1=\alpha-90°$. All points of the circle arc of center $B$ and passing through $O$ make with $OC_1$ an angle $\alpha$. Construct in the same way another isosceles triangle $OAC_2$ and an arc $OC_2$: point $P$ lies then at the intersection of those two arcs.

EDIT.
If the triangle is right-angled at $O$ it is quite easy to find the equation of the locus of point $P$. In that case we can choose the coordinates of the vertices as
$$
O=(0,0),\quad C_1=(a,0),\quad C_2=(0,b)
$$
and the coordinates of the circle centers as
$$
A=(a/2,-ta/2),\quad B=(-tb/2,b/2),
$$
where $t$ is a real parameter. The coordinates of $P$ turn out to be:
$$
P=\left(
{ab(1-t^2)(at+b)\over(at+b)^2+(bt+a)^2},
{ab(1-t^2)(bt+a)\over(at+b)^2+(bt+a)^2}
\right)
$$
and they thus define a parametric curve (shown in diagram below). One can also eliminate $t$ to find the implicit equation of the curve:
$$
(x^2+y^2)(ay-bx)=ab(y^2-x^2).
$$

Notice that only the points on the blue and red arcs of the curve satisfy the request $\angle C_1PO=\angle C_2PO$, while the points on the dashed arcs don't. The blue and red arcs are then the required locus.

A: If you are on a coordinate system, consider $P=(a,b)$ and find the equation of the line $\overline{OP}$. The point $S$ of intersection of lines $\overline{OP}$ and $\overline{C_1C_2}$ is computible.
Finally note that $PS$ is the bisector of angle $C_1PC_2$, thus we have
$$\frac{PC_1}{PC_2}=\frac{C_1S}{SC_2}.$$


text:
Q: ContructorInfo.Invoke vs delegate I've seen several questions here at SO which is about getting a delegate to create an object instead of using ConstructorInfo.Invoke.
Here is an example: Using a Delegate to call a constructor.
I just want to know why? If it's performance-wise, why is a delegate faster?
Update
I do understand that when creating a delegate you get rid of the validations when reusing it. That's one performance increase.
But that happens when a constructor is called through a delegate? Same thing as when doing var a = new XXX() or something else?
Do ConstructorInfo.Invoke() do the same thing as new XXX()? (Disregard any validation)
When using Activator.CreateInstance(), do it do about the same as Constructor.Invoke() (except any type lookup/validation).
I guess that my question boils down to: Can objects be created in different ways (like different IL instructions) or are all mention methods using the same instruction(s), but with different kinds of validations before the actual creation?

A: A few reasons:

*

*In various places, you have to provide a delegate. If something requires a Func<T>, you can't just give it a ConstructorInfo.

*It's type safe - you can guarantee what type will be created (or at least a compatible type) and you know what arguments are required (if any). Calling ConstructorInfo.Invoke, there's plenty to go wrong at execution time every time you call it, rather than just when a delegate is created.

*It's faster, because all the validation (access, arguments) etc is performed once when the delegate is created, instead of every time the ConstructorInfo.Invoke method is called.


text:
Q: install of shindig:error in wampserver I want install shindig in WampServer ,i uncomment always_populate_raw_post_data' to 'On' in php.ini but not work :
Your environment does not have always_populate_raw_post_data enabled which will interfere with Shindig. Please set 'always_populate_raw_post_data' to 'On' in php.ini

A: You have probably edited the wrong php.ini file, there are 2 ( at least )
If you want to edit the php.ini file that is used by Apache, then use the menus on the wampmanager icon that sits in the system tray, this will edit the correct file.
wampmanager -> PHP -> PHP.INI

If you want to use the PHP CLI (Command Line Interface) then edit the php.ini that lives in the \wamp\bin\php\phpx.y.z\php.ini
They both have different and unique uses.
ADDITIONAL INFO ON CURL
For curl to work you also need to uncomment these extensions :-
extension=php_curl

You also need these dll's libeay32.dll and ssleay32.dll which are in the phpx.y.z folder to be on your path. Avoid advice to copy these files to any \windows\?? folders.
It may be easier to just create a simple windows command file that sets the path up so your php folder is on the path.
This is what I use :-
Filename = phppath.cmd
echo off
PATH=%PATH%;C:\wamp\bin\php\php5.3.22
echo ---------------------------------------------------------------
php -v
echo ---------------------------------------------------------------

Change the php5.3.22 folder name to the version of PHP you are using.
Store this file in a folder that is already on your PATH and then you can run it from anywhere in any folder. Once it has been run PHP will be available to you by just running
phppath
php script.php

It should also be able to find libeay32.dll and ssleay32.dll because they are in the php folder which is now in a folder on your PATH.


text:
Q: How to pass parameters to a vm file (Velocity) from another vm file (velocity) through java script? My review.vm file contain a table of records. When user click one of those records in the table ,I want to pass id and data of that record as parameters and call update.vm file from  review.vm file through java script.
the java script function in review.vm looks below:
  function callUpdateVm(id,data) {
    var vmcall = "update.vm";
    window.location.href = vmcall;
    }

may i know how to pass the id and date also to update.vm?

A: If you are using velocity tools, then your javascript can be like:
var vmcall = "update.vm?id=" + id;

and on the server side, your update.vm file can access HTTP query parameters using the ParameterTool:
#set($id = $params.id)

This being said, you must of course be careful about access rules to your update.vm URL if you aren't inside a protected area, otherwise malicious users could trigger unwanted updates.


text:
Q: Firebase Cloud function listener stop after 1-2 hours var admin = require("firebase-admin");

var serviceAccount = require(__dirname+"/myserviceaccount.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "https://myproject.firebaseio.com"
});

db.ref('myref').on("child_changed", function(snapshot) {
   ...
});

package.json
{
  "name": "listener",
  "version": "0.0.1",
  "dependencies": {
    "firebase-admin": "^5.2.1"
  }
}

It works fine until 1-2 hour later and no error log. Anyone can solve this problem?

A: The code you shared doesn't start any Cloud Functions as far as I can see. I'm surprised that it deploys at all, but it definitely won't start a reliable listener in Cloud Functions for Firebase.
To write code that correctly functions in the Cloud Functions environment, be sure to follow the instructions here: https://firebase.google.com/docs/functions/get-started.
Specifically: the correct syntax to set up code in Cloud Functions that is triggered by updates to a database path is:
exports.listenToMyRef = functions.database.ref('/myref/{pushId}')
    .onUpdate(event => {
      // Log the current value that was written.
      console.log(event.data.val();
      return true;
    });


text:
Q: Content of database not showing up in Django I have some problems to get the content out of the django database.
I'm a bloody beginner at django so I did some tutorials. They've worked fine. Now I want to reproduce them in my own project with own variables so I can see if I've understood all the stuff.
So to come to my problem I initalized my modules in models.py
from django.db import models

class Aboutme(models.Model):
    author = models.CharField(max_length=30)
    ...

This works because I could add content to the database.
So there is no mistake.
Now in the views.py
from django.shortcuts import render
from portfolio.models import Aboutme

def portfolio_index(request):

    aboutme = Aboutme.objects.all()
    context = {'aboutme': aboutme}

    return render(request, 'portfolio_index.html', context)

So finally in my HTML file, called portfolio_index.html, I call the content via

{{ aboutme.author }}

I guess it's right. But the content of author doesn't showup, so what did I miss?
I can call static files via django, so couldn't be something wrong with django...
Can anyone help.
Thanks in advance.

A: I think that you need to use a for loop to show "aboutme" because with "aboutme = Aboutme.objects.all()" you query a list of elements.
{% for aboutme_item in aboutme %}

{{ aboutme_item.author }}

{% endfor %}


text:
Q: Linear interpolation along a "Bresenham line" I'm using linear interpolation for animating an object between two 2d coordinates on the screen. This is pretty close to what I want, but because of rounding, I get a jagged motion. In ASCII art:
ooo
  ooo
    ooo
      oo

Notice how it walks in a Manhattan grid, instead of taking 45 degree turns. What I'd like is linear interpolation along the line which Bresenham's algorithm would have created:
oo
  oo
    oo
      oo

For each x there is only one corresponding y. (And swap x/y for a line that is steep)
So why don't I just use Bresenham's algorithm? I certainly could, but that algorithm is iterative, and I'd like to know just one coordinate along the line.
I am going to try solving this by linearly interpolating the x coordinate, round it to the pixel grid, and then finding the corresponding y. (Again, swap x/y for steep lines). No matter how that solution pans out, though, I'd be interested in other suggestion and maybe previous experience.

A: Bresenham's algorithm for lines was introduced to draw a complete line a bit faster than usual approaches. It has two major advantages:

*

*It works on integer variables

*It works iteratively, which is fast, when drawing the complete line

The first advantage is not a great deal, if you calculate only some coordinates. The second advantage turns out as a disadvantage when calculating only some coordinates. So after all, there is no need to use Bresenham's algorithm.
Instead, you can use a different algorithm, which results in the same line. For example the DDA (digital differential analyzer). This is basically, the same approach you mentioned.
First step: Calculate the slope.
m = (y_end - y_start) / (x_end - x_start)

Second step: Calculate the iteration step, which is simply:
i = x - x_start

Third step: Calculate the coresponding y-value:
y = y_start + i * m
  = y_start + (x - x_start) * (y_end - y_start) / (x_end - x_start)

A: Here's the solution I ended up with:
public static Vector2 BresenhamLerp(Vector2 a, Vector2 b, float percent)
{
    if (a.x == b.x || Math.Abs(a.x - b.x) < Math.Abs(a.y - b.y))
    {
        // Didn't do this part yet. Basically, we just need to recurse
        // with x/y swapped and swap result on return
    }

    Vector2 result;
    result.x = Math.Round((1-percent) * a.x + percent * b.x);

    float adjustedPercent = (result.x - a.x + 0.5f) / (b.x - a.x);
    result.y = Math.Round((1-adjustedPercent) * a.y + adjustedPercent * b.y);

    return result;
}

A: This is what I just figured out would work. Probably not the most beautiful interpolations, but it is just a 1-2 float additions per iteration on the line with a one-time precalculation. Works by calculating the number of steps on a manhattan matrix.
Ah, and it does not yet catch the case when the line is vertical (dx = 0)
This is the naive bresenham, but the iterations could in theory only use integers as well. If you want to get rid of the float color value, things are going to get harder because the line might be longer than the color difference, so delta-color < 1.
void Brepolate( uint8_t* pColorBuffer, uint8_t cs, float xs, float ys, float zs, uint8_t ce, float xe, float ye, float ze )
{
    float nColSteps = (xe - xs) + (ye - ys);
    float fColInc = ((float)cs - (float)ce) / nColSteps;
    float fCol = cs;

    float dx = xe - xs;
    float dy = ye - ys;

    float fCol = cs;

    if (dx > 0.5)
    {
        float de = fabs( dy / dx );
        float re = de - 0.5f;

        uint32_t iY = ys;
        uint32_t iX;

        for (   uint32_t    iX = xs;
                            iX <= xe;
                            iX++ )
        {
            uint32_t off = surf.Offset( iX, iY );
            pColorBuffer[off] = fCol;
            re += de;
            if (re >= 0.5f)
            {
                iY++;
                re -= 1.0f;
                fCol += fColInc;
            }
            fCol += fColInc;
        }
    }
}


text:
Q: Pass thru data/time modified from Azure Blobstore to CDN via Imageresizer We've just moved our image hosting to Azure with Imageresizer (v 4.0.5.942) fronted by Cloudflare's CDN but are finding the CDN retains a cached image when the image has changed back on the Azure blobstore.
We used the same CF CDN and Imageresizer on our outgoing image hosting which was an iis box with Imageresizer diskcaching set and didn't have the issue.
The plugin section of our Azure imageresizer config files is -
<add name="AzureReader2" prefix="~/"connectionString=
"DefaultEndpointsProtocol=httpsAccountName=reiwastorstagimg
 AccountKey=xyzxyxyyz"`
checkForModifiedFiles="true" />

A test image is via CDN -
http://azstagingimage.reiwa.com.au/listing/09/2635009-04.jpg?maxwidth=724&maxheight=543&quality=100
Direct to Imaresizer App -
http://azstagingimage3.reiwa.com.au/listing/09/2635009-04.jpg?maxwidth=724&maxheight=543&quality=100
On prem the config contained -
<resizer>
    <plugins>
     <add name="DiskCache" />
    </plugins>

<diskCache autoClean="false" hashModifiedDate="true" subfolders="1024" />
</resizer>

My thinking is when we were on prem with diskcaching turned on, Imageresizer would check the original images date/time stamp, compare it to its cached versions date/time and if changed, would re process the image thereby changing the cached images date/time modified stamp which in turn was picked up by the CDN, causing a re-read.
Looking at the Imageresizer documentation, I believe checkForModifiedFiles="true" would cause Imageresizer to go back to the blob store, get the originating files modified date and pass that to the CF CDN (or browser) but we have it set and it's not doing as we expected.
Does anyone know if there's a way around this or do I need to turn diskcache on in the cloud too?
Thank you in advance.
Kieron

A: ImageResizer stopped serving the "original image" modified date in v3 (for processed requests) - it seems harmless but caused widespread breakage. Some browsers and proxies unfortunately compare last-modified to last fetch dates. It would be nicer to have it behave like an etag, but it doesn't. Last-modified has to be date of output generation or a wide range of side effects start occurring.
checkForModifiedFiles won't have much relevance without DiskCache enabled.
When disk cache is enabled, ImageResizer serves a stable modified date/etag based on when the result was cached. Without disk cache, ImageResizer doesn't send a last-modified date. Typically this doesn't have the effect of causing a CDN to never validate, though, but rather the opposite - too frequent invalidation.
ImageResizer usually plays nice with IIS and ASP.NET header configuration, and in some configurations a last-modified is always set to utcnow. But that's not happening on your server.
The path of least pain is usually the utilization of cache-breakers (like &r=31512351), or treating all blobs as immutable. The high latency of invalidation checks is usually unacceptable for ImageResizer users, and the immutable blob approach is quite popular.
ImageResizer is decent at caching headers with DiskCache, but when there's no storage or way to preserve state - it's hard to have a solution that isn't breaking something with its cache choices.
ImageResizer could do better, though.
If you want custom behavior, PreSendRequestHeaders is an easy spot to make changes. It's also pretty easy to swap out the NoCache and ClientCache plugins for your own classes if you want full control.


text:
Q: When does the replication from primary to secondary happen? I have setup a 3 node replica set.
Writing to primary node works but when I read with readPreference=secondary; I get values as null.
When I open the local node with robomongo I see that the collection does not exist. So it has not been replicated?
I am not sure when it gets replicated or am I missing something?
Update
I have used the following URI
mongodb://DNS1,DNS2,DNS3/?readPreference=secondary&w=0


text:
Q: Is there any way for `ls -d` when not passed any arguments to skip displaying `.`? I have the results of a find command going through xargs to an ls -d. When no files match, I get:
.
as my sole output, because by default ls -d displays:
.
..., when no (filename) arguments are specified. Is there any way for ls -d to omit ., when passed no arguments and just display no output?
Update: You just cannot convince ls -d not to display .:
.
ls -d -A\                # Skip implied
   --hide=.\             # No, really, skip implied
   --ignore=.            # I mean it, damn it!

.
:)

A: Using xargs together with find is sooo 1980s...
Call e.g.:
find . -type d -exec ls -d {} +

and the ls command will never be called without arguments.
The execplus feature has been added to find in 1989 by David Korn for SVr4.

A: You tagged linux, so you probably run GNU xargs, which has this option:
-r, --no-run-if-empty
    If the standard input does not contain any nonblanks, do not run the command.

With find ... | xargs -r ls -d, ls won't be started at all if find doesn't match anything.
find might still match . explicitly. To avoid that, add ! -name . to the find expression. Or use -mindepth 1 (in GNU find) to prevent find from matching any of the paths given on the command line.
(As for how to have ls itself ignore ., I have no idea.)


text:
Q: str.startswith with a list of strings to test for I'm trying to avoid using so many comparisons and simply use a list, but not sure how to use it with str.startswith:
if link.lower().startswith("js/") or link.lower().startswith("catalog/") or link.lower().startswith("script/") or link.lower().startswith("scripts/") or link.lower().startswith("katalog/"):
    # then "do something"

What I would like it to be is:
if link.lower().startswith() in ["js","catalog","script","scripts","katalog"]:
    # then "do something"

Is there a way to do this?

A: str.startswith allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):

From the docs:

str.startswith(prefix[, start[, end]])
Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for.

Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>

A: You can also use any(), map() like so:
if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:
if any(l.startswith(s) for s in x)
    pass # Do something

A: You can also use next() to iterate over the list of patterns.
prefixes = ["xyz", "abc"]
my_string = "abcde"
next((True for s in prefixes if my_string.startswith(s)), False)   # True

One way where next could be useful is that it can return the prefix itself. Try:
next((s for s in prefixes if my_string.startswith(s)), None)       # 'abc'


text:
Q: How to get tweeter data from past years using R? I would like to get tweets regarding certain string from past 4 years. I am using the following code
searchTwitter('dieoff', n=9000, from = '2010-01-01', until = '2015-05-30')

Using this, I was able to get 43 tweets.
But when I tried the same code with different duration (only 1 year and half)
searchTwitter('dieoff', n=9000, from = '2014-01-01', until = '2015-05-30')

I also got 43 tweets. How can I solve such a problem. I would like to get tweets from past 4 years. I am willing to try this out in any language.

A: What you want to do is not possible using the searchTwitter() function because Twitter's search API limits results to within the last week or so (per this thread). I have heard of some workarounds, maybe using rvest, but haven't tried any of these myself.


text:
Q: Power Query conditional formating color rows Is it possible to color the rows in a Power Query based on a formula?
I have tree conditional formats in my Excel sheet and would like them in a query
=$A2-TODAY()>13 (color green), =$A2-TODAY()<1 (color red), =$A2-TODDAY()<14 (color orange)


text:
Q: How to connect ArcMap 10.0 query layer to a different port? I have an instance where I have a server that has postgres 8.3 and postgres 9.2 on it. I have the 8.3 version on port 5432 and 9.2 on port 5433. I want to connect to the 9.2 instance, here is a screenshot of the setup:

This however is not working. It comes back as an invalid username and password because it is trying to connect to the 8.3 version, which the username and password does not exist on. However, if I do try one with the username/password of the 8.3 it works. I believe I am missing something with how ArcMap wants to configure the port number in the configuration box.

A: Looks like you need to add a PGPORT to the Data Source text box. So the result will look like this:


text:
Q: UFT: Excel Process Keeps Running and freezes execution I have an web automation framework in UFT where I've to update the customized excel report. During the report editing part of code, I am facing a strange issue related to excel process/vba object. I have this code stored in function library (.qfl) inside a function and it is called numerous times. The problem is, sometimes the UFT execution freezes and I see a running process of EXCEL.exe. Nothing happens on the screen for hours until I manually kill the process.
On error resume next
Dim objExcel, objWorkbook, objWorkSheet
Set objExcel = createobject("excel.application")
objExcel.DisplayAlerts = False
Set objWorkbook = objExcel.Workbooks.Open("SheetLocation")
Set objWorkSheet = objWorkbook.WorkSheets("SheetName")
intStepRow = objWorkSheet.Cells.Find("WC_01").Row
objWorkSheet.Cells(intStepRow, 7).Value = "SomeValue"
objWorkSheet.Cells(intStepRow, 8).Value = "SomeValue"
objExcel.ActiveWorkbook.Save
objExcel.ActiveWorkbook.Close True
objExcel.Quit()
Set objWorkSheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
On error goto 0

I tried putting a code at the end of function to kill the process but No luck. I also tried setting excel.Visible and .Display to true to see where exactly things go wrong but I don't see anything. I also tried removing the error handling but same, no luck.
Edit:
After enabling logging for each line, I found that below line is freezing the execution
Set objWorkbook = objExcel.Workbooks.Open("SheetLocation")

Thanks in advance for your time and suggestions :)

A: alternatively i find it interesting, could you try using the objExcel.quit() after you realese the object i.e. after you set wroksheet,workbook, excel = nothing.
e.g.
Set objWorkSheet = Nothing
Set objWorkbook = Nothing
Set objExcel = Nothing
objExcel.Quit()


text:
Q: Run a filter when a walker runs Is there any way to run a particular add_filter function whenever a specific Walker_Nav_Menu class runs? The function always needs to run when the walker goes, and I'd like them to share variables, in particular $column_limit. The function should run just before all the other stuff in the walker, in order to add classes to the li's before they get generated.
The purpose of this whole set of PHP is the enable mega-menu functionality in WordPress. Essentially, if I have markup like this:

Example

        Example

Example

Example

Example

Example

Example

Example

Example

Example

Example

With break and widget being classes added by the user in the WordPress menu editor, then the walker and function output this:

Example

        Example

Example

Example

Example

Example

Example

Example

Widget Title

Widget text

Example

Example

Example

The function is adding mega-menu-columns-# to the
 in the above code. All the other changes are being made by the Walker. All of this works, but I'd like it to work with less configuration; essentially I want to be able to set the column limit once, and not have to set the theme_location in the function. If I set a menu to use the walker, I want all of my PHP to run automatically. If this isn't clear enough, just ask for further clarification.
Here's my current code:
// mega menu walker
class megaMenuWalker extends Walker_Nav_Menu {
    private $column_limit = 3; // used to how many columns can be generated (

 and the widgets)
    private $show_widget = false; // used to determine weather or not to show a widget in the drop down
    private $column_count = 0; // for counting how many columns are in a drop down
    static $li_count = 0; // for counting how many lis are in a drop down, used only to check if the li is first in its list
    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $classes = empty($item->classes) ? array() : (array) $item->classes; // retrive array of classes for each li
        $item_id = $item->ID; // retrieve item id for each li, not really used, keeping it to maintain standard WP menu structure
        if ($depth == 0) {
            self::$li_count = 0; // reset the li counter when we return to the top level in the menu
        }
        if ($depth == 0 && in_array("widget", $classes)) {
            $this->show_widget = true; // show the widget if the top level li has a class of "widget"
            $this->column_count++; // if the widget is shown, increase the column counter by one
        }
        if ($depth == 1 && self::$li_count == 1) {
            $this->column_count++; // if there's anything in a drop down, increase the column counter by one
        }
        if ($depth == 1 && in_array("break", $classes) && self::$li_count != 1 && $this->column_count < $this->column_limit) {
            // if we're in ul ul, and an li has a class of break, and it's not the first in its list, and we haven't met the column limit...
            $output .= "

"; // add a break in the list
            $this->column_count++; // increase the column count by one
        }
        $class_names = join(" ", apply_filters("nav_menu_css_class", array_filter($classes), $item)); // set up the classes array to be added as classes to each li
        $class_names = " class=\"" . esc_attr($class_names) . "\""; // set up class HTML
        $output .= sprintf(
            "
%s", // output li structure
            $item_id, // not really used, keeping it for standard WP menu structure
            $class_names, // add the class names
            $item->url, // add the URL
            $item->title // add the title
        );
        self::$li_count++; // increase the li counter. Not used except if == 1
    }
    function start_lvl(&$output, $depth = 0, $args = array()) {
        if ($depth == 0) {
            $output .= "
"; // if a drop down exists, wrap it in
. I'm not sure why $depth == 0 and not 1, but it works, so I'm not complaining.
        }
        $output .= "
"; // output standard WP menu UL for drop downs
    }
    function end_lvl(&$output, $depth = 0, $args = array()) {
        $output .= "
"; // close UL for drop downs
        if ($depth == 0) {
            if ($this->show_widget) {
                // if the parent li has a class of widget...
                ob_start();
                dynamic_sidebar("Navigation Callout"); // show the widget
                $widget = ob_get_contents(); // retrieve the widget's HTML as a variable
                ob_end_clean(); // clear the shown widget
                $output .= $widget; // show the widget
                $this->show_widget = false; // reset the widget variable to false so the next li doesn't get one unless indicated.
                // I know this section is complicated, but it was the only way to correctly display the widget
            }
            $output .= "
"; // end the
 that contains the drop downs.
        }
    }
    function end_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        if ($depth == 0 && $this->column_count > 0) {
            $this->column_count = 0; // reset the column counter when a drop down ends.
        }
        $output .= "
"; // close the li of each menu item
    }
}

// add mega-menu-columns-# classes
// I didn't write this, but I'll do my best to explain it
add_filter("wp_nav_menu_objects", function($items, $args) {
    if ("first" !== $args->theme_location) {
        return $items; // don't run the function if it's not a specific menu. This should really be a check if the walker is set to a menu, not the menu's location.
    }
    static $post_id = 0; // set up the post id variable
    static $x_key = 0; // not sure what this is
    static $column_count = 1; // set the initial column count to 1
    static $column_limit = 3; // set the column limit to 3. Ideally would pull from the walker.
    static $li_count = 0; // set up the li counter
    $tmp = array(); // not sure waht this is
    foreach($items as $key => $item) {
        if (0 == $item->menu_item_parent) {
            $x_key = $key; // not sure...
            $post_id = $item->ID; // set the post ID to the item's ID
            $column_count = 1; // reset the column count
            $li_count = 0; // reset the li count
            if (in_array("widget", $item->classes, 1)) {
                $column_count++; // if widget is in the li class, add 1 to the column count
            }
        }
        if ($post_id == $item->menu_item_parent) {
            $li_count++; // if an item has children, increase the li count by one
            if (in_array("break", $item->classes, 1) && $li_count > 1 && $column_count < $column_limit) {
                $column_count++; // if break is in the item's classes, and the li count isn't one, and the column count is'nt equal to the column limit, increase the counter by one
            }
            $tmp[$x_key] = $column_count; // not sure what this is.
        }
    }
    foreach($tmp as $key => $value) {
        $items[$key]->classes[] = sprintf("mega-menu-columns-%d", $value); // adding the new class based on column count to the lis
    }
    unset($tmp); // not sure
    return $items; // ending the filter
}, PHP_INT_MAX, 2); // not sure

A: If all of it is your own code then it would be reasonable to just implement that as part of walker.
If you need to add a filter while third party walker runs you could probably:
Add it at wp_nav_menu_args hook, checking if walker is set to that:
add_filter( 'wp_nav_menu_args', function( $args ) {

    if ( $args['walker'] instanceof megaMenuWalker ) {

        add_filter( 'wp_nav_menu_objects', 'callback_name_here' );
    }

    return $args;
} );

Remove it at wp_nav_menu hook after the menu markup is completely generated:
add_filter( 'wp_nav_menu', function( $nav_menu ) {

    remove_filter( 'wp_nav_menu_objects', 'callback_name_here' );

    return $nav_menu;
} );


text:
Q: Display including Zero using SQL count(*) and group by For this query  i want to display records zero using SQL Count(*) and group by below is my SQL Query:
SELECT  B.BranchName as Filter,
Coalesce(COUNT(*), '0')   AS NoofSplits,
SUM(ls.Amount) AS TotalLoanValue
FROM    dbo.tblBranch B
LEFT OUTER JOIN dbo.tblLoan L ON L.BranchID = B.BranchID
LEFT OUTER JOIN dbo.tblLoanSplit LS ON L.LoanID = LS.LoanID
WHERE  LS.DateSettlement BETWEEN @StartDate AND @EndDate
GROUP BY B.BranchName
ORDER BY B.BranchName

A: Don't use COUNT(*) when you do an outer join, this will return 1 svn if there was no row to join. You must COUNT the join column of the Outer Table, in your case :
SELECT  B.BranchName as Filter,
    COUNT(LS.LoanID)   AS NoofSplits,
SUM(ls.Amount) AS TotalLoanValue
FROM    dbo.tblBranch B
LEFT OUTER JOIN dbo.tblLoan L ON L.BranchID = B.BranchID
LEFT OUTER JOIN dbo.tblLoanSplit LS ON L.LoanID = LS.LoanID
WHERE  LS.DateSettlement BETWEEN @StartDate AND @EndDate
GROUP BY B.BranchName
ORDER BY B.BranchName


text:
Q: When is a Unique Factorization Domain a Principal Ideal domain "Let $R$ be a Unique Factorization Domain and $(a,b)=(c)$ for $a,b,c \in R$. Show that $R$ is a Principal Ideal domain."
To be honest I found this very hard, here is my naive try:
Lets assume $R$ is a Unique Factorization Domain and $(a,b)=(c)$ $\Rightarrow c$ is gct of $a$ and $b$ then $\Rightarrow (b)\subseteq (c)$ and $(a)\subseteq (c)$ . Since this is true for every pair of Elements of $R$ we can construct a series $(a_1) \subseteq (a_2)\subseteq (a_3) ... \subseteq(a_n)$ in $R$. Because $R$ is a Unique Factorization Domain there is a $N$ with $a_N \in R$ and $(a_i)=(a_N)$ for $i \geq N$.
Let $I$ be an Ideal but not a Principal Ideal, so $I=(d,e,f,...z)$ with $d,e,f,...z \in R$. Then $I= r_1 \cdot d + r_2 \cdot e + r_3 \cdot f ... r_j \cdot z$ for all $r_i \in R$. But because $d,e,f,...z \in R$ and $(d),(e),(f),...,(z) \in (a_N)$, so $d,e,f,...z \in (a_N)$ so there are $\alpha, \beta, ..., \omega $ so that $d=\alpha \cdot a_N$, $e=\beta \cdot a_N$,..., $z=\omega \cdot a_N$. This means:
$$ \begin{align*} I &= r_1 \cdot d + r_2 \cdot e + r_3 \cdot f \ldots r_j \cdot z \\ &= r_1 \cdot \alpha \cdot a_N + r_2 \cdot  \beta \cdot a_N + \ldots r_j \cdot \omega \cdot a_N \\ &= a_N(r_1 \cdot \alpha + r_2 \cdot  \beta \cdot + \ldots r_j \cdot \omega) \in (a_N) \end{align*}
$$
I know that I am wrong somewhere, but I don't really know how to show it. Maybe there is a way to show that $R$ is an Euclidean Ring?

A: Here are some hints hints: every finitely generated ideal is principal (why?), so it's enough to show there is no ideal which is not finitely generated. If $I$ is such an ideal, take elements $a_1,a_2,\dots\in I$ such that $(a_1)\subsetneq(a_1,a_2)\subsetneq(a_1,a_2,a_3)\subsetneq\dots$. Each of those ideals is generated by some element, say $(a_1,\dots,a_n)=(b_n)$. What relations are there between $b_n$? Writing them in terms of their unique factorizations, can you see why we reach a contradiction?

A: Thank you very much for taking the time and helping:
1.) "Every finitely generated ideal is principal":
This follows with induction since $(a,b)=(c)$, then $(a,b,d)=(c,d)=(e)$... Since $(a,b,d) = a\cdot R + b\cdot R + d\cdot R$ and $a\cdot R +b\cdot R = c\cdot R$.
2.) "What relations are between $b_n$?"
$(b_i) \subsetneq (b_{i+1}) \Leftrightarrow (b_{i+1})$ is non-trivial divisor of $(b_i)$
3.) "...can you see why we reach a contradiction":
Unfortunately not. This last step is still unclear for me.


text:
Q: App keeps stopping after I add a email Verification button My application Keeps stopping after I add the Verify Email button. My Email Verification and Application is working correctly before I adding the verify Email Address button. I have included the Logcat and Source code of both xml and Java
Here is the Java code:
package com.dev.hospital;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;

public class MainActivity extends AppCompatActivity {
FirebaseAuth fAuth;
Button resendCode;
TextView verifyMsg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    verifyMsg.findViewById(R.id.verifymsg);
    resendCode.findViewById(R.id.resendcode);
    fAuth = FirebaseAuth.getInstance();

    FirebaseUser user = fAuth.getCurrentUser();

    if(!user.isEmailVerified()) {
        resendCode.setVisibility(View.VISIBLE);
        verifyMsg.setVisibility(View.VISIBLE);

        resendCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirebaseUser users = fAuth.getCurrentUser();
                users.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void aVoid) {
                        Toast.makeText(MainActivity.this,"Verification Email Has Been Sent",Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Log.d("TAGS","onFailure: Email not sent" + e.getMessage());
                    }
                });

            }
        });
    }
}
//Logout function
public void logout(View view) {
    FirebaseAuth.getInstance().signOut();
    startActivity(new Intent(getApplicationContext(),login.class));
    finish();
} }

It shows the warning: Null pointer exception in the module isEmailVerified()
Here is my XML code
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/backgroundmain"
android:clickable="false"
tools:context=".MainActivity">

<TextView
    android:onClick="logout"
    android:id="@+id/logout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/font"
    android:text="@string/logout"
    android:textColor="@color/textcolormain"
    android:textSize="25sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.898"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.052" />

<TextView
    android:id="@+id/verifymsg"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:fontFamily="@font/font"
    android:text="Email not Verified!"
    android:textColor="#ff0000"
    android:textSize="25sp"
    android:visibility="invisible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.498"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.888" />

<Button
    android:id="@+id/resendcode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shapes"
    android:fontFamily="@font/font"
    android:text="Verify Now"
    android:textColor="@color/textColor"
    android:visibility="visible"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.535"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.976" />
</androidx.constraintlayout.widget.ConstraintLayout>

Here is my Logcat: Shows error in onCreate: MainActivity.Java:24
2020-05-06 21:12:56.156 4930-4930/com.dev.hospital E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dev.hospital, PID: 4930
java.lang.RuntimeException: Unable to start activity    ComponentInfo{com.dev.hospital/com.dev.hospital.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2725)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
    at android.os.Handler.dispatchMessage(Handler.java:110)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6261)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1064)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.widget.TextView.findViewById(int)' on a null object reference
    at com.dev.hospital.MainActivity.onCreate**(MainActivity.java:24)**
    at android.app.Activity.performCreate(Activity.java:6705)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2678)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2790)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1528)
    at android.os.Handler.dispatchMessage(Handler.java:110)
    at android.os.Looper.loop(Looper.java:203)
    at android.app.ActivityThread.main(ActivityThread.java:6261)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1064)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:925)


text:
Q: React component testing with Jest I want to test my components using jest, but when I run it i am getting
`Cannot find module 'react-router/Router' from 'Router.js'
  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:191:17)
  at Object.<anonymous> (node_modules/react-router-dom/Router.js:5:15)`

if I start development server my application is working corectly.
My jest config in package.json looks like:
 "jest": {
    "testPathIgnorePatterns": [
      "/node_modules/"
    ],
    "moduleDirectories": [
      "<rootDir>/node_modules",
      "<rootDir>/src"
    ]
  }

A: You are overwriting moduleDirectories and you don't include the default, which is ["node_modules"]. You are including <rootDir>/node_modules instead, which is not the same, because that will only look into the node_modules in the root of your project, whereas "node_modules" follows the module resolution of Node.js. The behaviour of Node.js is to look for node_modules in the current directory, if the module is not found it looks in its parent directory (../node_modules) and so on until the module was found or the root of your file system is reached. For more details see Loading from node_modules Folders.
The important difference is that nested modules break if you change the default behaviour. In your case react-router-dom uses react-router as a dependency, and the node_modules might look like this:
node_modules
├─ jest
└─ react-router-dom
    └─ node_modules
        └─ react-router

In this example, node_modules in the root directory only contains jest and react-router-dom, so it wouldn't find react-router.
Note: npm started hoisting dependencies with version 3 and the result would look like this:
node_modules
├─ jest
├─ react-router-dom
└─ react-router

See also npm v3 Dependency Resolution.
If you are indeed using a severely outdated npm version, you should upgrade immediately. But you should never rely on that behaviour, and always include the default module resolution.
"jest": {
  "testPathIgnorePatterns": [
    "/node_modules/"
  ],
  "moduleDirectories": [
    "node_modules",
    "<rootDir>/src"
  ]
}


text:
Q: How to get the first row of every data record using perl? Data Record looks like this:
  1aaaaaaaaaaaaaaa
  aaaaaaaaaaaaaaaa
  aaaaaaaaaaaaaaaa
  __Data__
  1bbbbbbbbbbbbbbb
  bbbbbbbbbbbbbbbb
  bbbbbbbbbbbbbbbb
  __Data__
  1ccccccccccccccc
  cccccccccccccccc
  cccccccccccccccc

Perl code:
 $/="__Data__";

 open READFILE,"<","a_test.txt" or die "Unable to open file $file";
 while(<READFILE>)
 {
    if(/^([^\n]*)\n([^\n]*)\n/sm)
    {
        print "$1\n";
    }
}
close(READFILE);

This code only outputs 1aaaaaaaaaaaa and not the other first line of the other records. I'm sure there are other ways of doing this but using this code format, how can I get the other records to display only their first line. The ideal results would be:
 1aaaaaaaaaaaaaa
 1bbbbbbbbbbbbbb
 1cccccccccccccc

A: You could change your regex to output desired content,
if (/ (.+) /x) { print "$1\n"; }

in each record this will match first line as you described above.

A: Even though it's tempting to process the file section-by-section, in this case it seems more clear-cut to go line-by-line -- because the desired output is line-oriented. This avoids the need to parse the sections.
my $marker = "__Data__\n";
my $flag   = 1;

while (my $line = <>){
    print $line if $flag;
    $flag = $line eq $marker;
}

A: In one line:
$ perl -nle 'print; $_=<> until /^__Data__/ or eof' input.txt

A: One solution is to remove leading withespace, split in newline character and print first element, like:
while(<READFILE>)
{
    s/\A\s*//;
    printf qq|%s\n|, (split /\n/)[0];
}

A: I will repeat an idea that I've said many times here: A line is only one implementation of the record concept. It is the default implementation, but it is not the only one.

*

*Set the record separator to "\n__Data__\n"

*Simply print all the non-newline characters pulled from a regex:
use English qw<$RS>;
local $RS = "\n__Data__\n";

while ( <> ) { # A generic read
    print /(.*)/, "\n";
}

Thus, you split the data up by records, delimited by __Data__ and pull out only the first line.


text:
Q: Monitor HTTP NetBeans Firstly I had a problem with the antiJARLocking attribute that was showing an error in the console:
WARNING [http-nio-8084-exec-69] org.apache.catalina.startup.SetContextPropertiesRule.begin [SetContextPropertiesRule] {Context} Setting property 'antiJARLocking' to 'true' did not find a matching property.
But I commented this part and it does not appear anymore.
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/DivulgueAqui"/>
<!-- antiJARLocking="true" -->

Then got a bug with the netbeans monitor
Showing this error:
The request can not be recorded most likely because the NetBeans HTTP Monitor module is disabled.

But in my last tests to get this error and put here for you this did not happen!
When I'm trying to run the web service it returns me code 500.
The information is arriving in the method and insert but when it arrives in the dao.insert (u);
The service stops working
    @POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("usuario/inserir")
public String insertUsuario(String json){

    UsuarioDao dao = new UsuarioDao();
    Usuario u = new Usuario();

    JSONObject jsonObject = null;
    JSONParser parser = new JSONParser();

    String nome;
    String email;
    String senha;

       try {
            jsonObject = (JSONObject) parser.parse(json);

            nome = (String) jsonObject.get("nome");
            email = (String)jsonObject.get("email");
            senha = (String) jsonObject.get("senha");

            u.setNome(nome);
            u.setEmail(email);
            u.setSenha(senha);

            dao.inserir(u);

        } catch (ParseException ex) {
            System.out.println("WS.webService.insertUsuario()" + ex);
            Logger.getLogger(webService.class.getName()).log(Level.SEVERE, null, ex);
        }
     return null;

}
My question is. How do I solve this problem?


text:
Q: Cosmological constant in a semiclassical approximation of quantum gravity Why is it the case that, in a semiclassical description of quantum gravity, the cosmological constant is small in Planck units?
Why does this mean that
$$\ell \gg G$$
for $\Lambda = - 1/\ell^{2}$?

A: Semiclassical gravity (and basically anything known today) doesn't say anything about specific value of the cosmological constant. You can consider quantum corrections to the effective cosmological constant, you can look how it changes during phase transitions but there's always some constant term that is unconstrained by theory. At the present level of understanding we have to treat it as a free parameter with some value taken from observations.
This value is very strange having no obvious relation to any other known scale and when you take into account all the phase transitions and how it should be related to some high energy physics. This is a major unsolved problem of the modern physics.


text:
Q: React says refs and imperative code are not the right tool for showing and hiding dialogs. Why though? The docs explicitly state this:

Avoid using refs for anything that can be done declaratively.
For example, instead of exposing open() and close() methods on a Dialog component, pass an isOpen prop to it.

I get the idea and largely agree for reusable components - not having state (which would need to be manipulated imperatively via refs) hidden inside a component makes it easier to reason about and reuse. I'm wondering if this is applicable for concrete dialogs in an application also; if so I'm missing the understanding to use the right tools it seems.
For example: in my application, I have a file tree that shows a menu with options to create, rename, and delete files. Each option will show an appropriate dialog, and these dialogs are encapsulated in their own components. At the bottom of the component hierarchy is a reusable Dialog component:
FileTree
  FileMenu
  CreateFileDialog
    Dialog
  RenameFileDialog
    Dialog
  DeleteFileDialog
    Dialog

I can see two approaches here:

*

*FileTree manages all three dialogs' visibility states, meaning no refs

*the individual dialogs or even the underlying reusable dialog managing visibility state, using refs for showing dialogs when needed

In my concrete case Dialog is a third-party stateless component, but I could add a stateful wrapper for the second approach. And to me, that seems far superior: there is only a single instance of state handling code, encapsulated in the "correct" component. Having three instances of visibility state in FileTree means I need a way to distinguish these states (long names such as createFileDialogVisible or namespacing objects such as createFileDialog.visible).
(In practice there is additional state to be managed, e.g. the new file's name, but that is out of the scope of what the title asks. That said, I think it does impact the feasibility and clarity of putting all dialog state into FileTree.)
Given that I feel option two is so clearly superior, I can't imagine that the guideline is meant to encourage the first. Am I missing an alternative approach, or is this just something that is outside the scope of this guideline?

Appendix
Steps in my reasoning that I think are good candidates for being wrong:

*

*the only alternative to using refs is pulling state into the parent component

*managing state in the parent component makes the described code duplication/namespacing issues unavoidable

*using refs will actually result in less code duplication/more ergonomic code

The following code sample shows a stateless dialog (Dlg), a stateful wrapper (Dialog) and a Consumer for that stateful dialog. In approach 1, FileTree corresponds to Dialog except that there would be multiple visibility states. In approach 2, FileTree corresponds to Consumer, again with multiple refs.
import * as React from 'react';

function Dlg({ visible, onClose }) {
  return visible ? (

      dialog is shown
      <button onClick={onClose}>close</button>

  ) : (
    <dvi>dialog is hidden</dvi>
  );
}

function Dialog(props, ref) {
  const [visible, setVisible] = React.useState<boolean>(false);

  const show = () => setVisible(true);
  const hide = () => setVisible(false);

  React.useImperativeHandle(ref, () => ({ show, hide }));

  return <Dlg visible={visible} onClose={hide} />;
}

Dialog = React.forwardRef(Dialog);

function Consumer() {
  const dialogRef = React.useRef(null);

  const showDialog = () => {
    // eslint-disable-next-line no-throw-literal
    if (dialogRef.current === null) throw 'ref is null';

    dialogRef.current.show();
  };

  return (

        <button onClick={showDialog}>open</button>

      <Dialog ref={dialogRef} />

  );
}

A: What has turned out to be wrong was the second step in my reasoning:

managing state in the parent component makes the described code duplication/namespacing issues unavoidable

When already using hooks, it is easy to extract this into its own hook and provide an API this way. The added benefit compared to refs is that the hook is not null before the first render, so there is no need for a null check to make a type checker happy. The realization to have is this: the Dialog component was purely behavior, it did not add any rendering beyond what Dlg already did; behavior is best abstracted in hooks.
This approach is for example used in material-ui-popup-state. Applied to the example in this question:
import * as React from 'react';

function Dlg({ visible, onClose }) { /* unchanged */ }

function useDialog() {
  const [visible, setVisible] = React.useState(false);

  const show = () => setVisible(true);
  const hide = () => setVisible(false);

  const bindDlg = () => ({
    visible,
    onClose: hide,
  });

  return { show, hide, bindDlg };
}

function Consumer() {
  const dialog = useDialog();

  return (

        <button onClick={dialog.show}>open</button>

      <Dlg {...dialog.bindDlg()} />

  );
}

material-ui-popup-state does it a little bit differently, in that it makes you write <Menu {...bindMenu(popupState)}> instead of <Menu {...popupState.bindMenu()}>. I see two reasons to do it that way:

*

*bindMenu can be declared as a regular function, there is no question whether to memoize the function via useCallback.

*besides bindMenu there is also bindPopover and others. by making it not part of the hook, the hook itself can remain more agnostic of the component onto which it attaches props.

A: You didn't clarify if multiple dialogs can be open at once.
If they can, then they can handle their own visibility state.
I'd they can't then I'd actually look at using a small state machine in FileTree, or  hold it in React Context to prevent drilling.
That way you have a generic "setOpenDiog" piece of state which can be set to false, "create", "rename", "delete". Displaying the right one depending on the current selection.


text:
Q: Own CRM to get used by other application We built our own CRM for our web application which has several other functions.
Now we got the request from the management that also another web application should use our CRM.
Our current web application is a monolithic one, which means that everything is in one big web application developed with Grails.
The first idea from one DEV was to create a REST API so that they can use our CRM functionality and customers are created in our application/DB and will always get synced back to their application.
I think this is not the best idea and much better would be to screw out our CRM from the monolithic web application and make a stand-alone version of it (microservice). This stand-alone version should then be configurable for things like DB, file storage, entities, workflows, ...
What do you guys think about it and maybe does one has another good idea for this specific use case?

A: If you can refactor your existing CRM code into Grails plugins then you can use these plugins in your current application and future Grails applications that need CRM functionality. We are using this approach and have 10+ Grails applications in production and almost all of them are using the same set of CRM plugins.
If you like to see how we split up the domains/contexts you can find the plugins here: http://gr8crm.github.io
However we are currently in the process of migrating all CRM plugins to separate microservices (Spring Boot and Micronaut) but it's a huge effort. My advice is to think carefully before you go that route. If you can break out isolated functionality in your current monolith into microservices step by step, then it could be worth trying. But replacing all features in your current CRM with microservices will probably take longer than you expect.


text:
Q: Suggestions for deciding on a WCMS for a hockey website? I need to make a website for my hockey club. My main purpose for this site is allowing people to sign in and post articles and training schedules in their section. Eg Mens, Womens, Juniors and Masters. I want to have some kind of upload manager that will allow them to choose where they post the info too (eg, Mens, Masters and Homepage).
This is the main functionality I'm looking for at the moment.
The clubs previous website used Joombla which I have hated. I found it to be way to restrictive. Its on a old version of it so there are probably many improvements in the new version but from what I've read it seems like it still has a lot of restrictions in how content is managed. I am open to trying it again tho.
I've used Wordpress before and liked it but that was on a small scale projects and I'm not sure it really fits what I'll be trying to do here, since it mostly deals with blog posts and I'll need to have functionality to upload and display files.
I've had a look around at some other ones like Squarespace and Silverstripe. I'm really liking the simplicity of silverstrip(one thing I hate about Joombla is the clutter on the opening page) and am leaning towards it right now if I can find a nice way to have people post news to multiple pages at once.
If anyone has any suggestions they'd be very welcome. I know html, css, javascript and a bit of php. I'm learning Ruby atm so wouldn't be against using it so I could learn more but it might be a bit much for a sports website.

A: First off, its nice to see someone that likes hockey too :) You can't use Squarespace, you'll need an Apache server for what you want. You will need some way to store information, so you'll need a MySQL database, probably some advanced knowledge of PHP (I'm assuming you don't know how to connect to databases and do some other functions). Wordpress is too limited, so you can't use that. I have never used Silverstripe personally, but it seems like the best of your options here. You'll probably need some more knowledge of PHP before you attempt to make a members system.


text:
Q: SQL select joining tables If I have a table with the following data in MySQL:
id       Name       Value
1          A          4
1          A          5
1          B          8
2          C          9

how do I get it into the following format?
is that even possible?
id         Column   Column   Column    Column   Column    Column
1            A        4         A        5         B        8
2            c        9

A: You can use conditional aggregation:
select id,
       max(case when seqnum = 1 then name end) as name_1,
       max(case when seqnum = 1 then value end) as value_1,
       max(case when seqnum = 2 then name end) as name_2,
       max(case when seqnum = 2 then value end) as value_2,
       max(case when seqnum = 3 then name end) as name_3,
       max(case when seqnum = 3 then value end) as value_3
from (select t.*,
             row_number() over (partition by id order by value) as seqnum
      from t
     ) t
group by id;


text:
Q: Unable to edit or post after enabling SSL After using certbot to enable SSL on my server, I'm unable to edit or create any posts on my wordpress site, any attempt to results in an "Updating failed" message
Attempting to preview posts leaves me on an endless loading screen.
There has been no errors in wp-content's debug.log
Enabling really simple SSL plugin has had no effect and disabling all plugins and themes has the same problem.
Wordpress address and Site address have already been updated to https:// in settings > general
any advice would be greatly appreciated

A: Have you tried flushing permalinks? Sometimes not everything changes right away.
Step 1: In the main menu find "Settings > Permalinks".
Step 2: Scroll down if needed and click "Save Changes".
Step 3: Rewrite rules and permalinks are flushed.


text:
Q: Undeclared identifier, out of scope? (Using a C++ list) I am trying to access an instance of a list in one of my classes.
However I am getting this error:

error C2065: 'blocks' : undeclared identifier
   error C2228: left of '.push_back' must have class/struct/union

Here's my code:
    #include
class Block{
..
..
};

class Test{
..
..
void doSomething(){
    Block b(70,300,1);
    blocks.push_back(b);
}
};

list<Block> blocks;
Test *test;

int main(){
test->doSomething();
}

A: The code doesn't know what blocks is because it is defined globally after the code which is using it.
You need to move this line to be just above the Test class:
list<Block> blocks;

Or alternatively, make this list a member of the Test class rather than a global.
Your code has many other issues too.  For example, you have created a pointer to a Test object but haven't allocated memory for it.  You need to do this at the start of main():
test = new Test();

but then you have to delete it too after use:
delete test;

Even better, just create the Test object on the stack in main:
Test test;

A: Variable list<Block> blocks; is not visible to doSomething(). So you can declare the variable before function or, define function after variable.
class Test {
...
void doSomething();
};
list<Block> blocks;
...
void Test::doSomething ()
{ ... }


text:
Q: Refreshing json on an interval and displaying results without refreshing page I have a JSON like what you see below, that I want to "keep alive".  I would like to continually query the server ("refresh" at a continual interval, say 30 seconds) and update what's displayed on the page accordingly.  The JSON appears as so:
[
        {
            "Name": "Paul",
            "Date": "2012-10-26",
            "Score": 8
        },
        {
            "Name": "Janet",
            "Date": "2012-10-24",
            "Score": 18
        },
        {
            "Name": "Rick",
            "Date": "2012-10-26",
            "Score": 13
        }
]

My current (static) version to display this is:

This of course displays the data, but how would I "stream" the changes to "Score" as the json changes on the server (without refreshing the page)?
Is this what's referred to as polling?
Any help is appreciated.  Thank you

A: You just need to use a timer, or to be more specific, setInterval()...

The above script will run the getData() function at document.ready and then every 30 seconds, and update the #placeholder element with the return value.

A: Without any bells or whistles, you could just wrap that whole thing up in a function and then call it with a setInterval or setTimeout so that it runs the code at the given interval.
Basic example:
function getData(){
  ... your code ...

  setTimeout( getData, 3000 ); // Get data and refresh page every 3000 ms (3 seconds)
}

// Call function to kick off data collection
getData();


text:
Q: Laravel gettext or native localization? I would like to ask what and why would be the preferred tool for localizing Laravel projects? I have already used a gettext plugin and it worked well. I like using POedit which allows translators using it without programming skills. Plus, the translation hints are cool, too.
Is there any good reason for using Laravel native localization? Or, are there any cons of using gettext?
Thanks!

A: Why not both: GetText and native localization?

*

*Using GetText with source text is great for developers to work quickly and efficiently on new features without having to "make up" keys, switching files, maintaining consistency between keys and source text etc. Also, using GetText makes it easier to check if everything is translated and you don't need to worry if some keys/values are obsolete.

*Using PHP trans() with keys/values is great for copywriting. It's easy for the marketing team or CEO to change the text for all languages (included the source language) without changing the code.
For these reasons, we created https://translation.io/laravel that allows you to use both syntaxes at the same time (and we suggest to only use PHP key/value when the source text needs to be editable through the translation interface).
The package is here is you need more technical info: https://github.com/translation/laravel

A: The native localization method is described in the Laravel documentation. You basically maintain language files for all languages you want to translate to. To pull them out of the file, you use trans(), trans_choice() (for plural) or __() helpers in Blade template.
Thats the most basic translation handling. At one level higher you might want save all translations to the database. There exists a few packages on Github which doing this. Like:

*

*https://github.com/dimsav/laravel-translatable

*https://github.com/barryvdh/laravel-translation-manager
and more. Just search for Laravel Translation.
This method only works as long as you use Blade for the frontend. If you use VueJs, Angular or React, the blade helpers won't work anymore and you have to find different ways how to handle this. This might depend on existent language handling of the aforementioned frontend framework.
I wrote an blog article about that topic.

A: @Peter Matisko, can you give us a little update on how did you decide, which one are you preferring to use?
Personally I tried quite a couple of different translation libraries, but gettext is still first choice for me:

*

*extract all the translations from code and generate translation files (*.po)

*translations editor that runs on Mac, Windows and Unix (Poedit initial release ~20 years ago)

*translating plural forms


text:
Q: Executable Jar with Eclipse & Libgdx This is the first time I have tried to create an executable jar file from Eclipse, and I am confused as to how to do so. I know that there is the option to export a java file as a "jar" and "executable jar", but I am not sure how to ensure that my libgdx libraries, assets, and HighScore.txt file are fully integrated and are working. Furthermore, like most packages my package has a myriad of classes - one of which is the main class. How do I export the jar files and instruct eclipse that this specific class is the main class.
Here is an image of my file structure:

MainSimpleBike is my main class.

A: *

*Using the default jar
You specify your main class during runtime, like:
java -jar MyJar.jar MainSimpleBike

*You may also modify the manifest.txt by following the instruction here:
http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
If you modify the manifest.txt, like:
Main-Class: com.me.mygdxgame.MainSimpleBike

To create a jar:
jar cfm MyJar.jar Manifest.txt com.me.mygdxgame/*.class

You can simply run:
java -jar MyJar.jar

Your main class will be picked up automatically.

A: You can create an executable .jar file for Libgdx desktop apps from within Eclipse.  (@Mingyu's answer is correct, but requires manually creating the Manifest and doesn't take advantage of Eclipse's infrastructure.)
First, you need to make a "Launch Configuration" (this is needed to run your desktop app from Eclipse anyway).

*

*On the Run menu select Run Configurations ...,

*pick the Java Application entry on the left, and click the "New"
button to make a new configuration.

*On the right you'll pick the main class, the JRE, the classpath, etc.

For more details see the  Eclipse documentation
Now that you've told Eclipse how to run your Desktop Libgdx app, you just need to package that up into an executable Jar.

*

*Right-click on your desktop project and select Export....

*Choose Runnable JAR file (do not choose the JAR file entry).

*Click Next and now pick the launch configuration you just made, and
where to save the .jar.

For Libgdx I've found that the "Package requires libraries into generated JAR" option generates a working JAR file.

A: Run gradlew desktop:dist from the command line in the root of your project.  This will create a runnable jar file in .\desktop\builds\libs.


text:
Q: Не могу понять как решить задачу по Python Есть условие задачи:
Система «Контроль движения поездов» сохраняет информацию о поездах, которые шифруются
именами, названиями станций прибытия и плановым временем прибытия поезда на конечную
станцию. Написать программу, которая по введенному диапазону времени выводит на экран время
прибытия каждого поезда в заданном диапазоне, наименование поезда, пункт его
прибытия. Время прибытия поездов в заданном диапазоне расположить в порядке возрастания.
Считать, что поезда прибывают в моменты времени, кратные 30 минутам. Если при вводе
выходных данных следует, что, хотя бы два поезда одновременно прибывают в один пункт, то
должно выводиться сообщение об аварийной ситуации и запрос на ввод новых данных.
Не могу понять, как определить то, что хотя бы два поезда одновременно прибывают в один пункт.
Написал такой код, пытаясь идентифицировать значения времени по счетчикам:
from datetime import time
from collections import Counter

a = [{'train_code': '887B', 'station': 'Lipki', 'time_arrive': time(10, 00)},
     {'train_code': '411C', 'station': 'Kyiv   ', 'time_arrive': time(12, 00)},
     {'train_code': '887B', 'station': 'Lipki', 'time_arrive': time(10, 00)},
     {'train_code': '113F', 'station': 'Rivne', 'time_arrive': time(11, 30)}]

start_time = time(hour=int(input("h: ")), minute=int(input("m: ")))
end_time = time(hour=int(input("h: ")), minute=int(input("m: ")))
s = sorted(a, key=lambda x: x['time_arrive'])

for train in s:
    if start_time <= train.get('time_arrive') <= end_time:
        print(train)

s_tuple = tuple(k.get('time_arrive') for k in s)
train_counter = {k: s_tuple.count(k) for k in set(s_tuple)}
print(train_counter)

Идея со счетчиками показалась мне наиболее разумной, но даже ее я не могу нормально реализовать. Жду ваших идей.
UPD: нужно сравнить каждый словарь в списке друг с другом по значениям station и time. Если эти значения совпадают в разных словарях, вывести в консоль сообщение об этом этом.
Примечание: Есть идея создать копию списка и сравнить словари копии со словарями основного списка, но не ясно как применить это в коде. Буду благодарен за любую помощь.

Максимально приблизился к выполнению данной задачи, но столкнулся с проблемой выхода из цикла.
import pandas as pd
from datetime import time

flag = True
while flag:

  a = [{'train_code': '887B', 'station': 'Lipki', 'time_arrive': time(12, 00)},
      {'train_code': '411C', 'station': 'Kyiv   ','time_arrive': time(10, 00)},
      {'train_code': '743L', 'station': 'Lipki', 'time_arrive': time(12, 00)},
      {'train_code': '113F', 'station': 'Rivne', 'time_arrive': time(11, 00)}]

  start_time = time(hour=int(input("h: ")), minute=int(input("m: ")))
  end_time = time(hour=int(input("h: ")), minute=int(input("m: ")))
  s = sorted(a, key=lambda x: x['time_arrive'])

  for train in s:
    if start_time <= train.get('time_arrive') <= end_time:
      print(train)
      df = pd.DataFrame(a)
      res = df.groupby(["time_arrive", "station"]).filter(lambda x: len(x) > 1)
  print(res)
  print(res["time_arrive"].to_list())

  for i in res["time_arrive"].to_list():
    if start_time <= i <= end_time:
        count = len(res)
        print(count)
        if count >= 2:
            print('Error')
            break
            flag == True

        else:
            flag == False
            break

Подскажите пожалуйста почему не работает цикл выхода из программы, хотя по логике, вроде бы алгоритм построен правильно.

A: Воспользуйтесь модулем Pandas для удобной обработки и анализа табличных данных:
In [12]: import pandas as pd   #  pip install pandas

In [13]: df = pd.DataFrame(a)

Исходный DataFrame:
In [14]: df
Out[14]:
  train_code station time_arrive
0       887B   Lipki    10:00:00
1       411C    Kyiv    12:00:00
2       887B   Lipki    10:00:00
3       113F   Rivne    11:30:00

поиск строк с одинаковым временем прибытия:
In [15]: res = df.groupby("time_arrive").filter(lambda x: len(x) > 1)

результат:
In [16]: res
Out[16]:
  train_code station time_arrive
0       887B   Lipki    10:00:00
2       887B   Lipki    10:00:00

A: В начале замечание по вашему коду:
a = [{'train_code': '887B', 'station': 'Lipki', 'time_arrive': time(12, 00)},
      {'train_code': '411C', 'station': 'Kyiv   ','time_arrive': time(10, 00)},
      {'train_code': '743L', 'station': 'Lipki', 'time_arrive': time(12, 00)},
      {'train_code': '113F', 'station': 'Rivne', 'time_arrive': time(11, 00)}]

Неправильно добавлять преобразование времени прибытия типа time(12, 00) в каждую запись вручную. Количество записей может меняться - сейчас у вас 4 записи, а может быть и 40. Также возможна ситуация, когда записи читаются из файла или из базы данных. Список должен содержать только данные, преобразование нужно делать динамически - либо изменяя этот список, либо создавая новый.
Я разбил решение задачи на три шага:

*

*Прохожусь по исходному списку с поездами, извлекая из него имя станции и время прибытия поезда и формирую из этих данных таблицу прибытия типа: словарь[время][станция] = [{поезд_1}, {поезд_2}, {поезд_3}, ...]. Таким образом, если словарь['12:30']['Kyiv'] имеет список длиной больше единицы, то это означает совпадение времени прибытия двух или более поездов на эту станцию. При желании, уже на этом шаге можно выдавать сообщение об ошибке.

*Получив от пользователя временной диапазон, перебираю все подходящие варианты времени прибытия. Для каждого варианта перебираю станции попадающие на это время. Если станция имеет 1 поезд - печатаю, иначе сообщение об ошибке.

*Если пункт 2 отработал без ошибок, то завершение работы программы, иначе повтор пункта 2.
Можно сделать, чтобы программа не печатала ни одного поезда при наличии пересечения поездов, а просто запрашивала новый временной диапазон.
Или наоборот, чтобы программа сначала печатала все поезда, включая пересекающиеся, потом выдавала сообщение об ошибке.
У меня сделан промежуточный вариант: печатаются только поезда до первого пересечения, при наличии которого выдаётся ошибка и происходит запрос нового диапазона.
Решение
#!/usr/bin/python3

from datetime import timedelta, datetime
from collections import defaultdict

def get_time():
    # функция datetime() кроме времени требует год, месяц, день, поэтому
    # передаём произвольные - в качестве заглушки.
    return datetime(2001,1,1, hour=int(input("h: ")), minute=int(input("m: ")))

def print_trains(arrival_table):
    start_time = get_time()
    end_time = get_time()
    # Устанавливаем временной интервал для проверки расписания
    step = timedelta(minutes=30)

    cur_time = start_time
    while cur_time <= end_time:
        if cur_time in arrival_table:
            # Перебираем все поезда приходящие в указанное время.
            # Если в указанное время на станцию приходит больше одного
            # поезда, то печатаем сообщение об ошибке и
            # завершаем работу функции, иначе печатаем информацию о поезде.
            for station, train_lst in arrival_table[cur_time].items():
                print(cur_time.time())
                if len(train_lst) > 1:
                    print(f"Emergency situation on station {station}!")
                    print("Choose another time range.")
                    return 0
                else:
                    print(train_lst[0])

                print()
        # Увеличиваем время
        cur_time += step
    return 1

def make_arrival_table(trains):
    for record in trains:
        # Преобразуем время из строчного типа в datetime.
        # Год, месяц, день добавляем произвольные.
        record['time_arrive'] = datetime.strptime('2001 1 1 ' + record['time_arrive'], '%Y %m %d %H:%M')
    # defaultdict нужен для избавления от проверок на существование
    # требуемого ключа. При отсутствии ключ создаётся автоматически.
    arrival_table = defaultdict(lambda: defaultdict(list))

    for entry in trains:
        arrival_table[entry['time_arrive']][entry['station']].append(entry)

    return arrival_table
# поле 'time_arrive' изменено на строчный тип
trains = [
            {'train_code': '887B', 'station': 'Lipki', 'time_arrive': '10:00'},
            {'train_code': '411C', 'station': 'Kyiv', 'time_arrive': '12:00'},
            {'train_code': '887B', 'station': 'Lipki', 'time_arrive': '10:00'},
            {'train_code': '113F', 'station': 'Rivne', 'time_arrive': '11:30'}
        ]

arrival_table = make_arrival_table(trains)
# Цикл будет повторяться, пока не будет найден интервал
# без пересекающихся поездов
while not print_trains(arrival_table):
    pass

A: Задача решена.
import pandas as pd
from datetime import time

flag = True
while flag:

    # информация  поездах
    a = [{'train_code': '887B', 'station': 'Lipki', 'time_arrive': time(12, 00)},
         {'train_code': '411C', 'station': 'Kyiv   ', 'time_arrive': time(10, 00)},
         {'train_code': '743L', 'station': 'Lipki', 'time_arrive': time(12, 00)},
         {'train_code': '113F', 'station': 'Rivne', 'time_arrive': time(11, 00)}]

    # вводим диапазон времени приходящих поездов

    while True:
      try:
        start_time = time(hour=int(input("Enter start hours: ")), minute=int(input("Enter start minutes: ")))
        end_time = time(hour=int(input("Enter last hours: ")), minute=int(input("Enter last minutes: ")))
        break
      except ValueError:
        print('Enter an integers!')
    s = sorted(a, key=lambda x: x['time_arrive'])

    # проверяем прибытие каких поездов совпадает с заданым нами диапазоном

    for train in s:
        if start_time <= train.get('time_arrive') <= end_time:
            print(train)
            df = pd.DataFrame(a)
            res = df.groupby(["time_arrive", "station"]).filter(lambda x: len(x) > 1)
            count = len(res)

    # если среди маршрутов есть такие, что приходят на одну станцию в одно и то же время, выводим ошибку и просим ввести новые данные

    for i in res["time_arrive"].to_list():

        if (start_time <= i <= end_time) and (count >= 2):
                print(f'There are {count} wrong destinations')
                print('Accident error. Choose the other time range please.')
                break

            # если "ошибочных маршрутов" нет, прекращаем работу программы

        else:
                flag = False
                break


text:
Q: how to get different samples from same random op in single session I am trying to get multiple samples from xr by stacking xr op. Now, it seems that it just gives you same values. Is there a way I can get different values or xr in single session?
import tensorflow as tf
import tensorflow.random as tdr
import numpy as np

x = 5. # fixe_input
xr = tdr.uniform(shape=[1],minval=0., maxval=x)
x_list = tf.stack([xr for _ in range(10)]
with tf.Session() as sess:
    print('xlist', sess.run(x_list))

Output:
xlist [[2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]
 [2.2005057]]

A:
Is there a way I can get different values or xr in single session?

No, each node is evaluated once. Instead, why not change shape=[1] to be shape=[10]? That will give you an array of 10 samples from your distribution with a single sess.run call.
import tensorflow as tf
import tensorflow.random as tdr
import numpy as np

x = 5. # fixe_input
xr = tdr.uniform(shape=[10],minval=0., maxval=x)
with tf.Session() as sess:
    print('xlist', sess.run(xr))

xlist [2.6705563  1.477465   2.2741747  0.44075608 0.41182756 3.652794
   2.3826408  4.6979356  2.0650215  1.4842021 ]

A: You are essentially generating the random number once, catching it in a variable, and then copying it as in first part below.  You want to invoke the random function for each item in your list as seen in second part below.
In [2]: from random import randint

In [3]: x = randint(1,1000)

In [4]: random_nums = [x for _ in range(10)]

In [5]: random_nums
Out[5]: [728, 728, 728, 728, 728, 728, 728, 728, 728, 728]

In [6]: random_nums2 = [randint(1, 1000) for _ in range(10)]

In [7]: random_nums2
Out[7]: [92, 928, 72, 875, 719, 725, 957, 930, 729, 299]

In [8]:


text:
Q: $(...).autocomplete is not a function on second call I know there are other questions like this one, but none of them could help me.
Here's my Code:
var surnameOptions = @Html.Raw(JsonConvert.SerializeObject(ViewBag.originatorsSurname));
var prenames = @Html.Raw(JsonConvert.SerializeObject(ViewBag.originatorsPrename));

$("#surname").autocomplete({
    source: surnameOptions
});
$("#prename").focus(function(){
    if (! $("#surname").val() == ""){
        var prenameOptions = Array();
        for (i = 0; i < prenames.length; i++){
            if (surnameOptions[i] == $("#surname").val()){
                prenameOptions.push(prenames[i]);
            }
        }
    } else{
        var prenameOptions = @Html.Raw(JsonConvert.SerializeObject(ViewBag.originatorsPrename));
    }
    $("#prename").autocomplete({
        source: prenameOptions
    });
});

I don't know why, but the error only appears on the second .autocomplete call.
The rest of the code works.
The libraries are included just before this script:
<script src="~/Scripts/jquery-ui.js"></script>
<script src="~/Scripts/jquery-ui.min.js"></script>

Why is the second .autocomplete not working?


text:
Q: Does Ansible have to share root key between nodes and Ansible playbook server? As title, it seems not safe to run everything on root, especially when playbook server get hacked and it could ssh into any machines on the Ansible host list, what's the solution for this security problem?

A: I create a user specifically for the use of ansible, which can use passwordless sudo, but which has no defined password and requires an ssh key to login. In this way, the account is privileged but it is not accessible remotely without the ssh key.
Alternately, you can create the ansible account with a password, and require the sudo password each time you run ansible.
You can create such a user like this:
# Create user
adduser ansible

# Lock password preventing password login (optional)
passwd -l ansible

# Expire any existing password, preventing password login (optional)
chage -E 0 ansible

# Ensure ansible can sudo without a password (optional)
echo "ansible ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/ansible

# Create ansible's .ssh directory
mkdir -m 700 /home/ansible/.ssh

# Insert your desired SSH keys here
echo "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB7/BSV84tCEQ8SSwygqjEVPFcH+G2JSFEdyuJI7A2iG ansible-runner@example.com" > /home/ansible/.ssh/authorized_keys

# Correct ownership of newly created files and directories
chown -R ansible.ansible /home/ansible/.ssh

Adapt this as necessary to whatever process you use to bring up new server instances (kickstart, preseed, cloud-init, whatever).
I then set up ansible.cfg for passwordless sudo:
[defaults]
remote_user = ansible

[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

If you wish to require a sudo password to run playbooks, you can simply set become_ask_pass = True in ansible.cfg, and do not create /etc/sudoers.d/ansible as shown above.

A:
[ ] when playbook server get hacked and it could ssh into any machines on the Ansible host list, what's the solution for this security problem?

There is no solution to this security problem.
If the machine executing playbooks is compromised, servers managed by this machine should be considered compromised too.
Rephrasing: machine executing Ansible playbooks must fulfill security requirements of the servers themselves.

This applies to any machine used for administering the servers.
If a workstation used for administrative purposes is compromised, any program executed on that workstation and connecting to a server with a legitimate credentials can be replaced with a malicious one.
And that malicious code can do anything to the administered server using those credentials supplied "in good faith".
Moreover, using Ansible poses additional risks as:

*

*the Ansible code itself is commonly maintained in the userspace (say pip install ansible using a regular account, or a virtual env) -- for an attacker it might not even be necessary to gain elevated permissions on the workstation to change Ansible code to execute arbitrary code in a stealth way (because no administrator verifies Ansible Python's code every time it executes Ansible).

*Commands requiring elevated permissions executed by Ansible cannot be explicitly specified in the sudoers on the administered servers (i.e. Ansible requires ALL commands to be enabled).

The security of a system consisting of a server and administrative workstation is only as high as the security level of the weakest link.


text:
Q: How to mock an async instance method of a patched class? (The following code can be run in Jupyter.)
I have a class B, which uses class A, needs to be tested.
class A:
    async def f(self):
        pass

class B:
    async def f(self):
        a = A()
        x = await a.f()  # need to be patched/mocked

And I have the following test code. It seems it mocked the class method of A instead of the instance method.
from asyncio import Future
from unittest.mock import MagicMock, Mock, patch

async def test():
    sut = B()
    with patch('__main__.A') as a:  # it's __main__ in Jupyter
        future = Future()
        future.set_result('result')
        a.f = MagicMock(return_value=future)
        await sut.f()

await test()

However, the code got the error of:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\X~1\AppData\Local\Temp\1/ipykernel_36576/3227724090.py in <module>
     20         await sut.f()
     21
---> 22 await test()

C:\Users\X~1\AppData\Local\Temp\1/ipykernel_36576/3227724090.py in test()
     18         future.set_result('result')
     19         a.f = MagicMock(return_value=future)
---> 20         await sut.f()
     21
     22 await test()

C:\Users\X~1\AppData\Local\Temp\1/ipykernel_36576/3227724090.py in f(self)
      6     async def f(self):
      7         a = A()
----> 8         x = await a.f()  # need to be patched/mocked
      9
     10 from asyncio import Future

TypeError: object MagicMock can't be used in 'await' expression

A: Need to change
a.f = MagicMock(return_value=future)

to
a().f = MagicMock(return_value=future)

A: In Python 3.8+, patching an async method gives you an AsyncMock, so providing a result is a little more straightforward.
In the docs of the patch method itself:

If new is omitted, then the target is replaced with an AsyncMock if the patched object is an async function or a MagicMock otherwise.

AsyncMock lets you supply a return value in a much more straightforward manner:
import asyncio
from unittest.mock import patch

class A:
    async def f(self):
        return "foo"

class B:
    async def f(self):
        return await A().f()

async def main():
    print(await B().f())

    with patch("__main__.A.f", return_value="bar") as p:
        print(await B().f())

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        sys.exit(1)

....prints:
$ python example.py
foo
bar

The side_effect kwarg covers most kinds of values you'd be looking to return (e.g. if you need your mock function await something).

*

*if side_effect is a function, the async function will return the result of that function,

*if side_effect is an exception, the async function will raise the exception,

*if side_effect is an iterable, the async function will return the next value of the iterable, however, if the sequence of result is exhausted, StopAsyncIteration is raised immediately,

*if side_effect is not defined, the async function will return the value defined by return_value, hence, by default, the async function returns a new AsyncMock object.


text: Q: Is there a Force-focused lightsaber style more warrior oriented than Niman? Niman seems to be the most Force centric style but I believe that it's lacking in both offense and defense, and it doesn't have a good record either, most of Niman's specialists died on the first battle of Geonosis.


text:
Q: trigger my code when a email is added to mailbox? Is there a way to triiger c# code when a email appears in a exchange mailbox ? The mailbox belongs to a servcie account.
I am flexible about using Azure, on a IAAS solution. Thanks,PEter