text:
Q: React-Konva Free Drawing with hooks I found a good example using React-Konva and Free Drawing, but i could pu working with React-Hooks. That example is very nice and simple. It could be found here:
React-Konva Example
import React, { Component } from "react";
import Konva from "konva";
import { render } from "react-dom";
import { Stage, Layer, Line, Text } from "react-konva";

class App extends Component {
  state = {
    lines: []
  };

  handleMouseDown = () => {
    this._drawing = true;
    // add line
    this.setState({
      lines: [...this.state.lines, []]
    });
  };

  handleMouseMove = e => {
    // no drawing - skipping
    if (!this._drawing) {
      return;
    }
    const stage = this.stageRef.getStage();
    const point = stage.getPointerPosition();
    const { lines } = this.state;

    let lastLine = lines[lines.length - 1];
    // add point
    lastLine = lastLine.concat([point.x, point.y]);

    // replace last
    lines.splice(lines.length - 1, 1, lastLine);
    this.setState({
      lines: lines.concat()
    });
  };

  handleMouseUp = () => {
    this._drawing = false;
  };

  render() {
    return (
      <Stage
        width={window.innerWidth}
        height={window.innerHeight}
        onContentMousedown={this.handleMouseDown}
        onContentMousemove={this.handleMouseMove}
        onContentMouseup={this.handleMouseUp}
        ref={node => {
          this.stageRef = node;
        }}
      >
        <Layer>
          <Text text="Just start drawing" />
          {this.state.lines.map((line, i) => (
            <Line key={i} points={line} stroke="red" />
          ))}
        </Layer>
      </Stage>
    );
  }
}

render(<App />, document.getElementById("root"));

I tried to reproduce it with react Hooks, but I its not worked, maybe Im missing something. Actually, I really don't understood exactly how it works.
  export default function RenderMap(tokens) {

    const [lines, setLines] = useState([])

    function handleMouseDown({ evt }) {
    setIsDrawing(true)

    setLines([...lines, []])
  }

     function handleMouseUp() {
    if (isDrawing) {
      setIsDrawing(false)
    }
  }

     function handleMouseMove({ evt }) {
    if (!isDrawing) {
      return
    }
    const { offsetX, offsetY } = evt

    if (isDrawing) {
      let lastLine = lines[lines.length - 1]
      lastLine = lastLine.concat([offsetX.x, offsetY.y])
      lines.splice(lines.length - 1, 1, lastLine)
      setLines(lines.concat())
    }
  }

      return (
        <Stage
          x={stagePos.x}
          y={stagePos.y}
          width={3840}
          height={2160}
          // draggable
          onDragEnd={e => {
            setStagePos(e.currentTarget.position())
          }}
          onMouseDown={handleMouseDown}
          onMouseUp={handleMouseUp}
          onMouseMove={handleMouseMove}
        >

         {lines.map((line, i) => (
          <Line key={i} points={line} stroke="red" />
        ))}
          </Layer>
        </Stage>
      )
    }

What Im doing wrong? I got just undefined!

A: I found the solution!!!!
export default function RenderMap() {
  const [stagePos, setStagePos] = useState({ x: 0, y: 0 })
  const [lines, setLines] = useState([])
  const [isDrawing, setIsDrawing] = useState(false)

  function handleMouseDown() {
    setIsDrawing(true)
    setLines([...lines, []])
  }

  function handleMouseUp() {
    if (isDrawing) {
      setIsDrawing(false)
    }
  }

  function handleMouseMove({ evt }) {
    if (!isDrawing) {
      return
    }
    const { offsetX, offsetY } = evt

    if (isDrawing) {
      let lastLine = lines[lines.length - 1]
      lastLine = lastLine.concat([offsetX, offsetY])
      lines.splice(lines.length - 1, 1, lastLine)
      setLines(lines.concat())
    }
  }

  return (
    <Stage
      x={stagePos.x}
      y={stagePos.y}
      width={3840}
      height={2160}
      // draggable
      onDragEnd={e => {
        setStagePos(e.currentTarget.position())
      }}
      onMouseDown={handleMouseDown}
      onMouseUp={handleMouseUp}
      onMouseMove={handleMouseMove}
    >
      <Layer>

        {lines.map((line, i) => (
          <Line key={i} points={line} stroke="red" />
        ))}
      </Layer>
    </Stage>
  )
}


text:
Q: qgis errpr :The following layers were not correctly generated

I am a novice, is this what is the problem?

A: Your error message tells you have tried to run an R script in the Processing Toolbox, which requires .rsx scripts.
Please read QGIS processing guide, especially R syntax in Processing part.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reload HTML After Post Request I've been trying to reload a portion of the page after the user created a post.
JavaScript
success: function(result)
{
    $("#postsxd").load(" #postsxd");
    console.log(result);
}

Blade
@foreach(Auth::user()->posts()->latest()->paginate(1) as $userpost)

                user->getFirstMediaUrl('pps') ? $userpost->user->getFirstMediaUrl('pps')  : '/img/ava_10.jpg' }}"
                     width="36" height="36" alt="author">

                    {{ $userpost->author }}
                    (Your latest post)

                        <time class="published" datetime="2004-07-24T18:18">9 hours ago</time>

{!! $userpost->content !!}

@endforeach

I don't know why the page does not reload that element or what I am doing wrong. Thanks in advance for the help.
Also, how can I change a button after the user submits the form or clicks it?

A: Add foreach loop in a div tag and give a unique id to that div tag and use that tag in the javascript file.
Code :
Blade File

    @foreach(Auth::user()->posts()->latest()->paginate(1) as $userpost)

                    user->getFirstMediaUrl('pps') ? $userpost->user->getFirstMediaUrl('pps')  : '/img/ava_10.jpg' }}"
                         width="36" height="36" alt="author">

                        {{ $userpost->author }}
                        (Your latest post)

                            <time class="published" datetime="2004-07-24T18:18">9 hours ago</time>

{!! $userpost->content !!}

    @endforeach

JavaScript | Ajax Responce
success: function(result)
{
    $("#uniqueId").load(" #uniqueId > *");
    console.log(result);
}


text:
Q: Conflicting user defined class name with inbuilt class name - C# I have the following code, where I am using the inbuilt C# Stack class in my own user defined Stack1 class.
Everything works well with this user defined nomenclature. But, as soon as I change all references of my user defined Stack1 class, and call it as a Stack class - the compiler gets confused, and the C# inbuilt Stack classes that I am using inside my user defined Stack class no longer correspond to the inbuilt Systems.Collections.Stack class. But, fall back to the user defined StackHavingPopPushAndMinO1_2.Stack class.
Do you know why this is happening, and is there any way I can keep my user defined Stack class name as Stack and still use the inbuilt Systems.Collections.Stack class inside it?
Please see: I already solved the issue by using the System.Collections.Generic.Stack<int> classes inside my user defined Stack class. But my intention here is that I don't want to change the name of my user defined Stack class - and still use the inbuilt Systems.Collection.Stack class inside it.
Please see: I also created an alias for System.Collections and appended it to the inbuild Stack classes I am using. But I was just wondering if there is some other way I can use my user defined Stack class which has the inbuilt Systems.Collections.Stackclasses in it.
Following is the code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackHavingPopPushAndMinO1_2
{
    class Stack1
    {
        Stack mainStack = new Stack();
        Stack supportingStack = new Stack();

        public void Push(int value)
        {
            mainStack.Push(value);
            if(supportingStack.Count==0 || value <= (int) supportingStack.Peek())
            {
                supportingStack.Push(value);
            }
        }

        public int Pop()
        {
            int value = -1;
            if(mainStack.Count>0)
            {
                value = (int) mainStack.Pop();
                if (value == (int) supportingStack.Peek())
                    supportingStack.Pop();
            }
            return value;
        }

        public int Min()
        {
            if (supportingStack.Count > 0)
                return (int) supportingStack.Peek();
            return -1;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Stack1 stack = new Stack1();
            stack.Push(60);
            stack.Push(10);
            stack.Push(50);
            Console.WriteLine(stack.Min());
            stack.Push(80);
            stack.Push(9);
            stack.Push(11);
            Console.WriteLine(stack.Min());
        }
    }
}

Everything works fine with the user defined class Stack1. But, as soon as I change the name of Stack1 to Stack, the compiler gets confused, and we get errors due to name conflict. Any light on this will be greatly helpful. Why does not the C# Compiler know the difference between the user defined Stack class, and the inbuilt Stack class?

A:
Why does not the C# Compiler know the difference between the user defined Stack class, and the inbuilt Stack class?

How would you expect it to do so? When it encounters a declaration of a variable like this:
Stack stack = null;

... which class should that refer to? I suspect that in some cases you'd want that to refer to StackHavingPopPushAndMinO1_2.Stack, and in other cases you'd want it to refer to System.Collections.Stack. The C# compiler follows very strict name lookup rules to determine the meaning of a name. You can find those rules in the C# specification, and I suspect that you'd be hard-pressed to design better rules.
In particular, looking at your class, you have:
class Stack // After renaming
{
    Stack mainStack = new Stack();
    ...

Presumably, you want the type of mainStack to be System.Collections.Stack, otherwise you'll end up with infinite recursion - but what rules would you expect to determine that?
Your options are:

*

*Avoid the naming collision, which is generally the best approach

*Use aliases to be explicit

*Use fully-qualified names, e.g. System.Collections.Stack stack = null; instead of just the unqualified name


text:
Q: Observing glitches and some problem when using transforms ( rotate and translate ) in css I am a newbie in web development . I have come up with a design , a card , which on hover , rotates and shows the back of the card. I have tried using transitions and transforms (rotate , translate). I observe some glitches when using transforms , especially using rotate. This problem occurred on both chrome and safari.
This is my code :

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: sans-serif;
  display: flex;
  justify-content: center;
  padding: 20px 0;
}

.card {
  width: 300px;
}

.card__content {
  padding: 150px;
  text-align: center;
  position: relative;
  transition: transform 3s;
  background-color: pink;
  transform-style: preserve-3d;
}

.card:hover .card__content {
  transform: rotateY(.5turn);
}

.card__front,
.card__back {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 50px;
  backface-visibility: hidden;
  transform-style: preserve-3d;
}

.card__title {
  font-size: 3rem;
  transform: translateZ(100px);
}

.card__back {
  background-color: teal;
  transform: rotateY(.5turn);
}

CORONA

FEVER

So could anyone help me out by finding errors associated with the above code that causes this problem ?
Thank You


text:
Q: How to historize each version of my object with Doctrine ?   public function executeNew(sfWebRequest $request)
  {
    $this->form = new JobeetJobForm();
  }

  public function executeCreate(sfWebRequest $request)
  {
    $this->forward404Unless($request->isMethod('post'));

    $this->form = new JobeetJobForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }

    protected function processForm(sfWebRequest $request, sfForm $form)
  {
    $form->bind($request->getParameter($form->getName()));
    if ($form->isValid())
    {
      $jobeet_job = $form->save();

      $this->redirect('job/edit?id='.$jobeet_job['id']);
    }
  }

I generated module with doctrine generator. I would like make: if i edit current Job and click Save then instead of save this edit i would like create new object job with new ID and same data as current edited Job. How can i make it? I would like make this same as wikipedia.
EDIT:
i dont know how to open action edit, edit few fields and click Save and instead save this changes i would like create new object. What i must edit in processForm?

A: This is exactly the goal of the versionable behavior of Doctrine.

A: When you need do keep versions with all related objects. You can serialize the object and keep it in database. Look at the JMSerializerBundle at github.


text:
Q: Recently taken camera image won't display on Ionic page I am trying to display two images on a page using Ionic. I am taking one photo via a camera, and I am pulling the other image down from the web. I can successfully store the images as a FILE_URI that is something like the following:
Camera:
file:///var/mobile/Containers/Data/Application/2A696490-1D2B-4A22-B058-8F814AF52D90/tmp/cdv_photo_001.jpg

Web:
file:///var/mobile/Containers/Data/Application/2A696490-1D2B-4A22-B058-8F814AF52D90/Documents/file.png

The problem arises when I try to view the files. When I try to set an img HTMLElement's src in typescript via document["img1"].src = this.cameraImageURI; I get an error on my xcode console that is the following:
ERROR: Unable to send exception to server [object Object]

My page never even loads because of this error. I believe my issue may be with passing the entire string (as shared above) into the img1 src attribute.
I have looked into Ionic's FileOpener class, but I am not sure if that is the way to go.
UPDATE 1: I tried slicing out the file://, but unfortunately, that didn't work. Also, I tried using their function, normalizeURL, which should solve the issue too. The documentation for this is found here. But alas, it makes the string:
http://localhost:8080/var/mobile/Containers/Data/Application/17737D0A-F9C2-4DD9-8A9B-4DA6A094D100/tmp/cdv_photo_001.jpg

which didn't work either.

A: As discussed in the comments above, firstly we figured out that the first problem was linked with WkWebView not supporting URI containing file://.
To remove it, Ionic provide an handy util method which could be use as follow:
import { normalizeURL } from 'ionic-angular';

this.cameraImageURI = normalizeURL(this.cameraImageURI);

Dokumentation could be found at https://ionicframework.com/docs/wkwebview/ see topic "Rewriting file://
Secondly I thought that OP might had a problem with setting the URI result with document. I suggested to access the URI from the page template as following and luckily it worked out ;)
<div *ngIf="cameraImageURI != null">
  <img [src]="cameraImageURI">
</div>

Note: Doing so, the image will be only rendered if the URI isn't empty. Furthermore, cameraImageURI has to be a public variable of the class/view


text:
Q: Select AS to simplify structure of returned array From a select like this:
"SELECT `ScO`.`id` as `ScI`, `ScX`.`type` as `SxT` FROM ... etc

I would like rows to be returned as,
[] => Array
  ['ScI'] => *
  ['SxT'] => *

I am getting,
[] => Array
  ['ScO'] => Array
             ['ScI'] => *
  ['ScX'] => Array
             ['SxT'] => *

I dont need the extra nesting and hope im missing a simple syntax solution. Thankyou.

A: If you run that query in mysql nothing like ScO or ScX is exposed at all. So if you're getting those entities in your app it might be in your row mapper it happens.


text:
Q: Subset data.table by logical column I have a data.table with a logical column. Why the name of the logical column can not be used directly for the i argument? See the example.
dt <- data.table(x = c(T, T, F, T), y = 1:4)

# Works
dt[dt$x]
dt[!dt$x]

# Works
dt[x == T]
dt[x == F]

# Does not work
dt[x]
dt[!x]

A: x is not defined in the global environment. If you try this,
> with(dt, dt[x])
      x y
1: TRUE 1
2: TRUE 2
3: TRUE 4

It would work. Or this:
> attach(dt)
> dt[!x]
       x y
1: FALSE 3

EDIT:
according to the documentation the j parameter takes column name, in fact:
> dt[x]
Error in eval(expr, envir, enclos) : object 'x' not found
> dt[j = x]
[1]  TRUE  TRUE FALSE  TRUE

then, the i parameter takes either numerical or logical expression (like x itself should be), however it seems it (data.table) can't see x as logical without this:
> dt[i = x]
Error in eval(expr, envir, enclos) : object 'x' not found
> dt[i = as.logical(x)]
      x y
1: TRUE 1
2: TRUE 2
3: TRUE 4

A: From ?data.table

Advanced: When i is a single variable name, it is not considered an
  expression of column names and is instead evaluated in calling scope.

So dt[x] will try to evaluate x in the calling scope (in this case the global environment)
You can get around this by using ( or { or force
dt[(x)]
dt[{x}]
dt[force(x)]

A: This should also work and is arguably more natural:
setkey(dt, x)
dt[J(TRUE)]
dt[J(FALSE)]


text:
Q: How can I directly draw an SKPath from SVG string on screen arbitrarily in SkiaSharp? I am building an application which can send and receive skia sharp drawings. The SKPath is serialized into SVG format and sent. The receiving end then must deserialize and draw the SKPath from the SVG string. However, it seems impossible to do this outside the OnCanvasViewPaintSurface event.
I am currently trying to do this in the finger paint example in the Xamarin examples solution. The DrawTestLine method should draw a little freehand line I drew and serialized into SVG. In reality it runs with no exceptions but draws nothing on the screen.
Any help to get this to work is massively appreciated.
See my modifications below:
using System;
using System.Collections.Generic;

using Xamarin.Forms;

using TouchTracking;

using SkiaSharp;
using SkiaSharp.Views.Forms;

namespace SkiaSharpFormsDemos.Paths
{
    public partial class FingerPaintPage : ContentPage
    {
        Dictionary<long, SKPath> inProgressPaths = new Dictionary<long, SKPath>();
        List<SKPath> completedPaths = new List<SKPath>();
        SKBitmap bitmap;

        SKPaint paint = new SKPaint
        {
            Style = SKPaintStyle.Stroke,
            Color = SKColors.Blue,
            StrokeWidth = 10,
            StrokeCap = SKStrokeCap.Round,
            StrokeJoin = SKStrokeJoin.Round
        };

        public FingerPaintPage()
        {
            InitializeComponent();
            DrawTestLine();
        }

        private void DrawTestLine()
        {
            var svgPath = "M851.953 371.006L865.957 438.527L874.922 462.995L880.957 453.997L884.941 441.011L893.965 427.874L895.957 418.233L900.938 415.006L902.93 405.02L898.945 403.998";
            var testPath = SKPath.ParseSvgPathData(svgPath);
            bitmap = new SKBitmap(1920, 1080);// (int)canvasView.CanvasSize.Width, (int)canvasView.CanvasSize.Height);
            var canvas = new SKCanvas(bitmap);
            canvas.Clear();
            canvas.DrawPath(testPath, paint);
            canvasView.InvalidateSurface();
        }

        void OnTouchEffectAction(object sender, TouchActionEventArgs args)
        {
            switch (args.Type)
            {
                case TouchActionType.Pressed:
                    if (!inProgressPaths.ContainsKey(args.Id))
                    {
                        SKPath path = new SKPath();
                        path.MoveTo(ConvertToPixel(args.Location));
                        inProgressPaths.Add(args.Id, path);
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Moved:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        SKPath path = inProgressPaths[args.Id];
                        path.LineTo(ConvertToPixel(args.Location));
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Released:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        completedPaths.Add(inProgressPaths[args.Id]);
                        inProgressPaths.Remove(args.Id);
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Cancelled:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        inProgressPaths.Remove(args.Id);
                        canvasView.InvalidateSurface();
                    }
                    break;
            }
        }

        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            args.Surface.Canvas.DrawBitmap(bitmap, 0, 0);

            SKCanvas canvas = args.Surface.Canvas;
            canvas.Clear();

            foreach (SKPath path in completedPaths)
            {
                canvas.DrawPath(path, paint);
            }

            foreach (SKPath path in inProgressPaths.Values)
            {
                canvas.DrawPath(path, paint);
            }
        }

        SKPoint ConvertToPixel(Point pt)
        {
            return new SKPoint((float)(canvasView.CanvasSize.Width * pt.X / canvasView.Width),
                               (float)(canvasView.CanvasSize.Height * pt.Y / canvasView.Height));
        }
    }
}

A: using System;
using System.Collections.Generic;

using Xamarin.Forms;

using TouchTracking;

using SkiaSharp;
using SkiaSharp.Views.Forms;

namespace SkiaSharpFormsDemos.Paths
{
    public partial class FingerPaintPage : ContentPage
    {
        Dictionary<long, SKPath> inProgressPaths = new Dictionary<long, SKPath>();
        List<SKPath> completedPaths = new List<SKPath>();
        SKBitmap bitmap;

        SKPaint paint = new SKPaint
        {
            Style = SKPaintStyle.Stroke,
            Color = SKColors.Blue,
            StrokeWidth = 10,
            StrokeCap = SKStrokeCap.Round,
            StrokeJoin = SKStrokeJoin.Round
        };

        SKPath testPath = SKPath.ParseSvgPathData("M851.953 371.006L865.957 438.527L874.922 462.995L880.957 453.997L884.941 441.011L893.965 427.874L895.957 418.233L900.938 415.006L902.93 405.02L898.945 403.998");

        public FingerPaintPage()
        {
            InitializeComponent();
            DrawTestLine();
        }

        private void DrawTestLine()
        {
            canvasView.InvalidateSurface();
        }

        void OnTouchEffectAction(object sender, TouchActionEventArgs args)
        {
            switch (args.Type)
            {
                case TouchActionType.Pressed:
                    if (!inProgressPaths.ContainsKey(args.Id))
                    {
                        SKPath path = new SKPath();
                        path.MoveTo(ConvertToPixel(args.Location));
                        inProgressPaths.Add(args.Id, path);
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Moved:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        SKPath path = inProgressPaths[args.Id];
                        path.LineTo(ConvertToPixel(args.Location));
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Released:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        completedPaths.Add(inProgressPaths[args.Id]);
                        inProgressPaths.Remove(args.Id);
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Cancelled:
                    if (inProgressPaths.ContainsKey(args.Id))
                    {
                        inProgressPaths.Remove(args.Id);
                        canvasView.InvalidateSurface();
                    }
                    break;
            }
        }

        void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args)
        {
            bitmap = new SKBitmap((int)canvasView.CanvasSize.Width, (int)canvasView.CanvasSize.Height);
            var canvas = new SKCanvas(bitmap);
            canvas.Clear();
            canvas.DrawPath(testPath, paint);

            args.Surface.Canvas.DrawBitmap(bitmap, 0, 0);

            canvas.Clear();

            foreach (SKPath path in completedPaths)
            {
                canvas.DrawPath(path, paint);
            }

            foreach (SKPath path in inProgressPaths.Values)
            {
                canvas.DrawPath(path, paint);
            }
        }

        SKPoint ConvertToPixel(Point pt)
        {
            return new SKPoint((float)(canvasView.CanvasSize.Width * pt.X / canvasView.Width),
                               (float)(canvasView.CanvasSize.Height * pt.Y / canvasView.Height));
        }
    }
}


text:
Q: Is there any security gained by having a file with 4xx permsion instead of 6xx? If a file can only be read by its owner (400), is this any more secure than that file having read write permissions?
At best wouldn't this just help prevent you making stupid mistakes with your own files, rather than add any actual security? If you own a file, then you can alter its permissions. So if someone malicious gained access to a user, then having a file owned by that user set to 400 wouldn't prevent the attacker changing permissions on the file and writing to it?
Is there any security gained by having a file not writeable by its owner?

A: If your threat model is binary — either the user account is not compromised or it is fully compromised (arbitrary command execution) — there isn't any difference. As you note, the attacker can just chmod u+w the file.
Partial compromise, however, can happen. E.g., if the attacker only gains "write to any file", then he can't write to the 0400 file. This is of questionable benefit in a lot of cases though — "write to any file" can often be elevated to arbitrary command fairly easily (e.g., write to ~/.bashrc).
Further, with write permission on the parent directory, you can still delete (unlink) a mode 0400 file. Meaning an attacker could delete the existing file and put a new one in place using the same name.
The one "security" use that comes to mind is a FTP (etc.) dropbox. You could put a README file in there, mode 0400. If your dropbox parent directory is set to a+rwxt, then everyone can add new files there (and due to +t) only delete files they own. So your README would be protected.
So I think overall it's a prevent accidents feature more than a security feature.

A: Stupid mistakes destroy data. Protecting against stupid mistakes may save your data. Not having the write permission set on files you actually really want to keep is in the same category as not automatically using -f on rm, having rm complain to you if you accidentally try rm -r /, and not running your shell as root all the time. None of them are necessary, if you know what you're doing, but all of them might be useful in one situation or another.
But well, security vulnerabilities start small. User input may be used to decide on a file name to access, and if unsanitized, they may be able to cajole the program to accessing something that isn't meant to be accessed by end users. (Something like the classic ../../../passwd stuff.)
If an important file was kept without write permission, just being able to decide on the file name wouldn't allow writing said file. How much this matters, depends on what other files they might rewrite, though. (And really, better fix those uses of unsanitized inputs.)

A: In a nutshell, no, you are not gaining anything worth your effort. As you rightly mentioned, anyone who managed to read the file can also change its permissions.
There is always a security vs usability balance to take into account, and in this case I struggle to even see a gain, let alone gauge it against the effort of maintaining this solution.


text:
Q: CELERY_ALWAYS_EAGER in unit tests causes DetachedInstanceError I added some celery tasks to my python app, and they work great. I'm trying to fix my test suite for celery as well. I added celery.conf.CELERY_ALWAYS_EAGER = True to my test suite so that it can run with the tasks executed synchronously.
Problem is that random tests (that do not even use the celery task) are showing the error DetachedInstanceError: Parent instance <MyModel at 0x1096ba690> is not bound to a Session; lazy load operation of attribute 'child' cannot proceed.
Removing celery.conf.CELERY_ALWAYS_EAGER = True fixes the problem, but then the celery tasks are sent to the queue but not processed unless I start a worker in the terminal.


text:
Q: what is the difference between exec and dbus-launch? If I start a process, particularly at session start, what is the difference between using exec p and dbus-launch p?

A: dbus-launch is DBus-related. exec is a  shell built-in. See their manpages/help pages:
dbus-launch - Utility to start a message bus from a shell script.
exec - Replace the shell with the given command.

So... they basically do two different things... While both are expected to start program p passed as a parameter, you can read that in the case of dbus-launch, a few other things are done first:

You may specify a program to be run; in this case, dbus-launch will launch a session bus instance, set the appropriate environment variables so the specified program can find the bus, and then execute the specified  program, with the specified arguments.

In this case, a DBus daemon instance is created prior to creating the process, and it should be running a secondary session bus, which is made available to the child process through environment variables.
Also note that in the case of exec, the current shell is replaced by a new program. dbus-launch will not replace the shell, and nor will the program you start alongside the daemon.


text:
Q: Hadoop 2.6.4 MR job quick freeze Hadoop 2.6.4: 1 master + 2 slaves on AWS EC2
master: namenode, secondary namenode, resource manager
slave: datanode, node manager
When running a test MR job (wordcount), it freezes right away:
hduser@ip-172-31-4-108:~$ hadoop jar /usr/local/hadoop/share/hadoop/mapreduce/hadoop-mapreduce-examples-2.6.4.jar wordcount /data/shakespeare /data/out1
16/03/21 10:45:19 INFO client.RMProxy: Connecting to ResourceManager at ip-172-31-4-108/172.31.4.108:8032
16/03/21 10:45:21 INFO input.FileInputFormat: Total input paths to process : 5
16/03/21 10:45:21 INFO mapreduce.JobSubmitter: number of splits:5
16/03/21 10:45:22 INFO mapreduce.JobSubmitter: Submitting tokens for job: job_1458556970596_0001
16/03/21 10:45:22 INFO impl.YarnClientImpl: Submitted application application_1458556970596_0001
16/03/21 10:45:22 INFO mapreduce.Job: The url to track the job: http://ip-172-31-4-108:8088/proxy/application_1458556970596_0001/
16/03/21 10:45:22 INFO mapreduce.Job: Running job: job_1458556970596_0001

When running start-dfs.sh and start-yarn.sh on master, all daemons run succesfully (jps command) on corresponding EC2 instance.
Below Resource Manager log when launching MR job:
2016-03-21 10:45:20,152 INFO org.apache.hadoop.yarn.server.resourcemanager.ClientRMService: Allocated new applicationId: 1
2016-03-21 10:45:22,784 INFO org.apache.hadoop.yarn.server.resourcemanager.ClientRMService: Application with id 1 submitted by user hduser
2016-03-21 10:45:22,785 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl: Storing application with id application_1458556970596_0001
2016-03-21 10:45:22,787 INFO org.apache.hadoop.yarn.server.resourcemanager.RMAuditLogger: USER=hduser   IP=172.31.4.108 OPERATION=Submit Application Request    TARGET=ClientRMService  RESULT=SUCCESS  APPID=application_1458556970596_0001
2016-03-21 10:45:22,788 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl: application_1458556970596_0001 State change from NEW to NEW_SAVING
2016-03-21 10:45:22,805 INFO org.apache.hadoop.yarn.server.resourcemanager.recovery.RMStateStore: Storing info for app: application_1458556970596_0001
2016-03-21 10:45:22,807 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl: application_1458556970596_0001 State change from NEW_SAVING to SUBMITTED
2016-03-21 10:45:22,809 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.ParentQueue: Application added - appId: application_1458556970596_0001 user: hduser leaf-queue of parent: root #applications: 1
2016-03-21 10:45:22,810 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler: Accepted application application_1458556970596_0001 from user: hduser, in queue: default
2016-03-21 10:45:22,825 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.RMAppImpl: application_1458556970596_0001 State change from SUBMITTED to ACCEPTED
2016-03-21 10:45:22,866 INFO org.apache.hadoop.yarn.server.resourcemanager.ApplicationMasterService: Registering app attempt : appattempt_1458556970596_0001_000001
2016-03-21 10:45:22,867 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl: appattempt_1458556970596_0001_000001 State change from NEW to SUBMITTED
2016-03-21 10:45:22,896 WARN org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue: maximum-am-resource-percent is insufficient to start a single application in queue, it is likely set too low. skipping enforcement to allow at least one application to start
2016-03-21 10:45:22,896 WARN org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue: maximum-am-resource-percent is insufficient to start a single application in queue for user, it is likely set too low. skipping enforcement to allow at least one application to start
2016-03-21 10:45:22,897 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue: Application application_1458556970596_0001 from user: hduser activated in queue: default
2016-03-21 10:45:22,898 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue: Application added - appId: application_1458556970596_0001 user: org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.LeafQueue$User@1d51055, leaf-queue: default #user-pending-applications: 0 #user-active-applications: 1 #queue-pending-applications: 0 #queue-active-applications: 1
2016-03-21 10:45:22,898 INFO org.apache.hadoop.yarn.server.resourcemanager.scheduler.capacity.CapacityScheduler: Added Application Attempt appattempt_1458556970596_0001_000001 to scheduler from user hduser in queue default
2016-03-21 10:45:22,900 INFO org.apache.hadoop.yarn.server.resourcemanager.rmapp.attempt.RMAppAttemptImpl: appattempt_1458556970596_0001_000001 State change from SUBMITTED to SCHEDULED

Below NameNode log when launching MR job:
2016-03-21 10:45:03,746 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Rescanning after 30000 milliseconds
2016-03-21 10:45:03,746 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Scanned 0 directive(s) and 0 block(s) in 0 millisecond(s).
2016-03-21 10:45:20,613 INFO org.apache.hadoop.hdfs.server.namenode.FSEditLog: Number of transactions: 2 Total time for transactions(ms): 3 Number of transactions batched in Syncs: 0 Number of syncs: 2 SyncTimes(ms): 7
2016-03-21 10:45:20,760 INFO org.apache.hadoop.hdfs.StateChange: BLOCK* allocateBlock: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.jar. BP-1804768821-172.31.4.108-1458553823105 blk_1073741834_1010{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]}
2016-03-21 10:45:21,290 INFO org.apache.hadoop.hdfs.server.namenode.FSNamesystem: BLOCK* checkFileProgress: blk_1073741834_1010{blockUCState=COMMITTED, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} has not reached minimal replication 1
2016-03-21 10:45:21,292 INFO org.apache.hadoop.hdfs.server.namenode.EditLogFileOutputStream: Nothing to flush
2016-03-21 10:45:21,297 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.13.117:50010 is added to blk_1073741834_1010{blockUCState=COMMITTED, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} size 270356
2016-03-21 10:45:21,297 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.14.198:50010 is added to blk_1073741834_1010 size 270356
2016-03-21 10:45:21,706 INFO org.apache.hadoop.hdfs.StateChange: DIR* completeFile: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.jar is closed by DFSClient_NONMAPREDUCE_-18612056_1
2016-03-21 10:45:21,714 INFO org.apache.hadoop.hdfs.server.blockmanagement.BlockManager: Increasing replication from 2 to 10 for /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.jar
2016-03-21 10:45:21,812 INFO org.apache.hadoop.hdfs.server.blockmanagement.BlockManager: Increasing replication from 2 to 10 for /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.split
2016-03-21 10:45:21,823 INFO org.apache.hadoop.hdfs.StateChange: BLOCK* allocateBlock: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.split. BP-1804768821-172.31.4.108-1458553823105 blk_1073741835_1011{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW], ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW]]}
2016-03-21 10:45:21,849 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.13.117:50010 is added to blk_1073741835_1011{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW], ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW]]} size 0
2016-03-21 10:45:21,853 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.14.198:50010 is added to blk_1073741835_1011{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW], ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW]]} size 0
2016-03-21 10:45:21,855 INFO org.apache.hadoop.hdfs.StateChange: DIR* completeFile: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.split is closed by DFSClient_NONMAPREDUCE_-18612056_1
2016-03-21 10:45:21,865 INFO org.apache.hadoop.hdfs.StateChange: BLOCK* allocateBlock: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.splitmetainfo. BP-1804768821-172.31.4.108-1458553823105 blk_1073741836_1012{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]}
2016-03-21 10:45:21,876 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.14.198:50010 is added to blk_1073741836_1012{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} size 0
2016-03-21 10:45:21,877 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.13.117:50010 is added to blk_1073741836_1012{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} size 0
2016-03-21 10:45:21,880 INFO org.apache.hadoop.hdfs.StateChange: DIR* completeFile: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.splitmetainfo is closed by DFSClient_NONMAPREDUCE_-18612056_1
2016-03-21 10:45:22,277 INFO org.apache.hadoop.hdfs.StateChange: BLOCK* allocateBlock: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.xml. BP-1804768821-172.31.4.108-1458553823105 blk_1073741837_1013{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]}
2016-03-21 10:45:22,327 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.14.198:50010 is added to blk_1073741837_1013{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} size 0
2016-03-21 10:45:22,328 INFO BlockStateChange: BLOCK* addStoredBlock: blockMap updated: 172.31.13.117:50010 is added to blk_1073741837_1013{blockUCState=UNDER_CONSTRUCTION, primaryNodeIndex=-1, replicas=[ReplicaUnderConstruction[[DISK]DS-5c350bcc-f752-43cd-80c1-80f68e2db73e:NORMAL:172.31.13.117:50010|RBW], ReplicaUnderConstruction[[DISK]DS-a1e2988f-2ef7-4005-8129-0ca18c95b2cb:NORMAL:172.31.14.198:50010|RBW]]} size 0
2016-03-21 10:45:22,332 INFO org.apache.hadoop.hdfs.StateChange: DIR* completeFile: /tmp/hadoop-yarn/staging/hduser/.staging/job_1458556970596_0001/job.xml is closed by DFSClient_NONMAPREDUCE_-18612056_1
2016-03-21 10:45:33,746 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Rescanning after 30001 milliseconds
2016-03-21 10:45:33,747 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Scanned 0 directive(s) and 0 block(s) in 0 millisecond(s).
2016-03-21 10:46:03,748 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Rescanning after 30001 milliseconds
2016-03-21 10:46:03,748 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Scanned 0 directive(s) and 0 block(s) in 0 millisecond(s).
2016-03-21 10:46:33,748 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Rescanning after 30001 milliseconds
2016-03-21 10:46:33,749 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Scanned 0 directive(s) and 0 block(s) in 0 millisecond(s).
2016-03-21 10:47:03,749 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Rescanning after 30000 milliseconds
2016-03-21 10:47:03,750 INFO org.apache.hadoop.hdfs.server.blockmanagement.CacheReplicationMonitor: Scanned 0 directive(s) and 0 block(s) in 1 millisecond(s).

Any ideas ? thank you in advance for your support !.
Below *-site.xml files content. Note: I've indeed applied some dimensioning results values to properties, but I still had the EXACT SAME issue with minimal configuration (only mandatory properties).
core-site.xml
<configuration>
    <property><name>fs.defaultFS</name><value>hdfs://ip-172-31-4-108:8020</value></property>
</configuration>

hdfs-site.xml
<configuration>
    <property><name>dfs.replication</name><value>2</value></property>
    <property><name>dfs.namenode.name.dir</name><value>file:///xvda1/dfs/nn</value></property>
    <property><name>dfs.datanode.data.dir</name><value>file:///xvda1/dfs/dn</value></property>
</configuration>

mapred-site.xml
<configuration>
    <property><name>mapreduce.jobhistory.address</name><value>ip-172-31-4-108:10020</value></property>
    <property><name>mapreduce.jobhistory.webapp.address</name><value>ip-172-31-4-108:19888</value></property>
    <property><name>mapreduce.framework.name</name><value>yarn</value></property>
    <property><name>mapreduce.map.memory.mb</name><value>512</value></property>
    <property><name>mapreduce.reduce.memory.mb</name><value>1024</value></property>
    <property><name>mapreduce.map.java.opts</name><value>410</value></property>
    <property><name>mapreduce.reduce.java.opts</name><value>820</value></property>
</configuration>

yarn-site.xml
<configuration>
    <property><name>yarn.nodemanager.aux-services</name><value>mapreduce_shuffle</value></property>
    <property><name>yarn.resourcemanager.hostname</name><value>ip-172-31-4-108</value></property>
    <property><name>yarn.nodemanager.local-dirs</name><value>file:///xvda1/nodemgr/local</value></property>
    <property><name>yarn.nodemanager.log-dirs</name><value>/var/log/hadoop-yarn/containers</value></property>
    <property><name>yarn.nodemanager.remote-app-log-dir</name><value>/var/log/hadoop-yarn/apps</value></property>
    <property><name>yarn.log-aggregation-enable</name><value>true</value></property>
    <property><name>yarn.app.mapreduce.am.resource.mb</name><value>1024</value></property>
    <property><name>yarn.app.mapreduce.am.command-opts</name><value>820</value></property>
    <property><name>yarn.nodemanager.resource.memory-mb</name><value>6291456</value></property>
    <property><name>yarn.scheduler.minimum_allocation-mb</name><value>524288</value></property>
    <property><name>yarn.scheduler.maximum_allocation-mb</name><value>6291456</value></property>
</configuration>


text:
Q: Existe alguma ferramenta para site fluido alguém conhece alguma ferramenta que mostre o tamanho da tela? por exemplo conforme vou diminuindo o tamanho do navegador ela me mostre o tamanho da tela em px tinha uma no github mais acabei perdendo

A: Amigo o próprio DevTools faz isso, basta apertar F12 no Chrome e usar a ferramente de teste de devise clicando nesse icone ou apertando ctrl+shift+m

Além disso o Chrome tb tem uma serie de extensões para testar a responsividade direto no browser
https://chrome.google.com/webstore/search/responsive?hl=pt-BR
Eu uso essa https://chrome.google.com/webstore/detail/mobileresponsive-web-desi/elmekokodcohlommfikpmojheggnbelo?hl=pt-BR


text:
Q: Async ComboBox Filtration I am new to asynchronous methods and struggling with such a case (I made a simple example of my problem):
Let's say I've got a ComboBox, which Items are binded with a ***BindableCollection NameList *** which items are some names.
            <ComboBox
                x:Name="SubbranchComboBox"
                Margin="20 0 0 0"
                Width="100"
                Height="20"
                IsEnabled="True"
                IsEditable="True"
                IsTextSearchEnabled="False"
                InputScope="Xml"
                ItemsSource="{Binding NameList}" KeyUp="ComboBox_KeyUp">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}" />
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>

The ComboBox_KeyUp looks like this:
        private void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        var combobox = (ComboBox)sender;
        var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
        if (ctb == null) return;
        if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
            return;
        var caretPos = ctb.CaretIndex;
        var searchedText = combobox.Text.ToLower();
        combobox.SelectedIndex = -1;
        combobox.IsDropDownOpen = true;

        CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
        itemsViewOriginal.Filter = ((o) =>
        {
            if (String.IsNullOrEmpty(searchedText))
            {
                return true;
            }
            else
            {
                if (((string)o).ToLower().Contains(searchedText.ToLower()))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        });
        itemsViewOriginal.Refresh();
        ctb.CaretIndex = caretPos;
    }

and serves as search function for a typed phrase in the combobox.
The Problem is, I'd like the filtration to be done asynchronously, but whenever I try to do it I get an error: The calling thread cannot access this object because a different thread owns it
Please give me some advice, how it should be done.
All the example code:
    public partial class MainWindow : Window
{
    public BindableCollection<String> NameList { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        NameList = new BindableCollection<String>
            {
                "Tony",
                "Jerry",
                "George",
                "Harry",
                "Snape",
                "Sirius",
                "Dan",
                "Michael",
                "Mike",
                "Sebastian",
                "Simon",
                "Johny"
            };
    }

    private void ComboBox_KeyUp(object sender, KeyEventArgs e)
    {
        var combobox = (ComboBox)sender;
        var ctb = combobox.Template.FindName("PART_EditableTextBox", combobox) as TextBox;
        if (ctb == null) return;
        if (Keyboard.Modifiers.HasFlag(ModifierKeys.Shift) || Keyboard.Modifiers.HasFlag(ModifierKeys.Control) || Keyboard.Modifiers.HasFlag(ModifierKeys.Alt))
            return;
        var caretPos = ctb.CaretIndex;
        var searchedText = combobox.Text.ToLower();
        combobox.SelectedIndex = -1;
        combobox.IsDropDownOpen = true;

        CollectionView itemsViewOriginal = (CollectionView)CollectionViewSource.GetDefaultView(combobox.Items);
        itemsViewOriginal.Filter = ((o) =>
        {
            if (String.IsNullOrEmpty(searchedText))
            {
                return true;
            }
            else
            {
                if (((string)o).ToLower().Contains(searchedText.ToLower()))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        });
        itemsViewOriginal.Refresh();
        ctb.CaretIndex = caretPos;
    }
}

A:
The Problem is, I'd like the filtration to be done asynchronously, but whenever I try to do it I get an error: The calling thread cannot access this object because a different thread owns it

If you want to update the UI from a background thread, you should run the code in Application's dispatcher
Application.Current.Dispatcher.Invoke(() => /* modify combobox here */);


text:
Q: How to create enum object from its type and name of the value? I have a type (System.Type) of an enum and a string containing enumeration value to set.
E.g. given:
enum MyEnum { A, B, C };

I have typeof(MyEnum) and "B".
How do I create MyEnum object set to MyEnum.B?

A: I assume you don't have access to MyEnum, only to typeof(MyEnum):
void foo(Type t)
{
   Object o = Enum.Parse(t, "B");
}

A: MyEnum enumValue = (MyEnum)Enum.Parse(typeof(MyEnum), "B");

You also have a case-insensitive overload.

A: You can do this with generics. I created a Utility class to wrap this:
public static class Utils {
    public static T ParseEnum<T>(string value) {
        return (T)Enum.Parse(typeof(T), value, true);
    }

Then invoked like:
string s = "B";
MyEnum enumValue = Utils.ParseEnum<MyEnum>(s);


text:
Q: How to get a logic app to stop running after a successful run each day I have a logic app that I want to run once a line item appears in a table each day. once that line item appear, i don't want the logic app to run anymore that day.  Can't quite think of how to accomplish this.

A: Apart from using the related triggers you can use Terminate action to stop the flow.
After using Get entities (V2) I'm trying to Parse the result to get the timestamp of that particular entity to check if the table has an added row or not for that day

After parsing below is the condition that I'm using
{
"contains": [
"@formatDateTime(body('Parse_JSON')?[0]?['Timestamp'],'dd-MM-yyyy')",
"@formatDateTime(utcNow(),'dd-MM-yyyy')"]
}

Below is the complete flow of my Logic App

RESULTS:

To reproduce the same in your Logic App you can use the below code view
{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "Condition": {
                "actions": {
                    "Terminate": {
                        "inputs": {
                            "runStatus": "Succeeded"
                        },
                        "runAfter": {},
                        "type": "Terminate"
                    }
                },
                "else": {
                    "actions": {
                        "Delay": {
                            "inputs": {
                                "interval": {
                                    "count": 2,
                                    "unit": "Hour"
                                }
                            },
                            "runAfter": {},
                            "type": "wait"
                        },
                        "HTTP": {
                            "inputs": {
                                "method": "POST",
                                "uri": "<URI>"
                            },
                            "runAfter": {
                                "Delay": [
                                    "Succeeded"
                                ]
                            },
                            "type": "Http"
                        }
                    }
                },
                "expression": {
                    "and": [
                        {
                            "contains": [
                                "@formatDateTime(body('Parse_JSON')?[0]?['Timestamp'],'dd-MM-yyyy')",
                                "@formatDateTime(utcNow(),'dd-MM-yyyy')"
                            ]
                        }
                    ]
                },
                "runAfter": {
                    "Parse_JSON": [
                        "Succeeded"
                    ]
                },
                "type": "If"
            },
            "Get_entities_(V2)": {
                "inputs": {
                    "host": {
                        "connection": {
                            "name": "@parameters('$connections')['azuretables']['connectionId']"
                        }
                    },
                    "method": "get",
                    "path": "/v2/storageAccounts/@{encodeURIComponent(encodeURIComponent('AccountNameFromSettings'))}/tables/@{encodeURIComponent('<TableName>')}/entities"
                },
                "runAfter": {},
                "type": "ApiConnection"
            },
            "Parse_JSON": {
                "inputs": {
                    "content": "@body('Get_entities_(V2)')?['value']",
                    "schema": {
                        "items": {
                            "properties": {
                                "FirstName": {
                                    "type": "string"
                                },
                                "LastName": {
                                    "type": "string"
                                },
                                "PartitionKey": {
                                    "type": "string"
                                },
                                "RowKey": {
                                    "type": "string"
                                },
                                "Timestamp": {
                                    "type": "string"
                                },
                                "odata.etag": {
                                    "type": "string"
                                }
                            },
                            "required": [
                                "odata.etag",
                                "PartitionKey",
                                "RowKey",
                                "Timestamp",
                                "FirstName",
                                "LastName"
                            ],
                            "type": "object"
                        },
                        "type": "array"
                    }
                },
                "runAfter": {
                    "Get_entities_(V2)": [
                        "Succeeded"
                    ]
                },
                "type": "ParseJson"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {
            "$connections": {
                "defaultValue": {},
                "type": "Object"
            }
        },
        "triggers": {
            "manual": {
                "inputs": {
                    "schema": {}
                },
                "kind": "Http",
                "type": "Request"
            }
        }
    },
    "parameters": {
        "$connections": {
            "value": {
                "azuretables": {
                    "connectionId": "/subscriptions/<SUB_ID>/resourceGroups/<RG>/providers/Microsoft.Web/connections/azuretables",
                    "connectionName": "azuretables",
                    "id": "/subscriptions/<SUB_ID>/providers/Microsoft.Web/locations/centralus/managedApis/azuretables"
                }
            }
        }
    }
}

Alternatively, you can use Recurrence trigger to trigger it in regular intervals with the same logic.


text:
Q: Laying out JLabels and JTextFields When I run this program, both text fields appear right next to each other; if possible, how can I make it to where the password field is under the username field?
public static void main(String[] args) {
    JTextField username = new JTextField(10);
    JPasswordField password = new JPasswordField(10);

    final JPanel login = new JPanel();

    login.add(new JLabel("Username:"));
    login.add(username);
    login.add(Box.createHorizontalStrut(50));
    login.add(new JLabel("Password:"));
    login.add(password);

    int result = JOptionPane.showConfirmDialog(null, login,
       "Login Form", JOptionPane.OK_CANCEL_OPTION);

    if (result == JOptionPane.OK_OPTION) {
        System.out.println("Username: " + username.getText());
        System.out.println("Password: " + password.getText());
    }
}

A: Myself, I'd use a GridBagLayout since with this layout, you can specify what position in a grid you'd like to place your components, how they fill the grid cell, how they expand when the GUI expands, etc. How to use it is explained well in the GridBagLayout tutorial and in other tutorials and examples on this site.
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;

import javax.swing.*;

public class SimpleLogin {
   public static void main(String[] args) {
      SimpleLoginPanel simpleLoginPanel = new SimpleLoginPanel();
      int result = JOptionPane.showConfirmDialog(null, simpleLoginPanel,
            "Login Form", JOptionPane.OK_CANCEL_OPTION);

      if (result == JOptionPane.OK_OPTION) {
         System.out.println("Username: " + simpleLoginPanel.getUserName());

         // the code below is dangerous as it translates a char[] to a String
         // making the password potentially discoverable by outside programs.
         System.out.println("Password: " + new String(simpleLoginPanel.getPassword()));

      }
   }
}

// create a JPanel to hold our components
@SuppressWarnings("serial")
class SimpleLoginPanel extends JPanel {
   // insets provide blank space around the gridbag layout cells
   private static final Insets INSETS = new Insets(5, 5, 5, 5);
   private JTextField username = new JTextField(10);
   private JPasswordField password = new JPasswordField(10);

   public SimpleLoginPanel() {
      setLayout(new GridBagLayout());
      add(new JLabel("User Name:"), createGbc(0, 0));
      add(username, createGbc(1, 0));
      add(new JLabel("Password:"), createGbc(0, 1));
      add(password, createGbc(1, 1));
   }

   // so that outside classes can extract the data in the password field
   public char[] getPassword() {
      return password.getPassword();
   }

   // so that outside classes can extract the username's text
   public String getUserName() {
      return username.getText();
   }

   // the main method of this example, one that creates the GridBagConstraints
   // depending on the x, y position of the component.
   // this one is written for a two column grid.
   private GridBagConstraints createGbc(int x, int y) {
      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = x;
      gbc.gridy = y;
      gbc.gridwidth = 1;
      gbc.gridheight = 1;
      gbc.insets = INSETS;
      if (x == 0) {
         // if the left column, then anchor it to the left
         // and fill completely since it's a JLabel
         gbc.fill = GridBagConstraints.BOTH;
         gbc.anchor = GridBagConstraints.LINE_START;
      } else {
         // if the right column, anchor to the right and
         // only fill horizontally since its a JTextField.
         gbc.fill = GridBagConstraints.HORIZONTAL;
         gbc.anchor = GridBagConstraints.LINE_END;
      }
      return gbc;
   }

}

A: You can try to use BoxLayout:
login.setLayout(new BoxLayout(login, BoxLayout.PAGE_AXIS));

however it also set a Labels in a row with text fields.


text:
Q: Programmatically call webmethods in C# I'm trying to write a function that can call a webmethod from a webserive given the method's name and URL of the webservice. I've found some code on a blog that does this just fine except for one detail. It requires that the request XML be provided as well. The goal here is to get the request XML template from the webservice itself. I'm sure this is possible somehow because I can see both the request and response XML templates if I access a webservice's URL in my browser.
This is the code which calls the webmethod programmatically:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";
Stream stm = req.GetRequestStream();
doc.Save(stm);
stm.Close();
WebResponse resp = req.GetResponse();
stm = resp.GetResponseStream();
StreamReader r = new StreamReader(stm);
Console.WriteLine(r.ReadToEnd());

A: Following on from the comments above. If you have a WSDL file that describes your service you use this as the information required to communicate with your web service.
Using a proxy class to communicate with your service proxy is an easy way to abstract yourself from the underlying plumbing of HTTP and XML.
There are ways of doing this at run-time - essentially generating the code that Visual Studio generates when you add a web service reference to your project.
I've used a solution that was based on: this newsgroup question, but there are also other examples out there.

A: FYI, your code is missing using blocks. It should be more like this:
XmlDocument doc = new XmlDocument();
//this is the problem. I need to get this automatically
doc.Load("../../request.xml");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost/dummyws/dummyws.asmx?op=HelloWorld");
req.ContentType = "text/xml;charset=\"utf-8\"";
req.Accept = "text/xml";
req.Method = "POST";

using (Stream reqstm = req.GetRequestStream())
{
    doc.Save(reqstm);
}

using (WebResponse resp = req.GetResponse())
{
    using (Stream respstm = resp.GetResponseStream())
    {
        using (StreamReader r = new StreamReader(respstm))
        {
            Console.WriteLine(r.ReadToEnd());
        }
    }
}


text:
Q: How do I echo dynamic session variables in PHP? Order Page: On this page, customers can choose to add business card orders with different foreign languages and other options.
When the user clicks on a button to add an additional card, javaScript adds a series of form fields and in order to give them unique name attributes, I am simply adding a counter variable at the end of the name for each group of fields, so I can save them as a unique group of session variables where each form field has different names but the same counter number at the end so I know they belong together.

These are the session variables I am
saving when the user submits the form
to go to the next page:

*

*$_SESSION[quantity1] = 500

*$_SESSION[language1] = Korean

*$_SESSION[quantity2] = 250

*$_SESSION[language2] = Chinese

Checkout Page: On this page, I want it to echo out the information for each different card ordered.
I am trying to echo out all the session variables with the same number at the end of the session variable on the checkout page. So far I'm using a foreach loop to echo out all the session variables, but I am trying to only echo out the ones with a '1' at the end of the names, or a '2' at the end of the names, etc, and group them together.
So ideally, I would like something like this:

Order #1,
Quantity: 500,
Language on Card: Korean
Order #2,
Quantity: 250,
Language on Card: Chinese

How can I echo and group these dynamic session variables on the checkout page?

A: Why not store in the session in a manner like this?
$_SESSION[orders] => array(
  [0]=>array(
     'quantity'=>1,
     'language'=>'Korean'
   ),
  [1]=>array(
    'quantity'=>2,
    'language'=>'Chinese'
   ),
)

Then your iteration on checkout page will be simple

A: Restructure your session when saving to it instead:

*

*$_SESSION[order][1][quantity] = 500

*$_SESSION[order][1][language] = Korean

*$_SESSION[order][2][quantity] = 250

*$_SESSION[order][2][language] = Chinese

That way you can use foreach() on order to get it all cleanly.

A: Grouping the fields is relatively easy. Just loop through them all, pull off the number at the end and groups them in another array.
$vars = array();
foreach ($_SESSION as $k => $v) {
  if (preg_match('!\d+$!', $k, $matches)) {
    $number = $matches[0];
    if (array_key_exists($number, $vars)) {
      $vars[$number][$k] = $v;
    } else {
      $vars[$number] = array($k => $v);
    }
  }
}
print_r($vars);

To display them loop through $vars and do what you need to do. You may need to sort $vars if you want them in a particular order. You may need to sort the sub-arrays to put the fields in a particular order.


text:
Q: How to sort a file on multiple positions using Windows command line? I have an index text file, and I'm having trouble sorting it. I've been looking online for an answer, but Google hasn't pulled up anything with multi-positional searches.
Trying to do so with Unix (which would be easy), would be done as
sort inputfile -k1.1 -k3.3 -o outputfile

should accomplish the task, but trying to do so gives me Cygwin errors of already specifying the input twice (UNIX sorts are out!).
I need to sort this index file, either with Windows console applications or Perl on both positions.
Here is the input data:

1925699|0003352_0050003895.pdf|00500003895|0003352
  1682628|0003352_0050003894.pdf|00500003894|0003352
1682628|0003352_0050003893.pdf|00500003893|0003352

The desired output is:

1682628|0003352_0050003893.pdf|00500003893|0003352
1682628|0003352_0050003894.pdf|00500003894|0003352
1925699|0003352_0050003895.pdf|00500003895|0003352

I'm currently trying to use:
sort/+1,7 /+32,11 < inputfile > outputfile

But I've failed to get this to be successful. (It only sorts the first parameter.) Again Unix is out of the question, and I can do it in Perl, but can this be done in Windows command line?

A: @ECHO Off
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "destdir=U:\destdir"
SET "filename1=%sourcedir%\q45575219.txt"
SET "outfile=%destdir%\outfile.txt"
SET "tempfile=%destdir%\tempfile.txt"
(
FOR /f "usebackqdelims=" %%a IN ("%filename1%") DO (
 FOR /f "tokens=1,3delims=|" %%s IN ("%%a") DO (
  ECHO(%%s%%t^|%%a
 )
)
)>"%tempfile%"
(
FOR /f "tokens=1*delims=|" %%a IN (' sort "%tempfile%" ' ) DO ECHO(%%b
)>"%outfile%"

DEL "%tempfile%"

GOTO :EOF

You would need to change the settings of sourcedir and destdir to suit your circumstances.
I used a file named q45575219.txt containing your data for my testing.
Produces the file defined as %outfile%
Uses a temporary file defined as %tempfile%
Read the source file, assigning each line to %%a. Analyse %%a using pipe as a delimiter and select the first and third tokens. Prefix the first and third tokens to the entire line, separated by a pipe and echo into a temporary file.
sort the temporary file, tokenise again on pipe, selecting the first token (before the first pipe) and the rest of the line; output only the rest to the destination file.


text:
Q: Code running on Google Colab notebook not showing output on its Github copy I am using Pandas to read a CSV file. It is running normally on Google Colab notebook, but after I saved its copy on my Github repository, the code's output is not showing.
Google Colab Code running properly
The same code's output not showing on Github
Sorry for not uploading images directly. Tried twice and failed ._.


text:
Q: convert react class to react hooks useState? Can someone help me convert this to react hooks I believe  it would be react useState()
https://github.com/react-grid-layout/react-grid-layout/blob/master/test/examples/7-localstorage.jsx
import React from "react";
import RGL, { WidthProvider } from "react-grid-layout";

const ReactGridLayout = WidthProvider(RGL);
const originalLayout = getFromLS("layout") || [];
/**
 * This layout demonstrates how to sync to localstorage.
 */
 export default class LocalStorageLayout extends React.PureComponent {
 static defaultProps = {
 className: "layout",
 cols: 12,
 rowHeight: 30,
 onLayoutChange: function() {}
};

  constructor(props) {
    super(props);

    this.state = {
      layout: JSON.parse(JSON.stringify(originalLayout))
    };

    this.onLayoutChange = this.onLayoutChange.bind(this);
    this.resetLayout = this.resetLayout.bind(this);
  }

  resetLayout() {
    this.setState({
      layout: []
    });
  }

  onLayoutChange(layout) {
    /*eslint no-console: 0*/
    saveToLS("layout", layout);
    this.setState({ layout });
    this.props.onLayoutChange(layout); // updates status display
  }

  render() {
    return (

        <button onClick={this.resetLayout}>Reset Layout</button>
        <ReactGridLayout
          {...this.props}
          layout={this.state.layout}
          onLayoutChange={this.onLayoutChange}
        >

            5

        </ReactGridLayout>

    );
   }
}

function getFromLS(key) {
  let ls = {};
   if (global.localStorage) {
    try {
      ls = JSON.parse(global.localStorage.getItem("rgl-7")) || {};
    } catch (e) {
      /*Ignore*/
    }
  }
  return ls[key];
 }

 function saveToLS(key, value) {
  if (global.localStorage) {
   global.localStorage.setItem(
    "rgl-7",
      JSON.stringify({
      [key]: value
    })
  );
 }
}

 if (process.env.STATIC_EXAMPLES === true) {
 import("../test-hook.jsx").then(fn => fn.default(LocalStorageLayout));
}

trying my best to understand react classes since I only know react hooks so any patince help would be so amazing and helpful please and thank you

A: React classes are simple if you understand the lifecycle of a component.
A component is instantiated, then mounted (associated with DOM) & then it renders.
After every update (state or props) it's re-rendered.
Constructor
The instantiation of a component or any JS class happens in the constructor.  It is run only once.
Since class components inherit from React.Component, they pass the props to React.Component by calling super(props). This initializes the props field.
super calls should be the 1st line in a constructor.
You cannot access the following in the constructor: window, document, fetch, localStorage, sessionStorage.
render
The render method returns the rendered Element/Fragment. It corresponds to the returned part of a function component. It runs every time the component is rendered.
Event listener binding
The hardest part of classes is the event method binding.
The implicit this object, is necessary to access state, props & other component methods. However, inside an event listener method*. it refers to the event target.  Hence the bind calls. Nevertheless, this problem, can be bypassed by using arrow methods as the arrow functions do not have their own this (ie. this does not refer to event target).
Function components don't have this problem, as they don't need this.
State
The state is initialized in the constructor.
Unlike function components, classes treat the state as a single object.
Instead of,
let [x, setX] = useState(0); let [y, setY] = useState(1);

In classes it's:
this.state = {x:0, y:1};

And to update state, we use the setState method,
this.setState({x: 3}); // updates only x, & y is unchanged: setX(3)
this.setState({x: 3, y: 4}); // updates both x & y: setX(3); setY(4)
this.setState((state)=>({ y: state.y - 1)) // updates y using previous value: setY(y=>y-1)

An advantage of classes is that we can update a state property using another state property's previous value.
this.setState((state)=>({x: (y%2)? 100: 50})); // updates x using y's value

Also, the state can be updated with respect to props:
this.setState((state,props)=>({x: state.x + props.dx}));

In addition, setState has an optional 2nd callback argument.  This callback is run immediately after the state update.
this.setState(state=>({x: state.x+1}), ()=> {
    // called after x is updated
    sessionStorage.setItem('x', this.state.x);
});

// function version
setX(x=>x+1);

useEffect(()=> {
    localStorage.setItem('x', x);
}, [x]); // runs every time x is updated

Mounting
After mounting, componentDidMount() is called. Now, component can access the window & document objects.
Here here, you can

*

*Call setInterval/setTimeout

*Update state with API calls (fetch) or storage (localStorage & sessionStorage)

It's equivalent to useEffect(()=> {}, [])
Unmounting
Before unmounting componentWillUnmount() is called. Typically, clearTimeout/clearInterval are called here to clean up the component.
It's equivalent to the returned method of useEffect.
useEffect(()=>{
    //....
    return ()=> {
        // componentWillUnmount code
    };
}, [])


text:
Q: unhandled js exception: application main has not been registered expo TestFlight
I have a ios app develop by react native expo. now that's on the
  testing environment.I already installed working successfully some
  iPhone without any issue.
But my iphone x i installed the app without any error then i click the
  app end up this blow error what is the reason

A: I have the same issue with expo both on Testflight and production APP as well. It happens when the app is killed and re-open.

A: I also have the same issue with my application in production (Apple Store), but it doesn't happen on every build. I use ejected Expo.


text:
Q: How to avoid getting older results in AWS cloud trail API call We are using AWS Cloud Trail to retrieve data (cloud trail events). We have used the gem 'aws-sdk-cloudtrail' (version 1.0). As per Cloud Trail we are able to retrieve maximum 50 results (latest once). To fetch the previous (older once ) results we use 'next-token' received in the previous response. We perform this until we get an empty 'next-token'. When we receive an empty token it means all the cloud trail data has been retrieved.
For example:
Suppose Cloud Trail has 100 events logged in:
In the first api call we received the latest 50 results along with the token to retrieve next 50 (older 50).
In the second api call we receive the remaining 50 results (older results) along with next token as nil. It means there are no more results to be fetched.
In our case we are saving all the results received from the trail in our local database.We repeat this periodically.
When doing it for the second time (repeating above explained process) we again receive few newer and few older results. We again repeat the API call until we get 'next-token' as nil. This results in receiving redundant data which was already stored in the database when the first cycle executed.
Is there any way to get only the newly logged cloud trail events second cycle on-wards.

A: Like @Vorsprung said you can use the max event date time from your local database.
Here is the detailed solution for your Use case/Problem:
1. Query to your local database to check that cloudtrail data is present in the local database.

    IF yes
        // It means you have stored some data from cloudtrail before.
        // And now you are going to do request to cloudtrail for new trail events.
        // Note - At a time of the first request you don't have a token (i.e. next-token)

        GOTO Step 3

    ELSE
        // It means you have not stored any data from cloudtrail before.
        // And now you are going to do the first request to cloudtrail.
        // Note - At a time of the first request you don't have a token (i.e. next-token)

        GOTO Step 2

2.  LOOP true

        token = nil

        IF token
            // Send request to cloudtrail to get next bactch of latest cloudtrail events, now pass token(i.e. next-token) as parameter.
            // Which will return the maximum latest 50 trail events.
            // It will also return next-token if more cloudtrail events are remaining.

            IF next-token
              token = next-token
            ELSE
                BREAK LOOP;
            END

        ELSE
            // Send request to cloudtrail to get the latest cloudtrail events.
            // Which will return the maximum latest 50 trail events.
            // It will also return next-token if more cloudtrail events are remaining.

            IF next-token
              token = next-token
            ELSE
                BREAK LOOP;
            END
        END
    END

3.  LOOP true

        token = nil
        start_date_time = max_trail_event_date_time_form_local_db

        IF token
            // Send request to cloudtrail to get next bactch of latest cloudtrail events, now pass token and start_date_time(i.e. next-token and max_event_date_time_form_local_db) as parameters.
            // Which will return the maximum latest 50 events which are logged after start_date_time.
            // It will also return next-token if more cloudtrail events are remaining.

            IF next-token
              token = next-token
            ELSE
                BREAK LOOP;
            END

        ELSE
            // Send request to cloudtrail to get the latest cloudtrail events, now pass start_date_time(i.e. max_trail_event_date_time_form_local_db) as parameter.
            // Which will return the maximum latest 50 events which are logged after start_date_time.
            // It will also return next-token if more cloudtrail events are remaining.

            IF next-token
              token = next-token
            ELSE
                BREAK LOOP;
            END
        END
    END

Hope it will be helpful.

A: Select max date from your local database and then use that as the start date for the cloudtrail events

A: You save the "NextToken" in your local database and pass it when you call the API next time. Here is an example.
import boto3

cloudtrail = boto3.client('cloudtrail')
paginator = cloudtrail.get_paginator('lookup_events')

StartingToken = None

page_iterator = paginator.paginate(
    LookupAttributes=[{'AttributeKey':'EventName','AttributeValue': 'RunInstances'}],
    PaginationConfig={'PageSize':10, 'StartingToken':StartingToken })
for page in page_iterator:
    for event in page["Events"]:
        print(event["EventName"],event["EventTime"])
    try:
        token_file = open("token","w")
        token_file.write(page["NextToken"])
        StartingToken = page["NextToken"]
    except KeyError:
        exit()


text:
Q: Setup Mysql Foreign Data Wrapper in Postgresql Could somebody help me understand how I would go about setting up postgresql's mysql_fdw?  I'm looking at https://github.com/EnterpriseDB/mysql_fdw, and I not sure what the first step is.

A: You linked to the ODBC foreign data wrapper odbc_fdw. You can use it for MySQL, but if you just want MySQL you should use mysql_fdw instead. That way you don't have to mess with ODBC.
Handily, the README for mysql_fdw contains detailed instructions for installation and configuration, so you should be fine setting it up; I won't duplicate those instructions here.

A: I was able to do it the following way.
Installing the package:
sudo apt-get install postgresql-9.5-mysql-fdw

Adds the extension in the Database:
CREATE EXTENSION mysql_fdw;

Add the mysql server to postgresql:
CREATE SERVER mysql_server FOREIGN DATA WRAPPER mysql_fdw OPTIONS (host 'localhost', port '3306');

Create a user to access the database:
CREATE USER MAPPING FOR postgres SERVER mysql_server OPTIONS (username 'root', password 'passwordToConnect');

Import a Schema table from another server
IMPORT FOREIGN SCHEMA mySchema LIMIT TO (tableName) FROM SERVER mysql_server INTO public;

Imports all Schema tables from another server
IMPORT FOREIGN SCHEMA mySchema FROM SERVER mysql_server INTO public;

I hope I have helped.


text:
Q: stickyHeader on Primefaces datatable displays duplicate header in layoutUnit When I use stickyHeader on a datatable inside of a layoutUnit the headers are displayed twice, with the second header slightly offset vertically and horizontally. When I use the same table not in a layoutUnit it displays correctly. When I scroll down and the header sticks to the top it displays correctly. I've tried examining the generated html and css but am unable to fix it.
Using Primefaces 6.1.
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui">

<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<h:outputStylesheet library="css" name="primefaces.css"/>
</h:head>

<p:layout id="lo1">
<p:layoutUnit id="lu1" position="center">
    <p:dataTable value="#{simpleController.simpleObjects}" var="simpleObject" stickyHeader="true">
        <p:column headerText="attr1">
            <p:outputLabel value="#{simpleObject.attr1}"/>
        </p:column>
        <p:column headerText="attr2">
            <p:outputLabel value="#{simpleObject.attr2}"/>
        </p:column>
        <p:column headerText="attr3">
            <p:outputLabel value="#{simpleObject.attr3}"/>
        </p:column>
    </p:dataTable>
</p:layoutUnit>

</p:layout>

</html>

And this is the same table but not in a layoutUnit
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:p="http://primefaces.org/ui">

<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<h:outputStylesheet library="css" name="primefaces.css"/>
</h:head>

<p:dataTable value="#{simpleController.simpleObjects}" var="simpleObject" stickyHeader="true">
<p:column headerText="attr1">
    <p:outputLabel value="#{simpleObject.attr1}"/>
</p:column>
<p:column headerText="attr2">
    <p:outputLabel value="#{simpleObject.attr2}"/>
</p:column>
<p:column headerText="attr3">
    <p:outputLabel value="#{simpleObject.attr3}"/>
</p:column>
</p:dataTable>
</html>


text:
Q: error when I trying to make my C++ project using CPR and TorchScript Library I am trying to use CPR to get Post Request from an API but when I make my project using Cmake, it always error. Let's have a look at my CMakeList.txt, code and error.
Any ideas are very good to me. Thank in advance my bros.
CMakeList.txt
cmake_minimum_required(VERSION 3.15)
project(Preprocessing)

add_subdirectory(cpr)

add_executable(Preprocessing main.cpp)

set(CMAKE_PREFIX_PATH "/home/bao/CLionProjects/Preprocessing/libtorch/share/cmake/Torch")
find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")

target_link_libraries(Preprocessing ${CPR_LIBRARIES} ${TORCH_LIBRARIES})
include_directories(${CPR_INCLUDE_DIRS})

set_property(TARGET Preprocessing PROPERTY CXX_STANDARD 11)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS} ${CPR_CXX_FLAGS}")

set(CMAKE_CXX_STANDARD 11)

my code:
void query_split_text_service (std::string s){
    json j;
    j["sentence"] = s;

    std::cout<< j << std::endl;

    auto r = cpr::Post(cpr::Url{"http://127.0.0.1:8880/nlp/tone"},
                        cpr::Body{j.dump()}
    );
    std::cout << r.text << std::endl;
}

and error:
[ 78%] Linking CXX executable Preprocessing
CMakeFiles/Preprocessing.dir/main.cpp.o: In function `void cpr::priv::set_option<std::string>(cpr::Session&, std::string&&)':
main.cpp:(.text._ZN3cpr4priv10set_optionISsEEvRNS_7SessionEOT_[_ZN3cpr4priv10set_optionISsEEvRNS_7SessionEOT_]+0x2a): undefined reference to `cpr::Session::SetOption(std::string const&)'
collect2: error: ld returned 1 exit status
CMakeFiles/Preprocessing.dir/build.make:91: recipe for target 'Preprocessing' failed
make[2]: *** [Preprocessing] Error 1
CMakeFiles/Makefile2:346: recipe for target 'CMakeFiles/Preprocessing.dir/all' failed
make[1]: *** [CMakeFiles/Preprocessing.dir/all] Error 2
Makefile:129: recipe for target 'all' failed
make: *** [all] Error 2

but If comment some lines, the miracle that I can make my project and run it.
void query_split_text_service (std::string s){
    json j;
    j["sentence"] = s;

    std::cout<< j << std::endl;

//    auto r = cpr::Post(cpr::Url{"http://127.0.0.1:8880/nlp/tone"},
//                        cpr::Body{j.dump()}
//    );
//    std::cout << r.text << std::endl;
}


text:
Q: Regex in Custom Configuration Partially Working I have a ConfigurationProperty that is annotated with a RegexStringValidator that looks like this:
public class Test : ConfigurationElement
{
    [ConfigurationProperty("field", IsKey = true)]
    [RegexStringValidator("issuer|subject")]
    public string Field
    {
        get { return (string)base["field"]; }
    }
}

It always throws an exception saying that the RegexStringValidator failed.  I can achieve success if I change the regex value to either of these:

*

*"[a-zA-Z]*"

*".*"
The actual "field" value being validated is the simple string "issuer".  I can see no reason why there should be a problem.  In fact, the source code for RegexStringValidator does nothing fancy; it simply uses a Regex and checks for success.
So I tried to do the regex directly as a test, the same way that it is done inside RegexStringValidator:
Regex reg = new Regex(@"issuer|subject", RegexOptions.Compiled);
bool match = reg.Match("issuer").Success;

The above works as expected; it returns Success==true.  I even used Telerik's "Just Decompile" to verify the System.Configuration source code indeed matches what is published online.
Again, I can see no reason why my "issuer|subject" RegexStringValidator regex constantly fails.
Any ideas?
The only clue I've turned up is when I tried the regex "[a-zA-Z]".  Strangely, this failed because it did not have the trailing asterisk.  So perhaps the regex must be written to match the full-length of the input.  To test that theory, I changed my regex to "^issuer$|^subject$", but that still didn't work when applied to the RegexStringValidator.  It does, however, work with my explicitly written regex test.
What makes the above anomaly interesting is that the source code for RegexStringValidator gives no reason of why "[a-zA-Z]" would fail.  Does this imply that the code I'm reflecting and seeing online does not match what is actually executing on my machine?  That doesn't seem plausible.  So this is weird indeed...
I'm using a .net 4.0 build, on a machine that has .net 4.5 installed.

A: I figured it out.
When the configuration system first creates the ConfigurationElement, it initializes each property to the empty string.  It then immediately runs the validation rules, including the regex.  The empty string does not match my regex, and so it fails before it ever had a chance to assign the real value to the property.
In short, there is a defect in the .net configuration infrastructure.
To compensate for this defect, I added a default value and an IsRequired requirement:
public class Test : ConfigurationElement
{
    [ConfigurationProperty("field", IsKey = true, Default="issuer", IsRequired=true)]
    [RegexStringValidator("issuer|subject")]
    public string Field
    {
        get { return (string)base["field"]; }
    }
}

The default allows the ConfigurationElement to initialize without automatically failing the regex.   Unfortunately, this creates an unwanted side-effect because I don't want a default.  So I then need to compensate for the default by setting IsRequired to true.
This means the user is now forced to provide a value, and it will be correctly be validated by my regex.
Incidentally, now I understand why the regex statements [a-zA-Z]* and .* were "successfull."  It is because the asterisk means "zero to many".  When the property is initialized as the empty-string, and tested against either of these two regex statements, the "zero" requirement saves the day.  Of course that is not the behavior I want, but at least now there is no mystery.

A: It's not strange that  "[a-zA-Z]" failed. It wouldn't match the entire string.
The rest of your problem does indeed seem odd. Maybe write your own code rather than depending on that of others when it behaves strangely?

A: Have you tried the reg expression as
[RegexStringValidator("(issuer|subject)")]


text:
Q: Airflow scheduler stops with exception I have attached the error message along the question
ERROR - Exception when executing SchedulerJob._run_scheduler_loop
Traceback (most recent call last):
  File "/home/centos/env_airflow/lib64/python3.6/site-packages/sqlalchemy/engine/base.py", line 1277, in _execute_context
    cursor, statement, parameters, context
  File "/home/centos/env_airflow/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 608, in do_execute
    cursor.execute(statement, parameters)
psycopg2.OperationalError: server closed the connection unexpectedly
        This probably means the server terminated abnormally
        before or while processing the request.

A: The PostgreSQL database server closed the connection unexpectedly.
Look into the PostgreSQL log file for an explanation.
There you will either find an error message that explains the reason, or you will find a similar message (unexpected connection loss), which would indicate that a malicious firewall or router is interrupted the network connection.