text:
Q: WPF Overlay does not activate until after button has finished I have a small sample WPF application using Caliburn Micro. In it, I have a rectangle overlay that says loading. I want this to appear whenever a large task is loading however it doesn't appear until after the method is finished. I have tried using Dispatch as well as other suggestions howver nothing works until after the button method is finished. Below is my current example
  public async void TheActionButton()
        {
            //Application.Current.Dispatcher.Invoke(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            Execute.OnUIThread(new System.Action(() => { IsLoadingMessageVisible = true; NotifyOfPropertyChange(() => IsLoadingMessageVisible); }));
            await LongMethod();
        }

The overlay shows up only after LongMethod() is finished running. Is there a way to get it to show before the method runs?

A: You haven't posted the implementation of LongMethod so it's impossible to say what it actually does, but I would guess that it isn't implemented as an asynchronous and blocks the UI thread.
You may try to execute it on a background thread using a Task:
public async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
    await Task.Run(LongMethod);
}

A method isn't automatically asynchronous just because it returns a Task or a Task<T> and can be awaited.

A: You should use the TAP (Task-based Asynchronous Programming), it integrates well with such use cases.
async void TheActionButton()
{
    IsLoadingMessageVisible = true;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);

    await LongMethod();

    IsLoadingMessageVisible = false;
    NotifyOfPropertyChange(() => IsLoadingMessageVisible);
}

Note: implement your IsLoadingMessageVisible in the way so that you don't need to call NotifyOfPropertyChange() each time you set the property.


text:
Q: re-evaluate remote validation I have a radio button and a drop down list.
The drop down list is "AM, PM, N\A"
if the user ticks the radio button, they signify half day, so should select AM or PM
If the radio button is un-ticked then they should select N\A (I know this can be changed by jquery also but ignore that for now);
I have two remote validations over each of them in the model, passing the other as an additional field.
[Remote("IsHalfDayChange", "Remote", AdditionalFields = "AmPm", HttpMethod = "POST", ErrorMessage = "{0}")]
public bool IsHalfDay { get; set; }

[Remote("AmPmChange", "Remote", AdditionalFields = "IsHalfDay", HttpMethod = "POST", ErrorMessage = "{0}")]
public int AmPm { get; set; }

By default, the radio button is unticked, (full day) and the drop down is set to N\A.
If the user ticks the radio button, the remote validation correctly sees the wrong value in the drop downlist and displays an error.
If the user changes the drop down to AM or PM, the error for the radio button remains because it hasn't been re-evaluated.
How can I use jquery to re-evaluate the remote errors when either the radio button or drop down list change?

A: To save on performance you can just evaluate one on change rather than both unless you want the error to display under all
<script type="text/javascript" name="remoteVal_V1">
    $(document).ready(function () {

        $("#amPmDropDownSelect").change(function () {
            //$("#isHalfDayCheckBox").removeData("previousValue").valid();
            $("#amPmDropDownSelect").removeData("previousValue").valid();
        });

        $("#isHalfDayCheckBox").change(function () {
            //$("#isHalfDayCheckBox").removeData("previousValue").valid();
            $("#amPmDropDownSelect").removeData("previousValue").valid();
        });
    });
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP Arrays, foreach can't access complete array elements I am having trouble accessing array Elements using foreach loop.
<?php
    echo "<form method=post action=test.php>";
    echo "Item Name: <input type=text name=item[]>";
    echo "Price: <input type=text name=item[]>";
    echo "Quantity: <input type=text name=item[]>";
    echo "
";
    echo "
";
    echo "<input type=submit name=submit>";

    if (isset ($_POST['item']))
    {

        $item = $_POST['item'];

    }

    $item = array (

                   $item_name = $item [0],
                   $price = $item [1],
                   $qty = $item [2],
                   );

    foreach ($item as $item)
    {

        echo $item[0];
        echo $item[1];
        echo $item[2];
    }

?>

A: Simple way, is to rename your <input type=text by needable fields(name, price, qty) and then get data from $_POST by their names:
echo "<form method=post action=test.php>";
echo "Item Name: <input type=text name='name'>";
echo "Price: <input type=text name='price'>";
echo "Quantity: <input type=text name='qty'>";
echo "
";
echo "
";
echo "<input type=submit name=submit>";

$name = "";
if (isset ($_POST['name']))
{
    $name = $_POST['name'];
}

$price = "";
if (isset ($_POST['price']))
{
    $price = $_POST['price'];
}

$qty = "";
if (isset ($_POST['qty']))
{
    $qty = $_POST['qty'];
}

If you want to use more flexible method with possible list of input fields, then create array of keys with possible field's names and check all existence each key in foreach loop:
$all_possible_items_keys = ["name","price","qty","author"];
$items = [];
foreach ( $all_possible_items_keys as $key )
{
    if (isset ($_POST[$key]))
    {
        $items[$key] = $_POST[$key];
    }

}

print_r($items);

Output example:
Array ( [name] => 11 [price] => 11 [qty] => 22 ):

Add names to your <input type=text and add it to $all_possible_items_keys, then $items will hold keys=>value.

A: Inside the loop, $item is just one element of the array, so you shouldn't index it. $item[0] is the first character of the element.
It's also confusing to use the same variable for the array and the element in the loop.
Write it like this:
foreach ($item as $element) {
    echo $element;
}

But instead, you should set up your HTML like this:
<form method="post" action="test.php">
Item Name: <input type="text" name="product_name[]">
Price: <input type="text" name="price[]">
Quantity: <input type="text" name="quantity[]">

Item Name: <input type="text" name="product_name[]">
Price: <input type="text" name="price[]">
Quantity: <input type="text" name="quantity[]">

Item Name: <input type="text" name="product_name[]">
Price: <input type="text" name="price[]">
Quantity: <input type="text" name="quantity[]">

Item Name: <input type="text" name="product_name[]">
Price: <input type="text" name="price[]">
Quantity: <input type="text" name="quantity[]">

...
<input type="submit" name="submit">
</form>

Then your PHP code can do something like this:
$items = array();
foreach ($_POST['product_name'] as $i => $item_name) {
    $price = $_POST['price'][$i];
    $quantity = $_POST['quantity'][$i];
    if (!empty($item_name) && !empty($price) && !empty($quantity)) {
        // code to insert into database
    }
}


text:
Q: Не могу сделать форму для поиска в django3 вот мой views
from django.shortcuts import render
from .models import *
from django.views.generic import ListView

# simplePost

# Create your views here.
def index(req):
  posts = simplePost.objects.all()
  data = {
      "posts": posts
  }
  return render(req, 'main/index.html', data)

class search(ListView):
  def get_queryset(self):
      return simplePost.objects.filter(title=self.request.GET.get('q'))

  def get_context_data(self, *args, **kwargs):
      context = super().get_context_data(*args, **kwargs)
      context["q"] = self.request.GET.get('q')

      return context

Вот simplePost_list.html (результаты поиска должны быть здесь)
{% extends '../base/base.html' %}
{% block title %}
Результат Поиска
{% endblock %}
{% block content %}

     {% for i in context %}

{{ i.title }}

{{ i.text }}

             {{ i.date }}

     {% endfor %}

{% endblock %}

сама форма
<form action="{% url 'search' %}" method="get" class="search-form" required="">
  {% csrf_token %}
  <input type="search" name="q" class="search" placeholder="Поиск записей
  в блоге">
</form>

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

A: Очень странная фраза поиска работает правильно но ничего не выводиться
На самом деле скорее всего у вас поиск и работает правильно. Но вы ошиблись с выводом результата поиска в шаблон.
Вместо {% for i in context %} надо писать {%for i in object_list%}
Но конечно лучше будет в класс поиска (во views) добавить что-то вроде
context_object_name="result_serch"

и тогда в шаблоне
{%for i in result_serch%}

P.S. подробнее о context_object_name в документации


text:
Q: Dialog layout height with 0dp in constraint layout not working Currently using Constraint layout to create dialog and place my view something like this but view height with 0dp is not working.
Here recyclerview is not visible.
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:bind="http://schemas.android.com/tools">
    <data>
        <variable
            name="passengerSeatViewModel"
            type="PassengerSeatViewModel" />
        <variable
            name="seatSelectionViewModel"
            type="SeatSelectionViewModel" />
    </data>
    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/colorWhite">
        <android.support.constraint.Guideline
            android:id="@+id/guideline_left"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_begin="@dimen/_20dp" />
        <android.support.constraint.Guideline
            android:id="@+id/guideline_right"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_end="@dimen/_20dp" />
        <include
            android:id="@+id/header"
            layout="@layout/dialog_header"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintLeft_toRightOf="@+id/guideline_left"
            app:layout_constraintRight_toLeftOf="@+id/guideline_right"
            bind:header="@{@string/text_seat_selected_for}"
            bind:onCancelClick="@{passengerSeatViewModel}" />
        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/tv_segment"
            style="@style/TextStyle_L_Black"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="@dimen/_5dp"
            android:layout_marginLeft="@dimen/_5dp"
            android:drawableEnd="@drawable/green_filled_tick"
            android:drawableRight="@drawable/green_filled_tick"
            android:drawablePadding="@dimen/_5dp"
            android:gravity="center"
            android:text="@{seatSelectionViewModel.getSelectedSegment()}"
            app:layout_constraintLeft_toRightOf="@+id/guideline_left"
            app:layout_constraintTop_toBottomOf="@+id/header" />
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_passengers"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginTop="@dimen/_3dp"
            app:layout_constraintBottom_toTopOf="@+id/barrier_select_seats"
            app:layout_constraintLeft_toLeftOf="@+id/guideline_left"
            app:layout_constraintRight_toRightOf="@+id/guideline_right"
            app:layout_constraintTop_toBottomOf="@+id/tv_segment"
            bind:data="@{seatSelectionViewModel.passengerAdapterViewModel}"
            bind:passengerViewModel="@{passengerSeatViewModel}" />
        <android.support.constraint.Group
            android:id="@+id/group_copy"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="gone"
            app:constraint_referenced_ids="btn_copy_seat,tv_or,seperator_left,seperator_right" />
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_copy_seat"
            style="@style/AppBtnStyle_Disable"
            android:layout_width="0dp"
            android:text="@string/text_copy_same_seat"
            app:layout_constraintLeft_toLeftOf="@+id/guideline_left"
            app:layout_constraintRight_toRightOf="@+id/guideline_right"
            app:layout_constraintTop_toBottomOf="@+id/rv_passengers" />
        <android.support.v7.widget.AppCompatTextView
            android:id="@+id/tv_or"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/_20dp"
            android:paddingLeft="@dimen/_23dp"
            android:paddingRight="@dimen/_23dp"
            android:text="@string/or"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/btn_copy_seat" />
        <View
            android:id="@+id/seperator_left"
            android:layout_width="0dp"
            android:layout_height="@dimen/_1dp"
            android:background="@color/colorDividerSearch"
            app:layout_constraintBottom_toBottomOf="@+id/tv_or"
            app:layout_constraintLeft_toRightOf="@+id/guideline_left"
            app:layout_constraintRight_toLeftOf="@+id/tv_or"
            app:layout_constraintTop_toTopOf="@+id/tv_or" />
        <View
            android:id="@+id/seperator_right"
            android:layout_width="0dp"
            android:layout_height="@dimen/_1dp"
            android:background="@color/colorDividerSearch"
            app:layout_constraintBottom_toBottomOf="@+id/tv_or"
            app:layout_constraintLeft_toRightOf="@+id/tv_or"
            app:layout_constraintRight_toLeftOf="@+id/guideline_right"
            app:layout_constraintTop_toTopOf="@+id/tv_or" />
        <android.support.constraint.Barrier
            android:id="@+id/barrier_seats"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:barrierDirection="bottom"
            app:constraint_referenced_ids="tv_or,rv_passengers" />
        <android.support.constraint.Barrier
            android:id="@+id/barrier_select_seats"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:barrierDirection="top"
            app:constraint_referenced_ids="tv_or,btn_select_seat" />
        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_select_seat"
            style="@style/AppBtnStyleBlueBorderless"
            android:layout_width="0dp"
            android:layout_marginTop="@dimen/_16dp"
            android:text="@string/text_select_seat_for"
            app:layout_constraintBottom_toTopOf="@+id/footer_space"
            app:layout_constraintLeft_toLeftOf="@+id/guideline_left"
            app:layout_constraintRight_toRightOf="@+id/guideline_right" />
        <Space
            android:id="@+id/footer_space"
            android:layout_width="0dp"
            android:layout_height="@dimen/_22dp"
            app:layout_constraintBottom_toBottomOf="parent" />
    </android.support.constraint.ConstraintLayout>
</layout>

NOTE:

*

*1) Need to fix button at footer and other content above it. Above
portion will have height of wrap content.
2) Content is not scrolling inside bottom sheet

A: Use  app:layout_constraintHeight_default="wrap" in recyclerView

A: Use RelativeLayout in xml Dialog


text:
Q: Is there any program library support filtering JSON like mongodb query syntax? In mongodb, I can use query JSON like {"size":40} to get documents which size is 40.
Is there any program library to filter/check pure JSON document with a JSON query statement?

A: Have a look at libraries like lodash, or underscore.
A function like filter would be a good example.
Something like this can be used:
var items = [{
  "id": 1,
  "size": 3
}, {
  "id": 2,
  "size": 4
}, {
  "id": 3,
  "size": 1
}];

var result = items.filter(function(item) {
  return item.size == 1;
});

console.log(result);

Good video describing the use of the filter() function


text:
Q: Emojis are being displayed with a tag at the end in a Text Component, how to remove "undefined"? so I have a slider with a bunch of different emojis the user can select. But when they select one it gets displayed as "undefined".
When I display it in the console that doesn't get added only on the app it shows. How do I go about to remove the undefined part?
Screenshot:
[1]: https://i.stack.imgur.com/RlMQR.jpg
Code:
const [selectedEmoji, setSelectedEmoji] = useState([""]);
<Text style={{ color: "white", fontFamily: "Futura", padding: 20 }}>
     `{isToggled ? selectedEmoji + "Emoji ▲" : selectedEmoji + "Emoji ▼"}
</Text>
</TouchableOpacity>

Let me know if you need more code or have any ideas to the cause of this issue


text:
Q: Как найти все исходящие ссылки с сайта? Кто-нибудь знает проверенный скрипт, или программу, которая сможет найти все исходящие ссылки с сайта и указать на каких страницах они расположены.
Будьте добры, поделитесь информацией.
A: Вроде бы была такая функция в программе Internet Download Manager
A: Screaming Frog SEO Spider Tool Страница инструмента - считается одним из лучлих пауков для просмотра сайта. В т.ч. включает и список исходящих со страницами
Netpeak Spider Страница инструмента - аналог подешевле, тоже достаточно неплохой
Или другие SEO crawler'ы
https://ahrefs.com/ - сервис анализа доменов. Вводишь домен и выбираешь в группе Outgoing links - показывает какие ссылки на каких страницах

A: Вот тут есть мои 2 метода в описании топика, которые достают линки со страницы:
Вообщем-то, там ничего сложного - попробуйте..
Методы написаны на java


text:
Q: Stop Javascript function from firing onload? I've got this function that brings up a pop-up window onClick. However, it's working both onClick and onLoad. Naturally, this would be annoying to the end user to have to exit the window every time they load a page. Does anybody have an idea on how to make this onClick only? Removing the function at end stops the script completely.
function showMailingPopUp() {
    require(
        ["mojo/signup-forms/Loader"],
        function(L) {
          L.start({"baseUrl":"mc.us4.list-manage.com","uuid":"91363270e58a57510d5d933c6","lid":"b2d7dd4078"})
        }
    );

    document.cookie = 'MCPopupClosed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
    document.cookie = 'MCPopupSubscribed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
}

showMailingPopUp();

A: The reason your function is being called onLoad() is because you are calling it using showMailingPopUp(); at the end of your script.
onClick functionality should follow this format:
<button onclick="showMailingPopUp()">Click me to show mailing popup</button>

A: The reason showmailingPopUp isn't working with onclick is because it cannot find it. It should either be defined before in a script tag or in JavaScript binding with an event listener.
Here is a solution using JavaScript (adding an event listener to an element so the function will call correctly):
function showMailingPopUp() {
    require(
        ["mojo/signup-forms/Loader"],
        function(L) {
          L.start({"baseUrl":"mc.us4.list-manage.com","uuid":"91363270e58a57510d5d933c6","lid":"b2d7dd4078"})
        }
    );

    document.cookie = 'MCPopupClosed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
    document.cookie = 'MCPopupSubscribed=;path=/;expires=Thu, 01 Jan 1970 00:00:00 UTC;';
}

document.getElementById("element").addEventListener("click", function(){
    showMailingPopUp();
})

jsFiddle


text:
Q: show pragress bar while downloading file Hi in my application I have a file in URL I want download to my document folder in my application while downloading the file i want to show the progress bar. So I have used the MBProgressHUD for that but its not working properly its showing late please tell me how to resolve this one.
My code:
- (IBAction)down:(id)sender {
    UIButton *btn = (UIButton *)sender;

     spinner =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];

     spinner.mode = MBProgressHUDModeCustomView;

     [spinner setLabelText:@"downloading....."];

     [spinner setLabelFont:[UIFont systemFontOfSize:15]];

     [spinner show:YES];
   NSURL  *url = [NSURL URLWithString:fileurl];
   NSData *urlData = [NSData dataWithContentsOfURL:url];

    if ( urlData )
     {

        NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];

        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,name];
    [urlData writeToFile:filePath atomically:YES];
     }
   [activityIndicatorObject stopAnimating];
   [spinner hide:YES];

   [spinner removeFromSuperViewOnHide];

   }

I have used the above code its taking too much time to show the MBProgressHUD Please tell me how to resolve this issue I have stuck here for time.
Thanks..

A: You have to change in your code as below..
   - (IBAction)down:(id)sender {
UIButton *btn = (UIButton *)sender;

 //spinner =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   [MBProgressHUD showHUDAddedTo:self.view animated:YES];

 //spinner.mode = MBProgressHUDModeCustomView;

 //[spinner setLabelText:@"downloading....."];

 //[spinner setLabelFont:[UIFont systemFontOfSize:15]];

 //[spinner show:YES];
      NSURL  *url = [NSURL URLWithString:fileurl];
      NSData *urlData = [NSData dataWithContentsOfURL:url];

if ( urlData )
 {

    NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString  *documentsDirectory = [paths objectAtIndex:0];

    NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,name];
[urlData writeToFile:filePath atomically:YES];
 }
   //[activityIndicatorObject stopAnimating];
   //[spinner hide:YES];

  //[spinner removeFromSuperViewOnHide];
  [MBProgressHUD hideHUDForView:self.view animated:YES];

  }

Enjoy Code..

A: I suspect what you are experiencing are concurrency issues with the above code. I'm assuming the URL you are fetching is from over a network. The NSData method dataWithContentsOfURL: is blocking the main thread before the operating system has a chance to call setNeedsDisplay on the spinner, which also happens on the main thread, and this could explain why it's showing up late.
The solution would be to make some sort of asynchronous request, to fetch the file, with a completion handler, so your application can do tasks etc upon completion, (like stopping the activity indicator, persisting the file to local storage etc).
This is what the documentation has has to say about the dataWithContentsOfURL: of NSData class :-

Important: Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
  Instead, for non-file URLs, consider using the dataTaskWithURL:completionHandler: method of the NSSession class.


text:
Q: IntelliJ does not see sources, generated by Antlr4 (Cannot resolve symbol) I am trying to use Antlr4 with IntelliJ and Gradle and Antlr4 gradle plugin and Antlr4 IntelliJ plugin.
Unfortunately, IntelliJ does not see class names, generated by Antrl4, while Gradle tasks work fine.
In Project Structure I got the following chaos:

1) generated-src\antlr\main folder is depicted black (not red), but in different way than other sources and may be incorrect
2) a lot of red and wron source paths generated
3) generated source branch is within excluded group by color
4) main inside generated-scr has marking "sources root" and project name near it
5) no any root markings remain near main roots
6) "Cannot resolve symbol 'QueryByExamplesListener'" error mark inside QueryByExampleParser.java generated file, although QueryByExamplesListener.java file is right near it
Is it possible to fix all this?


text:
Q: C: Pass array in place of variable argument list I am writing a simple shell in C. It is actually coming along quite well with i/o redirection and such. One thing that I'd like to add is a way to switch between versions of the exec* functions. Right now I'm sticking to execlp(), execvp(), and execve().
I have all the arguments I want to pass in an array called argv. It is a null terminated array of null terminated strings, so it works fine with execv*, but I can't think of how to get it to work with execlp().
This is what I have now:
if     (strcmp(exec_opt, "vp") == 0)
  error = execvp(argv[0], argv);          /* Execute vp */
else if(strcmp(exec_opt, "lp") == 0)
  error = execlp(argv[0], "", argv);      /* Execute lp */
else if(strcmp(exec_opt, "ve") == 0)
  error = execve(argv[0], argv, environ); /* Execute ve */
else
{
  // throw errors about exec_opt
}

if(error != 0)
{
  // do something about it
}

In this configuration the compiler doesn't baff at the syntax, but it also doesn't work.
I've also tried
 error = execlp(argv[0], (char*) argv);  /* As a single string */
 char* argv1 = argv[1];                  /* don't pass command itself */
 error = execlp(argv[0], argv1);

Which do various odd but ultimately incorrect things. Is there a way for me to turn my array into a variable argument list? passing it directly (which makes the most type-sense, since variable argument lists are char* argv[]) yields a compiler error about casting incompatible pointers.

A: You can't really use execlp() with the array.  To use execlp(), you have to write out:
execlp(array[0], array[0], (char *)0);
execlp(array[0], array[0], array[1], (char *)0);
execlp(array[0], array[0], array[1], array[2], (char *)0);
execlp(array[0], array[0], array[1], array[2], array[3], (char *)0);
...

for each alternative number of arguments.  This is why execvp() was added to the repertoire (it wasn't part of 7th Edition UNIX™ in 1978, but was part of SUS v2 in 1997).  Now you just need execvpe(), which does not exist AFAIK (and I don't know why it isn't provided, either).

7th Edition UNIX did have excevp()
Dave said:

The 7th Edition manual does list execvp.

And ... it does, partially.  I think we have an erratum to report since the manual actually contains:

NAME
execl, execv, execle, execve, execlp, execvp, exec, exece, environ – execute a file
SYNOPSIS
execl(name, arg0, arg1, ..., argn, 0)
char *name, *arg0, *arg1, ..., *argn;
execv(name, argv)
char *name, *argv[ ];
execle(name, arg0, arg1, ..., argn, 0, envp)
char *name, *arg0, *arg1, ..., *argn, *envp[ ];
execve(name, argv, envp);
char *name, *argv[ ], *envp[ ];
extern char **environ;

DESCRIPTION

So, execvp() is listed in the NAME section, but there is no synopsis for execvp() (which is what I looked at to come to the conclusion it was missing).  There is a reference to execvp() on the next page:

Execlp and execvp are called with the same arguments as execl and execv, but duplicate the shell's actions in searching for an executable file in a list of directories. The directory list is obtained from the environment.

So, I excuse myself because I scanned the SYNOPSIS and execvp() was omitted from the synopsis.  But actually, the system call was present in 7th Edition Unix.  I don't think anyone is about to re-release the manuals with the omission fixed.
My print copy (yes, I do have printed properly bound versions of both Volume 1 (ISBN 0-03-061742-1) and Volume 2 (ISBN 0-03-061743-X) of the manual from way back then; I obtained them circa 1989) has the same omission in the SYNOPSIS section.

A: Try using avcall.  I haven't used it myself, I just found an interesting mention of it here: Passing parameters dynamically to variadic functions


text:
Q: ASP.Net MVC - dropdown list for associated objects I have two models in my application: Product and ProductType. Product has a reference to ProductType (in the DB it's named ProductTypeId), while ProductType has two columns (Id and Name).
I can get the dropdown to be properly populated and displayed on the forum using the following code:
Controller:
var typeList = new SelectList(_entities.ProductType.ToList(), "Id", "Name");
ViewData["Types"] = typeList;

View:
<%= Html.DropDownList("ProductType", (IEnumerable<SelectListItem>) ViewData["Types"]) %>

However my problem becomes that it's not updating the model back in the Controller.  If I leave the code as is, then the ModelState is invalid because of the ProductType string in the view, However, if I change it to anything else, it seems I can no longer refer to it within the controller.

A: I just tried the very same thing and it worked for me just fine
controller:
 public ActionResult Create()
    {
    configuratorDataContext dc = new configuratorDataContext();
    SelectList typelist = new SelectList(dc.Product_types.ToList(), "id", "Name");
    ViewData["Product_Types"] = typelist;
    ViewData.Model = new Product();
    return View();
    }

    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create(Product createProduct)
    {
    // createProduct here contains correct type_id wich
    }

view:
  <%= Html.DropDownList("type_id", (IEnumerable<SelectListItem>) ViewData["Product_Types"])%>


text:
Q: Get quantile for each value Is there an implemented (!) function in R which gives you the empirical quantile for each value? I couldn't find any ...
Let's say we have x
x = c(1,3,4,2)

I want to have the quantile of each element.
[1] 0.25, 0.75, 1, 0.5

Thank you very much!

A: You can use the ecdf() function:
ecdf(x)(x)
[1] 0.25 0.75 1.00 0.50

ecdf(x) creates a function, and you pass the elements of x to that function. The syntax admittedly looks strange


text:
Q: SQL query to select all forum threads but order them by the latest active thread I'm currently using this code to order the forum threads within my forum according to the date they were created.
$e = mysqli_real_escape_string($_GET["forum"]);
$q = mysqli_query($con,
     "SELECT * FROM threads WHERE forum = '$e' ORDER BY date DESC LIMIT $offset,$rowsPerPage");

However, this order's the threads by their creation date rather than their activity.
How can I order the threads by their activity?
I'm thinking of something along the lines of
SELECT * FROM threads WHERE forum = '$e' ORDER BY (replies in this thread).date DESC LIMIT 5
Is this possible or not?
EDIT:
table thread holds the inital thread data
table replies holds the replies

A: Add a column containing the last time a thread has been replied into your threads table, and then use order by this col. Don't forget to update the column on new reply.
There are ways to do it manually, but it will be far more slower than a dedicated column.

A: a subselect-join will do the trick:
select t.* , lp.latestpost
from threads as t
inner join (
  select p.thread_id , max(p.date) as latestpost
  from replies as p
  group by p.thread_id
) as lp on pl.thread_id = t.id
order by lp.latestpost desc


text:
Q: Send broadcast on notification click I have an application which is basically a webview and GCM notifications. I want to achieve the following thing: If the user is in the app and receives a notification, when he clicks the notification I want the webview to load the url provided in the notification.
I'm trying to accomplish this by using broadcast receiver but it doesn't work.
I dynamically register the receiver in the MainActivity:
private void registerNotificationReceiver() {
        final IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_LOAD_URL_FROM_NOTIFICATION);
        Log.i(TAG, "registerNotificationReceiver()");
        this.receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "notification received");

            }
        };

        super.registerReceiver(this.receiver, filter);
    }

And in the GCM Listener I'm using PendingIntent.getBroadast():
final Intent broadcastIntent = new Intent(MainActivity.ACTION_LOAD_URL_FROM_NOTIFICATION);
        PendingIntent intent = PendingIntent.getBroadcast(getApplicationContext(), 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        notificationBuilder.setContentIntent(intent);

        notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, notification);

I don't understand why onReceive in the MainActivity class is not called. The message "notification received" is not displayed.
Can you help me? Thank you :)

A: I cannot find right now the reason but there's a security reason. Latest Android versions won't allow you to trigger a listener from "kind-of" remote process without it being explicit.
The intent you broadcast MUST be explicit for it to work. Explicit means that you have to explicitly call the component that will handle the intent (the receiver). So this receiver must be declared in its own class and in the manifest as a <receiver>.
Follow this guy's example in the section Explicit Broadcast Intents http://codetheory.in/android-broadcast-receivers/
and thy will be done.


text:
Q: Setting up a basic api in rails I'm trying to create a basic rails app. I created an apis controller like so
class ApisController < ApplicationController
    def calendar
       #code
       render json: @response
    end
end

and my routing file looks like this
namespace :api, defaults: {format: 'json'} do
    get 'calendar' => 'apis#calendar'
end

Unfortunately i get the error uninitialized constant Api. I would ideally like to keep the api as simple as possible. Where am I going wrong
Any help is appreciated and Merry Christmas!

A: I recommend wrapping it in a module. You can manage versioning the same way.
Here's an example:
https://www.amberbit.com/blog/2014/2/19/building-and-documenting-api-in-rails/

A: Figured using scopes instead of namespaces
scope :api, defaults: {format: 'json'} do
    get 'calendar' => 'apis#calendar'
end


text: Q: Is there a way to refresh a custom notification depending on day/night mode? I want to know is there is a way to change the custom notification when it is already created depending on day/night mode, I mean the custom notification is of white color when it is in notification panel, but when the user changes to night mode from quick settings I want the notification turn to black.


text:
Q: Azure Devops pipeline cannot find al.exe I'm migrating an on-prem build onto Azure Devops. I am using a default Azure build agent with nothing specified over the default agent config.
Here is the part of the build pipeline YAML that is throwing an error:
- task: NuGetCommand@2
  displayName: 'Build Assemblies: Restore'
  inputs:
    command: 'restore'
    restoreSolution: '$(FooSolutionSolution)'
    feedsToUse: 'config'

- task: VSBuild@1
  displayName: 'Build Assemblies: Run'
  inputs:
    solution: '$(FooSolutionSolution)'
    platform: '$(FooSolutionBuildPlatform)'
    configuration: '$(buildConfiguration)'
    msbuildArgs: '-t:rebuild'

It is using the standard Microsoft.Common.CurrentVersion.targets file but is failing to find al.exe.
CoreCompile:
  C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Roslyn\vbc.exe /noconfig /imports: {..imports..} /optioncompare:Binary /optionexplicit+ /optionstrict+ /optioninfer+ /nostdlib /platform:AnyCPU /rootnamespace:FooCorp.Central /sdkpath:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1" /highentropyva+ /define:"CONFIG=\"Release\",TRACE=-1,_MyType=\"Windows\",PLATFORM=\"x64\"" /reference: {..references ..} /main:"FooCorp.Central.(None)" /debug- /keyfile:d:\a\1\s\Builds\FooCorpKey\FooCorpKey.snk /optimize+ /out:.\obj\x64\Release\FooSolution\FooCorp.Central.dll /ruleset:"C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Team Tools\Static Analysis Tools\\Rule Sets\MinimumRecommendedRules.ruleset" /subsystemversion:6.00 /resource:.{..resources..}  /target:library /warnaserror+ /utf8output /langversion:14 AssemblyInfo.vb {..all other vb files..} "C:\Users\VssAdministrator\AppData\Local\Temp\.NETFramework,Version=v4.5.1.AssemblyAttributes.vb"
  Using shared compilation with compiler from directory: C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Roslyn
GenerateSatelliteAssemblies:
  Creating directory ".\obj\x64\Release\FooSolution\es".
  Creating directory ".\obj\x64\Release\FooSolution\ru".
  Creating directory ".\obj\x64\Release\FooSolution\zh-CN".
  Creating directory ".\obj\x64\Release\FooSolution\lb-LU".
##[error]C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\MSBuild\Current\Bin\Microsoft.Common.CurrentVersion.targets(3639,5):
Error MSB6004: The specified task executable location "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\al.exe" is invalid.

This is something that I don't think I can control.
For comparison when I run the build locally from the command line the output from the same part of the build is:
GenerateSatelliteAssemblies:
  C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\al.exe /culture:zh-CN /keyfile:C:\s-gl\Builds\FooCorpKey\FooCorpKey.snk /out:.\obj\x64\Release\FooSolution\zh-CN\FooCorp.Central.Lic.resources.dll /platform:AnyCPU /template:.\obj\x64\Release\FooSolution\FooCorp.Central.Lic.dll /embed:.\obj\x64\Release\FooSolution\FooCorp.Central.Lic.a1.zh-CN.resources /embed:.\obj\x64\Release\FooSolution\FooCorp.Central.Lic.a2.zh-CN.resources /embed:.\obj\x64\Release\FooSolution\FooCorp.Central.Lic.a3.zh-CN.resources

As the build agent is supplied by Azure is there a way I can determine where the SDK tools are located?
Although https://stackoverflow.com/a/42140667 was reported for TeamCity not Azure Devops the solution there was to specify a different path to al.exe . Do I need to do something similar here?
Thanks

A: According to the logs, it appears that you are using the hosted windows-2019 agent.
By default the NETFX 4.6.1 Tools are not installed on the windows-2019 agent. So it cannot find the al.exe file under "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\al.exe". See Hosted Windows 2019 for details.
However the NETFX 4.6.1 Tools are installed on vs2017-win2016 agent. So, please try using vs2017-win2016 agent instead of the windows-2019 agent.
You can run the following commands in pipeline to check the installed versions
 of NETFX tools on each of the agents:
cd 'C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin'
dir

So, to use the latest windows-2019 agent, you can try to specify the path to the SDK editing directly in the [projectname].csproj file, add:
<TargetFrameworkSDKToolsDirectory>C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.7.2 Tools</TargetFrameworkSDKToolsDirectory>


text:
Q: STX: How to process elements that have a more higher level than a matched element has? ...or maybe somehow get child's content?
Hi guys, I'm using STX because I've got huge XML files.
I have some input
<?xml version="1.0" encoding="UTF-8"?>
<ME>
  <DataContainer id="1">
    <attributes>
      <DataType>vsDataF</DataType>
      <vsDataF>
        lable-F
        <zzz>100</zzz>
      </vsDataF>
    </attributes>
    <DataContainer id="1">
      <attributes>
        <DataType>vsData1</DataType>
        <vsData1>
          lable-1
          <zzz>1000</zzz>
        </vsData1>
      </attributes>
    </DataContainer>
    <DataContainer id="1">
      <attributes>
        <DataType>vsData2</DataType>
        <vsData2>
          lable-2
          <zzz>2000</zzz>
        </vsData2>
      </attributes>
    </DataContainer>
  </DataContainer>
  <DataContainer id="2">
    <attributes>
      <DataType>vsDataG</DataType>
      <vsDataG>
        lable-G
        <zzz>200</zzz>
      </vsDataG>
    </attributes>
</ME>

and I need to get such output
<?xml version="1.0" encoding="UTF-8"?>

  <vsDataF>
    <id>1</id>
    lable-F
    <zzz>100</zzz>
    <vsData1>
      <id>1</id>
      lable-1
      <zzz>1000</zzz>
    </vsData1>
    <vsData2>
      <id>1</id>
      lable-2
      <zzz>2000</zzz>
    </vsData2>
  </vsDataF>
  <vsDataG>
    <id>2</id>
    lable-G
    <zzz>200</zzz>
  </vsDataG>

I wrote a transform that does it partly
<stx:transform
  version="1.0"
  xmlns:stx="http://stx.sourceforge.net/2002/ns"
  output-method="xml">

  <stx:variable name="table_name"/>

  <stx:template match="/">

      <stx:process-children/>

  </stx:template>

  <stx:template match="ME/DataContainer/attributes/DataType">
    <stx:assign name="table_name" select="."/>
    <stx:element name="{$table_name}">
      <id>
        <stx:value-of select="../../@id"/>
      </id>
    </stx:element>
  </stx:template>

</stx:transform>

I know, there are few stx:process, for example stx:process-children, stx:process-self, stx:process-siblings, but this case it's does not work.

A: I've solved this problem. I learned how stx:group and stx:buffer work, it was difficult for me, but I managed to do it.
<stx:transform
  version="1.0"
  xmlns:stx="http://stx.sourceforge.net/2002/ns"
  output-method="xml">

  <stx:variable name="table_name"/>
  <stx:buffer name="columns"/>

  <stx:template match="/">

      <stx:process-children/>

  </stx:template>

  <stx:group name="copy-all" pass-through="all"/>

  <stx:template match="DataContainer/attributes/*[2]/*">
    <stx:element name="{local-name()}">
      <stx:value-of select="."/>
    </stx:element>
  </stx:template>

  <stx:template match="DataContainer/attributes/*[2]">
    <stx:assign name="table_name" select="local-name()"/>
    <stx:result-buffer name="columns" clear="yes">
      <stx:process-children/>
    </stx:result-buffer>
  </stx:template>

  <stx:template match="DataContainer/*[1]" priority="2">
    <stx:process-self/>
    <stx:element name="{$table_name}">
      <id>
        <stx:value-of select="../@id"/>
      </id>
      <stx:process-buffer name="columns" group="copy-all"/>
      <stx:process-siblings/>
    </stx:element>
  </stx:template>

</stx:transform>


text:
Q: How to find indices of NA values in one matrix and remove these indices from another matrix in R? I have 2 matrix (8760,318).
A = 1 2 3 4
    5 6 7 8
    9 0 1 11
    1 8 3 7

B = NA NA NA NA
    NA NA NA NA
    1  3  5  7
    2  4  6  8

I would like to find the indices of NA values in Matrix B and remove values corresponding to these indices in Matrix A and Matrix B. In the end I would like to have
A = 9 0 1 11
    1 8 3 7

B = 1 3 5 7
    2 4 6 8

I also would like to protect matrix form (x,318). All methods I have tried so far, broke the matrix form and gave me a vector with 1 row.

A: For A (lil bit hacky, maybe i will edit)
A[!is.na(B)[,1],]

For B
na.omit(B)

A: What about putting to NA all the values in A that are NA in B and apply na.omit() to A?
for (i in 1:nrow(B)) { for (j in 1:ncol(B)) { if (is.na(B[i,j])) A[i,j] = NA } }

na.omit(A)

A: I suggest converting to a data frame first.
A <- as.data.frame(A)
# 'data.frame':   4 obs. of  4 variables:
 # $ V1: num  1 5 9 1
 # $ V2: num  2 6 0 8
 # $ V3: num  3 7 1 3
 # $ V4: num  4 8 11 7

B <- as.data.frame(B)

Use the following to filter out rows where all entries are NA. This also ensures that you do not end up with a number of elements that cannot be formatted into a table-like structure
isrowallna <- apply(B, 1, function(x) all(is.na(x)))

Filter the data frame appropriately
A <- A[!isrowallna,]
B <- B[!isrowallna,]

Revert to matrix
A <- as.matrix(A)
 # num [1:2, 1:4] 9 1 0 8 1 3 11 7
 # - attr(*, "dimnames")=List of 2
  # ..$ : chr [1:2] "3" "4"
  # ..$ : chr [1:4] "V1" "V2" "V3" "V4"

B <- as.matrix(B)

Your data
A = matrix(c(1, 2, 3, 4,
    5, 6, 7, 8,
    9, 0, 1, 11,
    1, 8, 3, 7), nrow=4, byrow=TRUE)

B = matrix(c(NA, NA, NA, NA,
    NA, NA, NA, NA,
    1,  3,  5,  7,
    2,  4,  6,  8), nrow=4, byrow=TRUE)


text:
Q: With Pygame, is there a faster way to draw hundreds of small squares? I'm attempting to make a tile based game, not done anything like this before so I'm learning as I go along. However, I've got a big problem with speed, and I was wondering if anyone had any solutions/advice. I tried to separate recalculating bits and the actual drawing, though as you can only move the camera currently, it's got to do both at once, and it's very noticeable how slow it runs if you have a small tilesize and large resolution.
I thought an idea would be to split it into chunks, so you calculate an x*x area, and instead of checking each tile if it's within the screen bounds, you only check the group of tiles, then somehow cache it the first time it's drawn so you then end up drawing a single image from memory. However I didn't find anything on that when googling it.
As to the drawing part, it runs to the effect of:
for tile in tile_dict:
    pygame.draw.rect(precalculated stuff)

With the same tilesize as the image below, at 720p it runs at 100fps, and at 1080p it runs at 75fps. This is with literally nothing but drawing squares. Each block is a slightly different colour, so I can't just draw a bigger square. I know not to redraw every frame by the way.
As to the recalculation part, it's a bit longer but still quite easy to understand. I calculate which coordinates would be at the edge of the screen, and use that to build a list of all on screen tiles. I then delete any tiles that are outside of this area, move the cooordinate to the new location if the tile has moved on screen, and calculate any tiles that have just appeared. This runs at about 90fps at 720p, or 45fps at 1080p, which is really not good.
def recalculate(self):
    overflow = 2
    x_min = self.cam.x_int + 1 - overflow
    y_min = self.cam.y_int + 1 - overflow
    x_max = self.cam.x_int + int(self.WIDTH / self.tilesize) + overflow
    y_max = self.cam.y_int + int(self.HEIGHT / self.tilesize) + overflow

    self.screen_coordinates = [(x, y)
                               for x in range(x_min, x_max)
                               for y in range(y_min, y_max)]

    #Delete the keys that have gone off screen
    del_keys = []
    for key in self.screen_block_data:
        if not x_min < key[0] < x_max or not y_min < key[1] < y_max:
            del_keys.append(key)
    for key in del_keys:
        del self.screen_block_data[key]

    #Rebuild the new list of blocks
    block_data_copy = self.screen_block_data.copy()
    for coordinate in self.screen_coordinates:

        tile_origin = ((coordinate[0] - self.cam.x_int) - self.cam.x_float,
                       (coordinate[1] - self.cam.y_int) - self.cam.y_float)
        tile_location = tuple(i * self.tilesize for i in tile_origin)

        #Update existing point with new location
        if coordinate in self.screen_block_data:
            self.screen_block_data[coordinate][2] = tile_location
            continue

        block_type = get_tile(coordinate)

        #Generate new point info
        block_hash = quick_hash(*coordinate, offset=self.noise_level)

        #Get colour
        if coordinate in self.game_data.BLOCK_TAG:
            main_colour = CYAN   #in the future, mix this with the main colour
        else:
            main_colour = TILECOLOURS[block_type]
        block_colour = [min(255, max(0, c + block_hash)) for c in main_colour]
        self.screen_block_data[coordinate] = [block_type,
                                              block_colour,
                                              tile_location]

I realised in what I wrote above, I probably could cache the info for a 10x10 area or something to cut down on what needs to be done when moving the camera, but that still doesn't get around the problem with drawing.
I can upload the full code if anyone wants to try stuff with it (it's split over a few files so probably easier to not paste everything here), but here's a screenshot of how it looks currently for a bit of reference:

A: To increase the speed of drawing the small squares, you can draw them onto non-screen surface (any pygame surface that will be big enough to hold all the squares) and then blit this surface on the screen with correct coordinates.
This way you won't need to check if any squares are outside the screen and it will be only necessary to provide inverted camera (viewpoint) coordinates (If camera position is [50,20] then you should blit the surface with tiles onto [-50,-20]).


text:
Q: How can i make windows 10 boot loader load first then bitlocker I create Windows 10 dual boot installation
windows 10 (1) [ ENCRYPTED ] ||  windows 10 (2)
I encrypted my C: Drive on my windows 10 (1) installation and when I restart my machine bitlocker want's me to put the password in -- sometimes I don't want to boot to windows 10 (1) encrypted drive i just want to boot to windows 10 (2) without putting bitlocker password.
Is it possible to make boot loader load first to select the OS then depending on the OS bitlocker asks for the password?
For example:
This what happening
PC Starting > Bitlocker Screen > Bootloader Chose a OS to boot from
I need it like:
PC Starting >  Bootloader Chose a OS to boot from > If the OS have Bitlocker enabled display Bootloader Chose a OS to boot from.

A: Bitlocker is actually integrated inside the Windows boot-loader and always gets activated FIRST before the OS selection is shown.
As far as I know the only way around that is to use another (non-Microsoft) bootloader that in turns calls the Windows bootloader.
That may mean boot from another disk first, which holds the 3rd party bootloader (most people would use grub, the bootloader also used by Linux), which then calls either bootloader of Windows 1 or Bootloader of Windows 2.
Another typical scenario is dual-booting between Linux and Windows, using the Linux bootloader (grub) as the main loader, which in turn calls the Windows loader when needed (and you can have multiple Windows loaders from the Linux bootloader too).
You might want to look into the "Plop" bootlader. Plop is specifically designed for all sort of weird boot-loader scenarios where the normal bootloader provided by the OS isn't quite able to make things happen as you would like.
Plop can also (in some cases) work around some limitations of your Bios.
PS. I'm not affiliated with Plop. Just a happy user of that particular piece of software.

A: Press F11 on bitlocker screen and select a different OS.


text:
Q: Eclipse/maven - "Cannot change version of project facet EAR to 6.0 My Eclipse project has the following problem:
Maven error:

|Description||Resource||Path||Location||Type |Cannot change version of
  project facet EAR to 6.0.|[name]-ear||line 1|Maven Java EE
  Configuration Problem

A: I edited the fellowing files:
File: pom.xml:
[...]
<dependencies>
 [...]
 <dependency>
  <groupId>javax</groupId>
  <artifactId>javaee-api</artifactId>
  <version>6.0</version>
  <scope>provided</scope>
 </dependency>
 [...]
</dependencies>
[...]

File: org.eclipse.wst.common.project.facet.core.xml
[...]
<faceted-project>
 <installed facet="jst.ear" version="6.0"/>
</faceted-project>
[...]

after  > Maven > Update maven Project


text:
Q: Android open gallery is not working in my code I'm trying this code to open the gallery. My app makes a directory in the gallery. I can see my directory in the gallery. I'm trying to open it from my app by this code:-
        File sdDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File f = new File(sdDir, "Photo Location Note");
        Intent i = new Intent();
        i.setAction(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.withAppendedPath(Uri.fromFile(f), "Photo Location Note"), "image/*");
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);

It opens the gallery and shows a toast message as "Unable to find item". It doesn't open my directory "Photo Location Note" in the gallery.
How can I open my directory "Photo Location Note" in the gallery?

A: It works for me on Android 11 and earlier versions:
    public void openPhoto(Context context, String directory){

    File file = new File(directory);
    if(!file.exists()){
        return;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
                    FileProvider.getUriForFile(context,context.getPackageName() + ".provider", file) : Uri.fromFile(file),"image/*");

    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent = Intent.createChooser(intent, "Open File");
    context.startActivity(intent);

}

This fragment is important:
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);


text:
Q: значение типа "const char *" нельзя использовать для инициализации сущности типа "char *" я студент университета. Преподаватель прислал код для ознакомления. Я скопировал код в Visual Studio 2019 в точности, как было написано в документе, но компилятор выдаёт много ошибок. Я спрашивал, почему код не работает, но преподаватель сам не понимал этого и предложил поэкспериментировать. Уже 2 часа пытался изменить фрагмент кода, а ошибки те же. В основном компилятор ошибочно воспринимает слово за строковую константу. Подскажите, пожалуйста, что можно сделать в таком случае
#include<cstring>
#include<iostream>
#include<Windows.h>
using namespace std;
struct spisoc {
char *name; // название книги
char *author; // имя автора
int year; // год издания
spisoc *next; // указатель на следующую структуру в списке
};
  // определение массива структур для дополнения с инициализацией//
spisoc stm[] =
{ { "TurboPascal" , "Фаронов В.В.", 2018 },
{ "TurboC++" , "Винер Р.С.", 1991 },
{ "C-C++", "Березин Б.И. " , 2016 } };
spisoc *s;// определение внешнего указателя на вершину списка, он по умолчанию инициирован нулем (null)


text:
Q: Nginx gives 404 error for rails app except the root I have an Ubuntu 12.04 LTS VPS server that serves a static website with Nginx. I would like to set up a rails application that is accesible from the subfolder 'foo'. I use Passenger for serving the rails app
That is how I configured Nginx:
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    passenger_root /home/akarki/.rvm/gems/ruby-1.9.3-p429/gems/passenger-4.0.5;
    passenger_ruby /home/akarki/.rvm/wrappers/ruby-1.9.3-p429/ruby;

    server_names_hash_bucket_size 64;

    include       mime.types;
    default_type  application/octet-stream;

    sendfile        on;

    keepalive_timeout  65;
    gzip  on;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    gzip_types text/plain application/xml text/css text/js text/xml application/x-javascript text/javascript application/json application/xml+rss;
    charset UTF-8;
    error_log /opt/nginx/logs/file.log warn;

    server {
        listen 80;
        server_name www.domain.com;
        return 301 $scheme://domain.com$request_uri;
    }

    server {
        listen       80;
        server_name  domain.com;
        index  index.html index.htm;
        root /srv/www/domain.com;
        passenger_enabled on;
        passenger_base_uri /foo;
        try_files $uri.htm $uri.html $uri/ =404;

        location = / {
            rewrite ^ /de permanent;
        }

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

The static website works as expected but the only URL of the rails app that is accessible is the root under 'http://domain.com/foo'
Any other url gives a 404 error.
Do you have any suggestion how to fix this?

A: The best solution I could find to this after searching a lot was to re-install and configure nginx with phusion passenger
sudo apt-get purge nginx nginx-common nginx-full
sudo apt-get install nginx
sudo nano /etc/nginx/nginx.conf
# uncomment 'passenger_root' & 'passenger_ruby' paths accordingly
sudo nano /etc/nginx/sites-enabled/default
# replace with:
server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    server_name mydomain.com;
    passenger_enabled on;
    rails_env    production;
    root         /home/deploy/myapp/current/public;

    # redirect server error pages to the static page /50x.html
    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   html;
    }
}
sudo service nginx restart


text:
Q: Troubleshooting Program in Python. How to link Qs? I am here to ask another question about the code I am working on. I keep getting invalid syntax error. I asked a similar question on another account and someone answered the question and gave me a code. I edited it but i cannot seem to work it out. My project is to make a troubleshooting program for a mobile company. At the moment this is my code:
CODE:
print("Please answer 'yes' or 'no' to all questions. If you write something  else instead of yes or no then your solution might not come out correctly.")
solution = "Keep holding the power on button until the screen is on. If it  doesn't turn on, contact your phone provider to get a replacement."
solution2 = "Charge your phone fully and switch it on."
solution3 = "Delete some apps, you need a minimum of at least 5 GB of free  memory to run the phone correcly.\nYou are probably out of memory."
sol4 = "Take out everything from the phone and put it in a bag of rice for  24-36 hours to let the rice absorb the water."
sol5 = "Reset your phone."
sol6 = "You need a screen replacement. Get it fixed!"
sol7 = "You need to get your buttons replaced!"
sol8 = "Get a screen replacement or contact your phone provider to get a  phone replacement."
sol9 = "You need to update your phone software and apps."
sol10 = "You dont need to do anything. Your phone doesnt have any problems."
sol11 = "Please update your phone software."

  if input("Did you buy your phone recently? ") == 'yes':
if input("Did your drop your phone? ") == 'yes':
    if input("Did it become wet when you dropped it? ") == 'yes':
        print(sol4)

        else:
        print(sol5)
else:
if input("Has your phone ever been to slow?" ) == 'yes':
    print(sol5)
else:
    if input("Have you got more than 30 apps?? ") == 'yes':
        print(solution3)
        else:

        if input("Is your phone older than two years?") == 'yes':
            print(no_warranty)
        else:
            print(warranty)
    else:
        print(warranty)

So my question is, how can i complete this code and how can i link questions to more questions?
Thanks!

A: Invalid Syntax error is because your code is not indented properly.
In python you have to indent the code the right way to make it work since there is no ; in python to end the code line:
e.g for nested code blocks:
{
    Block 1
....{
    ....Block 2
        {
        ....Block 3
        }
    }
}

Here the 4 dots represent 4 space characters.
for your code you can try like this:
if input("Did you buy your phone recently? ") == 'yes':
    if input("Did your drop your phone? ") == 'yes':
        if input("Did it become wet when you dropped it? ") == 'yes':
            print(sol4)
        else:
            print(sol5)
            ....

Always remember, while using python always proprly indent you code otherwise it will throw invalid syntax error.

A: import time, webbrowser
while True:
    print('Hello, welcome to the phone broke hotline. Please follow the questions and only use 1 word answers.')
    time.sleep(1.25)#program will stop for 1.25 seconds
    print('What phone model do you have?.')
    Q1=input().lower() #makes it all lower case
    if Q1[0]=='i' or Q1[0]=='s' or Q1[0]=='n' :
        if Q1[1]=='p' or Q1[1]=='a' or Q1[1]=='o' :
            if Q1[2]=='h' or Q1[2]=='m' or Q1[2]=='k' :

                yes='y'
                y='yes'
                no='n'
                n='no'
                print('You have chosen ' + '' + Q1+ '' + '')
                prob=input('Did your ' + '' + Q1+ '' + ' get wet?\n').lower()
                if prob == yes or prob == y:
                    print("place the phone in a ziplock bag with dry, uncooked rice for a couple of hours and if that doesn't work please contact the nearest phone repair shop")
                    time.sleep(1)
                    print()
                    break
                elif prob == no or prob == n:
                    print('Did your screen crack?')
                prob2=input().lower()
                if prob2 == yes or prob2 == y:
                    print ('Go to this link to buy new phone parts.\n https://www.replacebase.co.uk/mobile-phone-parts/')
                    webbrowser.open('https://www.replacebase.co.uk/mobile-phone-parts/')
                    time.sleep(1)
                    print()
                    break
                elif prob2 == no or prob2 == n:
                    print('Is your ' + '' + Q1+ '' + '  unresponsive?')
                prob3a=input().lower()
                if prob3a == yes or prob3a == y:
                    prob3b=input('Is Your ' + '' + Q1+ '' + ' off?\n').lower()
                    if prob3b == yes or prob3b == y:
                        print("Turn your " + '' + Q1+ '' + "  on and if it wont turn on put it on charge and if that doesn't work contact your nearest phone repair shop")
                        print()
                        break
                    elif prob3b == no or prob3b == n:
                        print('Go to your nearest phone repair shop')
                        print()
                        break
                elif prob3a == no or prob3a == n:
                    print('Has your ' + '' + Q1+ '' + ' overheated')
                prob4=input().lower()
                if prob4 == yes or prob4 == y:
                    print('place in a cool area for a couple of hours')
                    print()
                    break
                elif prob4 == no or prob4 == n:
                    print('Your ' + '' + Q1+ '' + ' is fine. Thank You for using our services today.')
                    print()
                    print('         ...........')
                    time.sleep(1)
                    break


text:
Q: DocumentDb JOIN not returning result if JOINED property doesn't exist My typical document for a user looks like this:
{
   "id": "SomeGuid",
   "firstName": "John",
   "lastName": "Smith",
   "pet": { "id": "anotherGuid", "name": "Fluffy" }
}

If the user doesn't have a pet, I don't even save the pet property in DocumentDb so the user document would look like this:
{
   "id": "Guid123",
   "firstName": "Jane",
   "lastName": "Doe"
}

I want to get a list of my users along with their pet names so here's my SQL:
SELECT c.id, c.firstName, c.lastName, p.name
FROM c
JOIN p IN c.pet

This SELECT is not returning any data. If I remove the JOIN and get only user information, it works fine.
How do I get all users? If they have a pet, I should get the pet's name, if not, no pet name. Using my example, I want to get a list that looks like this:
[
   { "id": "SomeGuid", "firstName": "John", "lastName": "Smith", "name": "Fluffy" },
   { "id": "Guid123", "firstName": "Jane", "lastName": "Doe" }
]

A: I was able to achieve what I want by NOT using a JOIN.
Here's my SELECT that gives me exactly what I want:
SELECT c.id, c.firstName, c.lastName, c.pet.name
FROM c

The result I get is exactly what I want which is:
[
   { "id": "SomeGuid", "firstName": "John", "lastName": "Smith", "name": "Fluffy" },
   { "id": "Guid123", "firstName": "Jane", "lastName": "Doe" }
]


text:
Q: Laravel 9 api error while trying to get current user from request I am building a blog and I wanted to validate the user that is creating a blog by getting the user data from the request ie, id, name, role, and other stuff then validate if they have the correct role for creating a blog and if so I will use the id to set the user as the author as off now i am trying
            $user = Auth::user();
            var_dump($user);

            $userID = Auth::user()->id;
            var_dump($userID);

to get the user
here is the code below:
public function store(Request $request)
    {
        try {
            $validation = Validator::make($request->all(), [
                'title' => ['required', 'string', 'max:200', 'min:10', 'unique:blogs'],
                'description' => ['required', 'string', 'max:1000', 'min:10'],
                'body' => ['required', 'string',],
                'cat_id' => 'required',
                'published' => 'required',
                'featured' => 'required',
                'guragina' => 'required',
                'image' => 'required',
                'tags' => 'required',
            ]);
            if ($validation->fails()) {
                return response()->json([
                    'success' => false,
                    'msg' => $validation->errors()->all(),
                ], 400);
            } else {

                $user = Auth::user();
                var_dump($user);

                $userID = Auth::user()->id;
                var_dump($userID);

                if ($request->user()->role->WRITER || $request->user()->role->OWNER) {
                    $filename = "";
                    if ($request->file('image')) {
                        $filename = $request->file('image')->store('blogs', 'public');
                    } else {
                        $filename = "null";
                    }
                    $tags = explode(",", $request->tags);
                    $result = Blog::create([
                        'title' => $request->title,
                        'description' => $request->description,
                        'body' => $request->body,
                        'image' => $filename,
                        'cat_id' => $request->cat_id,
                        'published' => $request->published,
                        'featured' => $request->featured,
                        'author' => $userID,
                        'guragina' => $request->guragina,
                        'views' => 0
                    ]);
                    $result->tag($tags);
                } else {
                    return response()->json([
                        'success' => false,
                        'msg' => "You can't write posts",
                    ], 403);
                }

                if ($result) {
                    return response()->json([
                        'success' => true,
                        'msg' => 'Post Added Successfully.'
                    ]);
                } else {
                    return response()->json([
                        'success' => false,
                        'msg' => "Some Problem occurred."
                    ], 400);
                }
            }
        } catch (Exception $e) {
            return response()->json([
                'success' => false,
                'msg' => $e->getMessage(),
            ], 400);
        }
    }


text:
Q: Edit attribute value and add new attribute in xml using python Below is the sample XML file consisting of 3 data-sources. In each data-source there is a  tag having an attribute .
Now, out of 3 data-sources, 2 of them didn't have the  attribute and one of the data-source have  but the value is false.
I want to add the  attribute in the missing one and modify its values to true in data-source where its present.
SAMPLE XML snippets:

A: Using DOM
# import minidom
import xml.dom.minidom as mdom

# open with minidom parser
DOMtree = mdom.parse("Input.xml")
data_set = DOMtree.documentElement

# get all validation elements from data_Set
validations = data_set.getElementsByTagName("validation")

# read all validation from validations
for validation in validations:
    # get the element by tag anme
    use-fast-fail = validation.getElementsByTagName('use-fast-fail')
    # if the tag exist
    if use-fast-fail:
        if use-fast-fail[0].firstChild.nodeValue == "false":
            # if tag value is false replace with true
            use-fast-fail[0].firstChild.nodeValue = "true"
    # if tag does not exist add tag
    else:
        newTag = DOMtree.createElement("use-fast-fail")
        newTag.appendChild(DOMtree.createTextNode("true"))
        validation.appendChild(newTag)

# write into output file
with open("Output.xml", 'w') as output_xml:
   output_xml.write(DOMtree.toprettyxml())

Using simple file read and string search with regex
# import regex
import re

#open the input file with "read" option
input_file = open("intput.xml", "r")
#put content into a list
contents = input_file.readlines()
#close the file
input_file.close()

#loop to check the file line by line
#for every entry - get the index and value
for index, value in enumerate(contents):
    #searches the "value" contains attribute with false value
    if (re.search('<background-validation>false<background-validation/>',value)):
        #if condition true True - changes to desired value
        contents[index] = "<background-validation>true<background-validation/>\n"
    #searches the "value" contains attribute, which always comes just before the desired attribute
    if (re.search('validate-on-match',value)):
        #searches the "value" of next element in the list contains attribute
        if not (re.search('<background-validation>"',contents[index + 1])):
            #if not adding the attribute
            contents.insert(index + 1, "<background-validation>true<background-validation/>\n")

#open the file with "write" option
output_file = open("Output.xml", "w")
#joining all contents
contents = "".join(contents)
#write into output file
output_file.write(contents)
output_file.close()

Note: in the second options, addition of line if does not exist is given in an assumption that all data-source block is in same structure and order, else we may need to check multiple conditions.


text:
Q: Emacs, getting the output of the echo area How can I insert directly the text displayed in the echo area? (also wrongly called the minibuffer).
When I for example run (+ 2 2) in a buffer and execute it with C-x C-e it correctly displays the result '2' in the echo area. There is also a '2' in the Messages buffer. I'd like this '2' inserted below the line executed, in the same buffer, or something like that.
Is there a command to, for example, pipe the echo area into the buffer or copy the last line of the Messages buffer into the present working buffer?

A: In lisp-interaction-mode which is the default mode for the *scratch* buffer you can use eval-print-last-sexp bound to C-j.
Edit:
In any buffer you can switch to lisp-interaction-mode with M-x: lisp-interaction-mode [RET]
Now C-j should be bound by default to eval-print-last-sexp unless the binding is shadowed by another mode.
You can check the quick description of the current major-mode with C-h m.
If it is shadowed or simply not bound you can eval
(global-set-key (kbd "C-c p") 'eval-print-last-sexp)
with C-x C-e. That will bind the command to C-c p.
To make the change permanent write it in your .emacs file.

A: You need to use one of the EMACS insert commands. To accomplish what you illustrated in your simple example you would need to do the following.
(insert-string (number-to-string (+ 2 2)))


text:
Q: Self join in ruby on rails I am having trouble with a self join statement in Ruby on Rails.
Well, it is kind of complicated and irritating but what I want to get is:
5 jobs out of the JobCompact table that has the same foreign key build_compact_id and either the language "ruby" or "rubinius"
My query looks as follows:
JobCompact.all(
:joins => "JOIN job_compacts AS jobs2 ON job_compacts.build_compact_id = jobs2.build_compact_id",
:conditions => ["job_compacts.language = ? AND jobs2.language=?", 'ruby', 'rubinius'],
:limit => 5)

In general that seems to be working but only return me objects out of the first table. The second table (jobs2) is not shown in the result set. I would like to get a collection with all job_compacts that match the given condition.
I hope I could explain my problem, otherwise do not hesitate to ask me. Thanks in advance!


text:
Q: Angularjs Progress circle not working on dynamic input when I try to give input value to progress circle in Angular js, only the value(20%) is displayed and loader color is not shown. please refer the attached screenshot.
The Angular progress works fine if the input value(20%) is given directly given in HTML.
But when try to bind value{{count}} its showing only the value, but some css is missing and the progress color is not displayed.
$scope.count= 20;
(function($) {
    $.fn.loading = function() {

        var backgroundColor = '#ccc';
        var progressColor = '#1abc9c';
        var percent = 90;
        var duration = 2000;

        var DEFAULTS = {
            backgroundColor : '#ccc',
            progressColor : '#1abc9c',
            percent : 90,
            duration : 2000
        };

        $(this)
                .each(
                        function() {
                            var $target = $(this);

                            var opts = {
                                backgroundColor : $target.data('color') ? $target
                                        .data('color').split(',')[0]
                                        : DEFAULTS.backgroundColor,
                                progressColor : $target.data('color') ? $target
                                        .data('color').split(',')[1]
                                        : DEFAULTS.progressColor,
                                percent : $target.data('percent') ? $target
                                        .data('percent') : DEFAULTS.percent,
                                duration : $target.data('duration') ? $target
                                        .data('duration') : DEFAULTS.duration
                            };
                            // console.log(opts);

                            $target
                                    .append('

'
                                            + opts.percent + '%
');

                            $target.find('.background').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.left').css('background-color',
                                    opts.backgroundColor);
                            $target.find('.rotate').css('background-color',
                                    opts.progressColor);
                            $target.find('.right').css('background-color',
                                    opts.progressColor);

                            var $rotate = $target.find('.rotate');
                            setTimeout(function() {
                                $rotate.css({
                                    'transition' : 'transform ' + opts.duration
                                            + 'ms linear',
                                    'transform' : 'rotate(' + opts.percent
                                            * 3.6 + 'deg)'
                                });
                            }, 1);

                            if (opts.percent > 50) {
                                var animationRight = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-end';
                                var animationLeft = 'toggle '
                                        + (opts.duration / opts.percent * 50)
                                        + 'ms step-start';
                                $target.find('.right').css({
                                    animation : animationRight,
                                    opacity : 1
                                });
                                $target.find('.left').css({
                                    animation : animationLeft,
                                    opacity : 0
                                });
                            }
                        });
    }
})(jQuery);

.position {
  float: left;
  margin: 20px 0px;
}

.progress-bar-container {
  width: 100px;
  margin: 0 auto;
}

.pb-heading {
    border: 0px;
    margin-bottom: -10px;
}

.progress-bar {
  position: relative;
  height: 100px;
  color: #111;
  background-color: transparent;
  -webkit-box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
  box-shadow: inset 0 0px 0 rgba(0,0,0,.15);
}

.progress-bar div {
  position: absolute;
  height: 100px;
  width: 100px;
  border-radius: 50%;
}

.progress-bar div span {
    position: absolute;
    font-family: Arial;
    font-size: 20px;
    line-height: 80px;
    height: 75px;
    width: 75px;
    left: 12.5px;
    top: 12.5px;
    text-align: center;
    border-radius: 50%;
    background-color: white;
}

.progress-bar .background { background-color: #b3cef6; }

.progress-bar .rotate {
  color: red;
  clip: rect(0 50px 200px 0);
  background-color: #4b86db;
}

.progress-bar .left {
  clip: rect(0 50px 200px 0);
  opacity: 1;
  background-color: #b3cef6;
}

.progress-bar .right {
  clip: rect(0 50px 200px 0);
  transform: rotate(180deg);
  opacity: 0;
  background-color: #4b86db;
}
 @keyframes
toggle {  0% {
 opacity: 0;
}
 100% {
 opacity: 1;
}
}

                            Total Uploaded this Week

                            Successfully Uploaded

A: I believe that changing your progress-bar data-percent={{count}} to have quotes around will fix your issue:

Also I'm not sure about your logic since you didn't post any of you angularjs code, remove ng-class="rotate" and put just  class="rotate" ng-class will take expression so it will think that rotate is some property on $scope and you would need to set it up like:
$scope.rotate='rotate'
but using:
class="rotate"

should work fine.
Because all of this is just a workaround and messy approach, I would advise to check this and work it out AngularJS way:
http://jtblin.github.io/angular-chart.js/


text:
Q: ReadDirectoryChangesW seems to be missing events I've been trying to get ReadDirectoryChangesW to monitor a subtree for file changes, but I have found that I am getting inconsistent results.  The following is a self contained test case which illustrates the problem.  When I run this it sometimes produces:
A : Created
C : Updated
A : Deleted

Another time it might produce:
A : Created
B : Updated
C : Updated
A : Deleted

I create a huge buffer, and the number of files being changed is very small (3 files).
The code:
import os, sys, time, threading
import win32file, win32event, win32con, pywintypes

class ChangeFiles ( threading.Thread ) :
    def run( self ) :
        files = [ 'A', 'B', 'C' ]
        time.sleep( 1 )
        for path in files : f = open( path, 'w' ); f.write( 'mooo' ); f.close()
        time.sleep( 0.5 )
        for path in files : os.remove( path )

ChangeFiles().start()

FILE_LIST_DIRECTORY = 0x0001

handle = win32file.CreateFile (
  '.',
  FILE_LIST_DIRECTORY,
  win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
  None,
  win32con.OPEN_EXISTING,
  win32con.FILE_FLAG_BACKUP_SEMANTICS | win32file.FILE_FLAG_OVERLAPPED,
  None
)

buffer = win32file.AllocateReadBuffer( 1024 * 64 )
overlapped = pywintypes.OVERLAPPED()
overlapped.hEvent = win32event.CreateEvent( None, 0, 0, None )

readFlags = win32con.FILE_NOTIFY_CHANGE_FILE_NAME  | \
            win32con.FILE_NOTIFY_CHANGE_DIR_NAME   | \
            win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES | \
            win32con.FILE_NOTIFY_CHANGE_SIZE       | \
            win32con.FILE_NOTIFY_CHANGE_LAST_WRITE | \
            win32con.FILE_NOTIFY_CHANGE_SECURITY

ACTIONS = { 1 : "Created", 2 : "Deleted", 3 : "Updated" }

while 1 :
    win32file.ReadDirectoryChangesW( handle, buffer, False, readFlags, overlapped )

    rc = win32event.WaitForSingleObject( overlapped.hEvent, 200 )

    if rc == win32event.WAIT_OBJECT_0 :
        nbytes = win32file.GetOverlappedResult( handle, overlapped, True )
        if nbytes > 0 :
            for action, file in win32file.FILE_NOTIFY_INFORMATION( buffer, nbytes ) :
                print '%s : %s' % ( file, ACTIONS.get ( action, "Unknown" ) )
        else :
            print 'no bytes'
            break
    elif rc < 0 :
        print 'Error: %d' % win32api.GetLastError()
        break

A: The issue here is that the timeout you're passing to WaitForSingleObject is very low, so the function tends to time out before you get notified about the events. Your code does not check that condition, hence you see no output (try testing for rc > 0, too).
You can fix this by passing the value of INFINITE (i.e. 0xFFFFFFFF) to WaitForObject.


text:
Q: Как написать тест кейсы по уже готовому продукту? В тестовом задании на позицию Junior QA, кроме всего прочего дали задание написать тест кейсы по уже готовому продукту. Подскажите ,пожалуйста, как поступить более правильно. Искать именно ошибки, или можно не находить уже существующие баги, а придумать их самому?
Ведь насколько я понимаю смысл этого не найти ошибки, а увидеть мое понимаени?

A: Могу предположить на основании тех кейсов, которые мы давали своим тестрировщикам. (Мы правда для этого писали специальное приложение, с багами, и отдавали тестерам, но то так).
Цель тестировщика не найти баги (как ни странно это не звучит), а протестировать функционал. Соответсвенно тест кейс не обязательно должен находить баг (особенно если его нет), он должен проверять что все приложение работает так, как оно задумывается.
Банальный вариант на авторизацию:

*

*Открыть авторизацию

*Вбить имя

*Вбить цифру

*Вбить имя из 70 тысяч символов

*Вбить "ничего"

И так далее.. Багов тут может и не быть (и не должно быть), но ключевое это идея что функционал работает.


text:
Q: testing database results to set a checkbox as checked I want to output a checked attribute on my checkboxes if the data appears in my database.
i tried doing in_array() but it didn't work because of the values (see Database)
I don't know how i should output them nicely
PHP CODE:
    $general_list = "";
if($row['f_general'] == 'Bar, '){
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Bar, \" checked=\"checked\"/>Bar";
}else{
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Bar, \"/>Bar,";
 }
if($row['f_general'] == 'Restaurant,'){
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Restaurant, \" checked=\"checked\"/>Restaurant,";
}else{
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Restaurant, \"/>Restaurant,";
 }
if($row['f_general'] == 'Coffee Shop,'){
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Coffee Shop, \" checked=\"checked\"/>Coffee Shop,";
}else{
    $general_list .= "<input type=\"radio\" name=\"general[]\" value=\"Coffee Shop, \"/>Coffee Shop,";
 }

My database values are stored like this:
Bar, Restaurant, Coffee Shop, Concierge,

HTML CODE:
<input type="checkbox" name="general[]" value="Bar, "/>Bar,
<input type="checkbox" name="general[]" value="Restaurant, "/>Restaurant,
<input type="checkbox" name="general[]" value="Coffee Shop, "/>Coffee Shop,
<input type="checkbox" name="general[]" value="Concierge, "/>Concierge,
<input type="checkbox" name="general[]" value="Business Center, "/>Business Center,
<input type="checkbox" name="general[]" value="Salon, "/>Salon,

A: Don't add comma with value.You can use implode to store value like
implode(",",$_POST[general]);

and explode for display:
explode(",",$_POST[general]); //it will return array

A: It's not clear how your data is coming out of the database, but if you are storing it as a comma-separated string: don't. There are better ways to do it--use separate database rows for each of the entities in $row['f_general'], i.e.
f_general
Bar
Restaurant
Coffee Shop
(etc.)

You can then do a query and put all the items in the field f_general into an array, rather than having to parse a comma-separated string.
Since you do have the string, parse it to create an array:
$db_row = explode(", ", $row['f_general']);

You can then make your code a lot more compact and easy to maintain by doing the following:
# set up an array with all the checkboxes in it:
$items = array('Bar', 'Restaurant', 'Coffee Shop', 'Concierge', 'Business Center', 'Salon');

$general_list = '';

# go through each item in the array
foreach ($items as $i) {
    # see if that item is in the data from the database
    if ( in_array($i, $db_row) ) {
        $general_list .= '<input type="radio" name="general[]" value="'
        . $i . '" checked="checked" />' . $i . '';
    }
    else {
        $general_list .= '<input type="radio" name="general[]" value="'
        . $i . '" />' . $i . '';
    }
}


text:
Q: Android RelativeLayout align center of one view on top right corner of another view I have experience with RelativeLayout but I've never run across a way to solve the problem I am presented with (aside from hard coding margin values, which I want to avoid.)
I want to try to create something like the following image in a RelativeLayout:

The box is its own View and I want to get the View that contains the orange circle to be centered on the top right corner of the View that contains the blue box.
I tried with android:alignTop="boxView" and android:alignRight="boxView" but that put my orange circle completely within my box. I want it to be so that the circle is centered above the top right corner of the box.
Anybody know how I can get that outcome with a RelativeLayout? preferably without having to hardcode margins away from the edge of the screen for the orange dot view.

A: This code creates what you are looking for but does use margins. Now you can set the margin in code if this is a dynamic structure you are creating. As you can see I used negative margins to move the upper right shape outside of the blue box. These need to be half the height of the circle you are trying to move. You can do all of this in code to center the circle in the upper right corner.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/linearLayout1"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:background="#0000FF"
            android:orientation="vertical" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="26dp"
            android:layout_height="26dp"
            android:layout_alignRight="@+id/linearLayout1"
            android:layout_alignTop="@+id/linearLayout1"
            android:layout_marginRight="-13dp"
            android:layout_marginTop="-13dp"
            android:background="#FF00FF"
            android:orientation="vertical" >
        </LinearLayout>

    </RelativeLayout>

A: Best and proper way to do:
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="@dimen/_10sdp">

    <View
        android:id="@+id/viewBox"
        android:layout_width="35dp"
        android:layout_height="35dp"
        android:background="@color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent" />

    <View
        android:layout_width="15dp"
        android:layout_height="15dp"
        android:src="@drawable/ic_close"
        app:layout_constraintBottom_toTopOf="@+id/viewBox"
        app:layout_constraintLeft_toRightOf="@+id/viewBox"
        app:layout_constraintRight_toRightOf="@+id/viewBox"
        app:layout_constraintTop_toTopOf="@+id/viewBox" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: You could use ConstraintLayout circular positioning, just align your view on 45 degrees angle and adjust radius:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:background="@color/colorAccent"
        android:id="@+id/view"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:background="@color/colorPrimary"
        android:id="@+id/alignedView"
        android:layout_width="30dp"
        android:layout_height="30dp"
        app:layout_constraintCircle="@id/view"
        app:layout_constraintCircleAngle="45"
        app:layout_constraintCircleRadius="60dp" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: It's very easy to acheive that using constraint layout.
just set start and end constraint of circle to the same point and top and bottom to the same point (eg top right corner of textview) like below:
<TextView
    android:id="@+id/newWarningLabel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="left|center"
    android:lines="2"
    android:text="testtest"
    android:textColor="@color/white"
    android:textSize="12sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"/>

<TextView
    android:id="@+id/alertCounter"
    android:layout_width="20dp"
    app:layout_constraintStart_toStartOf="@id/newWarningLabel"
    app:layout_constraintEnd_toStartOf="@id/newWarningLabel"
    app:layout_constraintTop_toTopOf="@id/newWarningLabel"
    app:layout_constraintBottom_toTopOf="@id/newWarningLabel"
    android:layout_height="20dp"
    android:gravity="center"
    android:textColor="@color/white"
    android:textStyle="bold"
    android:textSize="10sp"
    android:visibility="visible"
    android:text="1"
    android:background="@drawable/red_circle"/>


text:
Q: How do you force a job to prompt the user for variables in a parallel pipeline? I have a very basic Gitlab CICD yaml file that is supposed to run two jobs on completion of another job. I'd like one job to automatically set a variable, while the other job prompts the user to define one. These jobs are called auto and manual respectively. However, when I run the file below, the manual step just doesn't set anything and continues to run without prompting  the user for variables. This does make sense, but how exactly do I force this job to prompt the user for variable definitions?
stages:
- A
- B

.template
  script:
    - echo ${MY_VARIABLE}

setup:
  stage: A
  script:
    - echo "do nothing yet"
  allow_failure: false
  when: manual

auto:
  stage: B
  variables:
    MY_VARIABLE: "I am automatically set"
  when: on_success
  dependencies:
    - setup

manual:
  stage: B
  when: manual
  dependencies:
    - setup

Currently, the above results in:
auto output
I am automatically set

manual output

What I want:

UPDATE: It doesn't look like there is a way to force the above.