text:
Q: Calculate user formula from from account number I have two tables, the first is dbo.formula
Id | Poste  | Calculation | Montant
---+--------+-------------+--------
 1 | Achats | 3801%+381%  | .....
 2 | Tva    | 446%-445%   | ....
 3 | Tiers  | 411%+401%   | ....

The second table is dbo.value
Compte  | Solde
--------+-------
 380000 | 400.00
 380100 | 500.00
 381100 | 200.00
 381200 | 100.00
4456600 | 100.00
4455400 | 150.00

I need to be the result in the first table in field Montant like
 1 | Achats | 3801%+381%   |..... = 500.00 + 200.00 + 100.00 = 800.00
 2 | Tva    | 446%-445%   |.... = 100.00 - 150.00 = -50.00

I tried a request but it works only the 3 beginning numbers of account, and it works with + only.
select f.ID, f.Poste, sum(v.Solde) total
from formula f
inner join value v
    on charindex('+' + left(v.Compte, 3) + '%', '+' + f.Calculation) > 0
group by f.ID, f.Poste

I want a request to work from 1 to 8 digits of number account, and also work with +, -, *, /.

A: Personally, I'd start by creating a new table to store your calculation logic in a more structured manner instead of a big varchar:
create table calcs
(
    FormulaId int,
    operator varchar(1),
    pattern varchar(10)
)

insert into calcs
    select
        Id as FormulaId,
        case when left([value],1) like '[^0-9]' then left([value],1) else '+' end as operator,
        case when left([value],1) like '[^0-9]' then right([value],len([value])-1) else [value] end + '%' as pattern
    from formula
    cross apply string_split(Calculation, '%')
    where [value] <> ''

select * from calcs

Results:
/--------------------------------\
| FormulaId | operator | pattern |
|-----------|----------|---------|
|     1     |     +    | 3801%   |
|     1     |     +    | 381%    |
|     2     |     +    | 446%    |
|     2     |     -    | 445%    |
|     3     |     +    | 411%    |
|     3     |     +    | 401%    |
\--------------------------------/

Now, you can use this table to assist in building the complete formula string you want:
select
    f.Id,
    f.Poste,
    f.Calculation,
    (
        SELECT c.operator + convert(varchar(20),v.Solde)
        from calcs c
        join [value] v on v.Compte like c.pattern
        where c.FormulaId = f.Id
        for xml path('')
    )
    + ' = ' + convert(varchar(20),
                  sum(case when c2.operator = '+' then v2.Solde else 0 end)
                - sum(case when c2.operator = '-' then v2.Solde else 0 end)) as Montant
from formula f
left join calcs c2 on c2.FormulaId = f.Id
left join [value] v2 on v2.Compte like c2.pattern
group by f.Id, f.Poste, f.Calculation

Results:
/------------------------------------------------------------\
| Id | Poste  | Calculation | Montant                        |
|----|--------|-------------|--------------------------------|
| 1  | Achats | 3801%+381%  | +500.00+200.00+100.00 = 800.00 |
| 2  | Tva    | 446%-445%   | -100.00-150.00 = -250.00       |
| 3  | Tiers  | 411%+401%   | NULL                           |
\------------------------------------------------------------/

If you wanted to tidy up the leading + symbols where the first value is positive, you could wrap the whole thing in an additional SELECT, or use a CTE:
with newFormula (Id, Poste, Calculation, Montant) as
(
    select
        f.Id,
        f.Poste,
        f.Calculation,
        (
            SELECT c.operator + convert(varchar(20),v.Solde)
            from calcs c
            join [value] v on v.Compte like c.pattern
            where c.FormulaId = f.Id
            for xml path('')
        )
        + ' = ' + convert(varchar(20),
                      sum(case when c2.operator = '+' then v2.Solde else 0 end)
                    - sum(case when c2.operator = '-' then v2.Solde else 0 end)) as Montant
    from formula f
    left join calcs c2 on c2.FormulaId = f.Id
    left join [value] v2 on v2.Compte like c2.pattern
    group by f.Id, f.Poste, f.Calculation
)
select
    Id,
    Poste,
    Calculation,
    case when left(Montant,1) = '+'
        then right(Montant,len(Montant)-1)
        else Montant
    end as Montant
from newFormula

Results:
/------------------------------------------------------------\
| Id | Poste  | Calculation | Montant                        |
|----|--------|-------------|--------------------------------|
| 1  | Achats | 3801%+381%  | 500.00+200.00+100.00 = 800.00  |
| 2  | Tva    | 446%-445%   | -100.00-150.00 = -250.00       |
| 3  | Tiers  | 411%+401%   | NULL                           |
\------------------------------------------------------------/


text:
Q: System freezes when trying to install Ubuntu 18.04 My Dell Inspiron 7567 Gaming laptop freezes when trying to install Ubuntu 18.04 for the first time.
I downloaded the Ubuntu 18.04 .iso file from the official Ubuntu website, used Rufus to burn the ISO into my 16GB Cruiser Glide USB stick, while following all the steps in the Ubuntu Installation guide.
I booted off of the USB drive, went into language, selected my language, but after a few moments, the mouse will work but only that. Everything else freezes. I tried again in run Ubuntu only mode. It freezes after some period of time. The mouse moves, but everything else is frozen.
I tried re-burning the drive, but it failed.
I tried acpi=off, but it also failed.
I noticed some error messages while booting, the image will be very shaky / unclear, but I think it will provide just enough information. The image and video is attached.
System specs
  OS Name: Microsoft Windows 10 Pro
  Version: 10.0.17134 Build 17134
  Other OS: Description Not Available
  OS Manufacturer: Microsoft Corporation
  System Manufacturer: Dell Inc.
  System Model: Inspiron 15 7000 Gaming
  System Type: x64-based PC
  System SKU: 0798
  Processor: Intel(R) Core(TM) i7-7700HQ CPU @ 2.80GHz, 2801 Mhz, 4 Core(s), 8 Logical Processor(s)
  BIOS Version/Date: Dell Inc. 1.1.0, 2017-08-17
  SMBIOS Version: 3.0
  Embedded Controller Version: 255.255
  BIOS Mode: UEFI
  BaseBoard Manufacturer: Dell Inc.
  BaseBoard Model: Not Available
  BaseBoard Name: Base Board
  Platform Role: Mobile
  Secure Boot State: On
  PCR7 Configuration: Elevation Required to View
  Windows Directory: C:\Windows
  System Directory: C:\Windows\system32
  Boot Device: \Device\HarddiskVolume2
  Hardware Abstraction Layer Version = "10.0.17134.1"
  Installed Physical Memory (RAM): 16.0 GB
  Total Physical Memory: 15.9 GB
  Available Physical Memory: 12.0 GB
  Total Virtual Memory: 18.7 GB
  Available Virtual Memory: 13.4 GB
  Page File Space: 2.88 GB
  Page File: C:\pagefile.sys
  Kernel DMA Protection: Off
  Virtualisation-based security: Not enabled
  Device Encryption Support: Elevation Required to View
  Hyper-V - VM Monitor Mode Extensions: Yes
  Hyper-V - Second Level Address Translation Extensions: Yes
  Hyper-V - Virtualisation Enabled in Firmware: Yes
  Hyper-V - Data Execution Protection: Yes
  Drive partitioned in Disk 1 (D: drive), TOSHIBA MQ01ABD100, 5400RPM HDD, for 160000MB, or 156.25GB, unallocated.
I took out my personal information that is not relevant to solving the issue.
Link to Google Drive for error messages: https://drive.google.com/folderview?id=1e13ZL06StVl6Yx6d9iY9Ou0qweC89Rud

A: The rufus program uses two methods to format a drive: iso and dd. The iso option uses legacy bios and dd uses UEFI. Whatever option you used first to format your drive, try using the other option. If you are having trouble formatting your flash drive, rufus should reformat it for you. If that does not work, try to boot up from it again and when it displays a keyboard and a person at the bottom of the screen, hit the tab button. Then hit enter on "English" and press enter again on "Try Ubuntu without installing." When the desktop appears, click the "Install Ubuntu" icon on the desktop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I implement extension helper methods as an abstract class with variable parameters? To cut down on reused code throughout my repository which gets values from another library, I wanted to create extension methods for "parsing"(for lack of a better word) one class to another.  How do I implement abstract methods with different parameters.
I can't find anything that answers my question, and I'm not sure it can even be done.
Instead of having something like this in multiple places.
var list = _library.GetList();
var model = list.Select(o => new ClassA()
{
   ID = o.ID,
   Name = o.Name
}).ToList<ClassA>();

I want extension methods so I can call something like
var list = _library.GetList();
var model = ExtensionClass.ParseMany(list);

But, I want to base this off an abstract class so it can be reused by mutliple different classes, so I have
public abstract class Parser<U, T> where T : class where U : class
{
   public abstract T ParseOne(U parser);
   public abstract IEnumerable<T> ParseMany(IEnumerable<U> parser);
}

public class ParseA<ClassA, ClassADTO>
{
   public override ClassA ParseOne(ClassADTO parser){ // }
}

But it doesn't seem that my parameter that is passed in is the actual object, it says it's a KeyValuePair and now I'm lost.
I expect to able to return a new instance based on my parameter, basically what I already do in my code multiple times.

A: I guess you can have a generic parser using Func. I just wrote a sample and hope it helps you.
public class ClassA
{
    public int SomeNumber { get; set; }

    public string SomeString { get; set; }
}

public class ClassB
{
    public int OtherNumber { get; set; }

    public string OtherString { get; set; }
}

public static class ExecuteParsingFunction
{
    public static TDestiny Parse<TOrigin, TDestiny>(TOrigin origin,
                                Func<TOrigin, TDestiny> parserFunction)
    {
        return parserFunction(origin);
    }
}

public static class ParsingFunctions
{
    public static ClassB ParseAToB(ClassA a)
    {
        return new ClassB { OtherNumber = a.SomeNumber, OtherString = a.SomeString };
    }

    public static IEnumerable<ClassB> ParseManyAToB(IEnumerable<ClassA> aCollection)
    {
        foreach(var a in aCollection)
            yield return ParseAToB(a);
    }
}

public void Sample()
{
    var a = new ClassA { SomeNumber = 1, SomeString = "Test" };
    var manyAs = new List<ClassA> { a };

    var b = ExecuteParsingFunction.Parse(a, ParserFunctions.ParseAToB);
    var manyBs = ExecuteParsingFunction.Parse(manyAs, ParserFunctions.ParseManyAToB);
}


text:
Q: How to I prevent user from typing the same tag in the Textext textarea I am using Textext plugin for the tags. What am trying to achieve is to prevent multiple duplicates of the items(tags) typed in the textarea.

As you can see in the above pic the tag "C" is typed twice. It want to prevent the user from typing the duplicates. How do I do this?
I came across the filter plugin But its functionality is little different from what I want.
I am sure there is some good way to achieve this. Please help!

A: Use the below to get the inside text:
var txt = document.getElementById('textarea');
var insideText = $(txt).parent().children('div').text();

The text will be in concatenated form. So, you need to take care when the user deletes the tag or creates a new tag.
To test the above code, run it in console tab of developer tool of the browser.


text:
Q: How to sort object using java 8 streams I am using the stream API in java 8 to handle my collections. However, I am wondering what would be an elegant way to sort my objects in a given order, using this API.
SortedCollection = inputCollection.stream()
    .map(e -> {
        return new Element(e.id, e.color);
    }).collect(Collectors.toList());

Here I would like to sort the elements that have been mapped, using the id
attribute.
Any idea ? Thanks !

A: Simply use Stream#sorted as follows with the name of your getter method for the Element's ID.
inputCollection.stream()
               .map(e -> new Element(e.id, e.color))
               .sorted(Comparator.comparing(Element::getId))
               .collect(Collectors.toList());

A: Full detail example: May be helpful for the starter on Stream class.
  public class Employee {
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }

        int salary;

        public Employee(String n, int s) {
            this.name = n;
            this.salary = s;
        }

        @Override
        public String toString() {
            return "[" + name + ", " + salary + "]";
        }

        public static void main(String[] args) {
            List<Employee> list = new ArrayList<Employee>() {
                {
                    add(new Employee("Joe", 50000));
                    add(new Employee("Jim", 75000));
                    add(new Employee("Tom", 80000));
                    add(new Employee("Jim", 70000));
                    add(new Employee("Steve", 55000));
                    add(new Employee("Jim", 100000));
                    add(new Employee("Joe", 59000));
                    add(new Employee("Rich", 88000));
                }
            };
            List<Employee> listSorted = new ArrayList<Employee>();
            Comparator<Employee>  NameCommparator = Comparator.comparing(Employee::getName);
            listSorted = list.stream().sorted(NameCommparator).collect(Collectors.toList());

            System.out.println(listSorted);

//sorting on descending order
            Comparator<Employee>  SalaryCommparator = Comparator.comparing(Employee::getSalary);
            listSorted = list.stream().sorted(SalaryCommparator.reversed()).collect(Collectors.toList());
            System.out.println(listSorted);

        }
    }

A: Maybe try this
SortedCollection = inputCollection.stream()
                .map(e -> {
                    return new Element(e.id, e.color);
                })
                .collect(Collectors.collectingAndThen(Collectors.toList(), l -> l.sort(yourComparator)));


text:
Q: Call JS function once hidden input has value from session attribute How can I be able to automatically call a JS function once an assigned session attribute passes a value to a hidden input field in JSP. Kindly see below:
Java Class:
session.setAttribute("activity1", 1);
session.setAttribute("activity2", 0);

JSP:

        Activity1
        Activity2

<input type="hidden" id="act1" value="${sessionScope.activity1}"/>
<input type="hidden" id="act2" value="${sessionScope.activity2}"/>

Javascript:
 $('#act1').change(function(){
        if($(this).val() == '1'){
            $('#actDiv1').css('background-color', 'green');
        }else{
            $('#actDiv1').css('background-color', 'red');
        }
 });
 $('#act2').change(function(){
        if($(this).val() == '1'){
            $('#actDiv2').css('background-color', 'green');
        }else{
            $('#actDiv2').css('background-color', 'red');
        }
 });

Once the value of the hidden field contains a value passed from the session attribute, it will automatically perform the script. So meaning, upon passing of the value, call js function immediately.
Greatly appreciate your help, let me know if there are any other clarifications on this.

A: On page load, input id="act1" will get the value from session. After that, even if the value in session attribute changes, it wont change the value in input id="act1".
Solution : I am assuming you are using some js to change the value in session variable. You can manually set the new value into hidden input and then trigger the change function.
$('#hidden_input').val('new_value').trigger('change');


text:
Q: Создать линейный, однонаправленный список всех чисел. Добавить последний чётный элемент в список после каждого нечётного элемента Помогите пожалуйста, я не знаю как код дописать, а точнее добавить последний чётный элемент в список после каждого нечётного элемента
#include"iostream"

using namespace std;

struct SingleList {
    int data;
    SingleList* next;
};

SingleList* Make_SingleList(SingleList* head, int n) {
    head->next = NULL;
    for (int i = 0; i < n; i++) {
        SingleList* newItem = new SingleList;
        cout << "Enter data - " << i + 1 << "=";
        cin >> newItem->data;
        newItem->next = head;
        head = newItem;
    }
    return head;
}

void Print_SingleList(SingleList* head) {
    SingleList* current = head;
    while (current->next != 0)
    {
        cout << current->data << "  ";
        current = current->next;
    }
    cout << endl;
}

SingleList* InsertItemSingleList(SingleList* head, int DataItem) {
    SingleList* Current = head;
    while (Current->next != NULL)
    {
        if (Current->data < 0) {
            SingleList* NewItem = new SingleList;
            NewItem->data = DataItem;
            NewItem->next = Current->next;
            Current->next = NewItem;
        }
        Current = Current->next;
    }
    return head;
}

void DeleteSingleList(SingleList* head) {
    if (head != NULL) {
        DeleteSingleList(head->next);
        delete head;
    }
}

int main()
{
    int n;
    cout << "Enter n=";
    cin >> n;
    SingleList* head = new SingleList;
        head = Make_SingleList(head, n);
    cout << "make list=";
    Print_SingleList(head);
        head = InsertItemSingleList(head, "последнее чётное число");
    cout << "list with inserts=";
    Print_SingleList(head);
    cout << "Delete list" << endl;
    DeleteSingleList(head);
    Print_SingleList(head);
    return 0;
}


text:
Q: why my spring boot application doesn't execute bash (.sh) file i run a script shell from springboot application , it show this error when i run the spring application :
Cannot run program "src/main/java/com/springapp/app/bach/scripts/test.sh": CreateProcess error=193, %1 is not a valid Win32 application
#!/bin/bash

echo "Hello World !"

this is the controller which execute the commande :
    @Override
public String runScript(String pathScript) throws IOException, InterruptedException {
    try {
        Process p = Runtime.getRuntime().exec(pathScript);

        InputStream is = p.getInputStream();
        StringBuffer sb = new StringBuffer();

        int i = 0;
        while ((i = is.read()) != -1) {

            sb.append((char) i);

        }

        return sb.toString();
    }
    catch (IOException e){
        e.printStackTrace();
    }
}

the main applicattion :
    String message = runScript.runScript("src/main/java/com/innovsys/qopsbe/bach/scripts/test.sh");

    System.out.println(message);

I did my research on google i found a solution, they told me to put a "cmd" just before the path of the file
but it didn't work for me !!


text:
Q: Trigger jQuery event and know if and Checkbox in list/array is checked The code below is a cut down version of the page, but you see that it will iterate through a list and produce a checkbox for each item in the list.
What I want to know:

*

*How do I trigger a jQuery event when ANY of the checkboxes are clicked (either making them checked or unchecked)?

*What jQuery code do I need to then look at the list of checkboxes produced by the below code and then make a button (e.g. with id="DeleteSelected" ) visible if any are checked, or hide the button if they are all unchecked?

<s:form action="manageQuestions" >
    <s:iterator value="questions" id="currentQuestion">
        <s:checkbox name="questionCheck" id="ch-%{id}" value="selected" fieldValue="%{id}"/>
    </s:iterator>
</s:form>

I'm such a jQuery dunce that I know that I need to put:
<script>

</script>

there at the end but that's all I know.  I don't know if I need to put:
$(document).ready(function() {
    //something here
}

or if I don't need the document ready etc. at all.

A: Try this: http://jsbin.com/AfEriqe/1/edit
$(document).ready(function() {
  var checkboxes = $('input[type=checkbox]');
  $(checkboxes).on('change', function() {
    console.log('checkbox changed');
    if($(checkboxes).is(':checked')) {
      console.log('at least one checked');
    }
  });
});

A: I wish to add to Vlad's answer, to change the css class of the element that I wanted to show/hide, the condition check was extended to:
if($(checkboxes).is(':checked')) {
    $("#deleteSelected").attr('class', 'visible');
} else {
    $("#deleteSelected").attr('class', 'hidden');
}

where 'deleteSelected' is the id of the element to show/hide


text:
Q: RNetlogo / NLstart doesn't do anything I am trying to use Netlogo via R using the following code:
library(RNetLogo)
my.netlogo1 <- "my.netlogo1"

nl.path <- "C:/Program Files/NetLogo 6.1.1/app"
NLStart(nl.path, gui = FALSE,
nl.obj = my.netlogo1, nl.jarname='netlogo-6.1.1.jar')

And I get the following message:
java.lang.NoClassDefFoundError: org/nlogo/workspace/Controllable
    at java.base/java.lang.Class.forName0(Native Method)
    at java.base/java.lang.Class.forName(Class.java:416)
Caused by: java.lang.ClassNotFoundException
    at RJavaClassLoader.findClass(RJavaClassLoader.java:383)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:588)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 2 more

I heard it was because of a compatibility issue with Netlogo6 but that it had now been solved. Could someone say what I'm doing wrong?


text:
Q: Count all observed factor levels, also those that aren't observed We have the DF
df <- data.frame(group=as.factor(rep(c("UP","DOWN"),6)),variables=(rep(c("sex","smoke","sport"),each=4))
             ,values=as.factor(c(1,1,1,0  ,1,1,0,0, 1,1,1,1)))

   group variables values
1     UP       sex      1
2   DOWN       sex      1
3     UP       sex      1
4   DOWN       sex      0
5     UP     smoke      1
6   DOWN     smoke      1
7     UP     smoke      0
8   DOWN     smoke      0
9     UP     sport      1
10  DOWN     sport      1
11    UP     sport      1
12  DOWN     sport      1
>

Now I want to know all counts of all levels
library(plyr)

This command does almost perfectly what I want
count(df, c("variables", "group", "values"))

 variables group values freq
1      sex  DOWN     0    1
2      sex  DOWN     1    1
3      sex    UP     1    2
4    smoke  DOWN     0    1
5    smoke  DOWN     1    1
6    smoke    UP     0    1
7    smoke    UP     1    1
8    sport  DOWN     1    2
9    sport    UP     1    2

I also want to count the factor levels that arent observed. Like I did per hand in the following output.
 variables group values freq
1      sex  DOWN     0    1
2      sex  DOWN     1    1
3      sex    UP     0    0  <--
4      sex    UP     1    2
5    smoke  DOWN     0    1
6    smoke  DOWN     1    1
7    smoke    UP     0    1
8    smoke    UP     1    1
9    sport  DOWN     0    0  <--
10   sport  DOWN     1    2
11   sport    UP     0    0  <--
12   sport    UP     1    2

How can I achieve the above output?

A: You can do this also with data.table with less lines of code:
library(data.table)
dt <- setDT(df)
cj <- CJ(dt$variables, dt$group, dt$values, unique = TRUE)
dt[, .N, keyby = c("variables", "group", "values")][cj][is.na(N), N := 0]

print(dt)
    variables group values N
 1:       sex  DOWN      0 1
 2:       sex  DOWN      1 1
 3:       sex    UP      0 0
 4:       sex    UP      1 2
 5:     smoke  DOWN      0 1
 6:     smoke  DOWN      1 1
 7:     smoke    UP      0 1
 8:     smoke    UP      1 1
 9:     sport  DOWN      0 0
10:     sport  DOWN      1 2
11:     sport    UP      0 0
12:     sport    UP      1 2

Explanation
setDT() converts a data.frame to a data.table by reference, ie, without copying.
CJ() is a cross join. It forms a data.table from the cross product of the vectors. Thus, it's the data.table version of expand.grid.
The parameter unique = TRUE is a convenient alternative to wrapping each argument in level() or unique().
The counting by groups is done with dt[, .N, keyby = c("variables", "group", "values")]:
   variables group values N
1:       sex  DOWN      0 1
2:       sex  DOWN      1 1
3:       sex    UP      1 2
4:     smoke  DOWN      0 1
5:     smoke  DOWN      1 1
6:     smoke    UP      0 1
7:     smoke    UP      1 1
8:     sport  DOWN      1 2
9:     sport    UP      1 2

Now, dt[, .N, keyby = c("variables", "group", "values")][cj] (right) joins the CJ() result with all possible combinations.
Finally, [is.na(N), N := 0] replaces all NAs in column N by 0.

A: You could also do:
library(plyr)
d1 <- count(df, c("variables", "group", "values"))
d2 <- expand.grid(list(levels(df$variables), levels(df$group), levels(df$values)))
d2$freq <- 0
colnames(d2) <- colnames(d1)
m <- merge(d1, d2, by = c("variables", "group", "values"), all.y  = T)[,-5]
m[is.na(m)] <- 0

   # variables group values freq.x
# 1        sex  DOWN      0      1
# 2        sex  DOWN      1      1
# 3        sex    UP      0      0
# 4        sex    UP      1      2
# 5      smoke  DOWN      0      1
# 6      smoke  DOWN      1      1
# 7      smoke    UP      0      1
# 8      smoke    UP      1      1
# 9      sport  DOWN      0      0
# 10     sport  DOWN      1      2
# 11     sport    UP      0      0
# 12     sport    UP      1      2

The idea is to make a data frame (named d2) in which all possible combinations of variables and group and values are generated and then merge it with d1.

A: Here is one idea. You can replicate the rows based on freq variable. If the freq is 2 then the replicated row will have a unique rowname which we can target and change its freq and values to 0.
df1 <- plyr::count(df, c("variables", "group", "values"))
df2 <- df1[rep(row.names(df1), df1$freq),]
df2$freq[grep('.', row.names(df2), fixed = TRUE)] <- 0
df2$values[df2$freq == 0] <- 0

df2
#     variables group values freq
#1         sex  DOWN      0    1
#2         sex  DOWN      1    1
#3         sex    UP      1    2
#3.1       sex    UP      0    0
#4       smoke  DOWN      0    1
#5       smoke  DOWN      1    1
#6       smoke    UP      0    1
#7       smoke    UP      1    1
#8       sport  DOWN      1    2
#8.1     sport  DOWN      0    0
#9       sport    UP      1    2
#9.1     sport    UP      0    0

If you want to reset your rownames then,
row.names(df2) <- NULL


text:
Q: Procedure in derived class doesn't return derived object I have a base class in C# like:
public class A{
  public A something() {
     //...
  }
}

And a derived class like:
public class B:A

When I do:
B obj = new B();
obj = obj.something();

VS throws an error saying (something like) "A can't be converted to B". Isn't it supposed to return B and not A?
Update:
Thank you all.
I've changed A.something(string) and now is A.something(int). The values passed to it are always ints, so... B (and other "sister" classes) are just a midstep in a full refactoring of the code, so they will disappear.
The case is that I have 4 classes that do the same and I'm changing'em for a unified one. Thus the need to return "B" objects for now.

A:
VS throws an error saying (something like) "A can't be converted to
  B". Isn't it supposed to return B and not A?

because your parent class function something() return type is A, and you are trying save that in Child class reference variable obj as below:
obj = obj.something(); //something returns instance of `A`

here child class reference variable obj can not point to  parent class instance but otherway(Parent class reference variable can point to child class instance) is possible.

A: you should consider changing the return type of the something() method in A class.

*

*it should return void

*you can pass a parameter via reference if you need to modify it in the function
This way you can overload/override the method in the derived class to get a different behavior if you need to.
the way it looks now there is not much you can do except a reinterpret_cast  which will cause problems later on.

A: Either you have to override Something() in Class B or get result of obj.something(); in Class A's Object.

A: No, even though it's defined in the base class, the return type won't be different, it will still return an instance of A which is not necessarily convertible to B. You could do something like this:
public class A{
  public virtual A something() {
     //...
  }
}

public class B:A
{
   public override A something() {
     return new B();
   }
}

B obj = new B();
obj = obj.something() as B;

Of course, the override does not really solve anything here. You could just return a B in the base class and it would work the same way, but that's just awkward.
I think your issue is that you are not following the LISKOV substitution principle here: you should be able to replace every instance of A with an instance that implements A without affecting the client. Downcasting in general is a code smell. You should treat all instances as A's and vary the behavior in your subclasses, not in the clients


text:
Q: Is there any way to run a Windows 10 Mobile app in Windows 10? I have a Windows 10 tablet. Instagram is available for Windows 10 Mobile - but not Windows 10.
Is there any way to run a Windows 10 Mobile app in Windows 10?


text:
Q: Reference a range dynamically I have this list

I want to first find familiyX and then go down to mum or dad side and then save the adresses listed below in the variable sTo.
Sub findAndStore()

    Dim EmailRng As Range, cl As Range
    Dim sTo As String, fam As String

    fam = "family2"

    Set EmailRng = Worksheets("sheet2").Range("D3:D" & Worksheets("sheet2").Cells(Worksheets("sheet2").Rows.Count, "D").End(xlUp).Row)

    For Each cl In EmailRng
        sTo = sTo & ";" & cl.Value
    Next

End Sub

The range is hardcoded. How can I make it dynamic based on that value fam holds?

A: Do you actually need a code to do it ?
I would recommend to create a new sheet, where the data are fields by column and records per row, than create a pivot table and get the information you need.
However for sake of VBA training
Sub findAndStore(family_name As String)
    ' find the family column
    Dim family_column As Integer, mum_column As Integer, dad_column As Integer
    family_column = ActiveSheet.Range("1:1").Find(family_name).Column

    ' get values
    Dim collected_addresses As String
    Dim addresses_collection As Variant
    Set addresses_collection = New Collection

    For column_offset = 0 To 1 'mum and dad column

        current_row = 3 'start on a third row under dad/mum header
        Do
            cell_value = ActiveSheet.Cells(current_row, family_column + column_offset).Value
            current_row = current_row + 1 'move to next row
            If cell_value <> "" Then addresses_collection.Add cell_value
        Loop Until cell_value = ""

    Next column_offset ' next column

    For Each s In addresses_collection
        collected_addresses = collected_addresses & s & ";"
    Next s

    Debug.Print collected_addresses

End Sub


text:
Q: AWS Lambda not executing node.js MySQL queries The company I work for is currently trying to migrate some of our existing codebase over to AWS Lambda. We are running node.js 4.3 (highest version offered for lambda) and we are executing inside a VPC to connect to an RDS database. The Lambda function is connecting to the database just fine, however a simple select query to our MySQL table isn't executing or returning any errors. Here is the code we are trying:
exports.handler = (event, context, callback) => {

  /**
   * Require Config file
  **/
  var config = require('./config.js');

  /**
   * AWS/MWS Configuration
  **/
  var AWS = require('aws-sdk');
  var MWS = require('mws');

  var mws           = require('./lib/mws-reports/lib/mws.js');
  var XML           = require('./lib/mws-reports/pixl-xml');
  var mwsReportsAPI = require('./lib/mws-reports/lib/reports.js');
  var mwsFeedsAPI   = require('./lib/mws-reports/lib/feeds.js');

  AWS.config.region      = config.AWS.region;
  AWS.config.credentials = config.AWS.credentials;

  var client = new mws.Client(
    config.MWS.credentials.accessKeyId,
    config.MWS.credentials.secretAccessKey,
    config.MWS.credentials.sellerID,
    {}
  );

  /**
   * Configure DB
   * @var Promise - A library to maintain Promises (used for chained MySQL queries)
   * @var Utils - A wrapper for utility functions.
   * @var connection - The MySQL DB Connection
  **/
  var Promise = require('bluebird');
  var utils   = require('./lib/Utils');
  var mysql = require('mysql');

  var MySQLConnection = mysql.createConnection(config.mysql);

  MySQLConnection.connect(function (err) {
    if(err) {
      console.log("Error connection: " + err.stack);
      return;
    }

    console.log("Connected as id " + connection.threadId);
  });

  var connection      = Promise.promisifyAll(MySQLConnection);
  var InventoryHealth = require('./app/models/InventoryHealth');
  var Items           = require('./app/models/Items');

  connection.query("SELECT * FROM items", function(err, rows) {
    rows.forEach(function(item) {
      console.log(JSON.stringify(item));
    });
  });

  connection.end();
  context.done(null, "Finished :)");
}

As I mentioned, the strangest part of all of this is the lack of response I get from Lambda. This is all it tells me:
START RequestId: f726f0ba-ecec-11e6-b0b3-9d51c554a5ac Version: $LATEST
2017-02-07T04:22:01.123Z    f726f0ba-ecec-11e6-b0b3-9d51c554a5ac    (node) crypto.createCredentials is deprecated. Use tls.createSecureContext instead.
END RequestId: f726f0ba-ecec-11e6-b0b3-9d51c554a5ac
REPORT RequestId: f726f0ba-ecec-11e6-b0b3-9d51c554a5ac  Duration: 4232.01 ms    Billed Duration: 4300 ms    Memory Size: 128 MB Max Memory Used: 22 MB

Any advice would be amazing. Thank you.

A: You are not using callbacks correctly. Read up on that. And remember to initialize modules outside the handler for faster function execution.
Without looking at what the code does, and I have not tested this code, you need something more in the lines of:
  /**
   * Require Config file
  **/
  var config = require('./config.js');

  /**
   * AWS/MWS Configuration
  **/
  var AWS = require('aws-sdk');
  var MWS = require('mws');

  var mws           = require('./lib/mws-reports/lib/mws.js');
  var XML           = require('./lib/mws-reports/pixl-xml');
  var mwsReportsAPI = require('./lib/mws-reports/lib/reports.js');
  var mwsFeedsAPI   = require('./lib/mws-reports/lib/feeds.js');

  AWS.config.region      = config.AWS.region;
  AWS.config.credentials = config.AWS.credentials;

  var client = new mws.Client(
    config.MWS.credentials.accessKeyId,
    config.MWS.credentials.secretAccessKey,
    config.MWS.credentials.sellerID,
    {}
  );

  /**
   * Configure DB
   * @var Promise - A library to maintain Promises (used for chained MySQL queries)
   * @var Utils - A wrapper for utility functions.
   * @var connection - The MySQL DB Connection
  **/
  var Promise = require('bluebird');
  var utils   = require('./lib/Utils');
  var mysql = require('mysql');

  var InventoryHealth = require('./app/models/InventoryHealth');
  var Items           = require('./app/models/Items');

  exports.handler = (event, context, callback) => {

    var MySQLConnection = mysql.createConnection(config.mysql);

    MySQLConnection.connect(function (err) {
      if(err) {
        console.log("Error connection: " + err.stack);
        callback(err, err);
      } else {

        console.log("Connected as id " + connection.threadId);

        var connection      = Promise.promisifyAll(MySQLConnection);

        connection.query("SELECT * FROM items", function(err, rows) {
          if (err) {
            console.log(err);
            callback(err, err);
          } else {
            rows.forEach(function(item) {
              console.log(JSON.stringify(item));
            });
            connection.end();
            callback(null, rows);
          }
        });

      }
});

}


text:
Q: Validator (xsd) for xml in android I have a project with API 10 (2.3.3 version) in Android and i have a problem for the validation of xml with xsd file.
This is my code:
public static Document buildDoc(String xml, String xsd){
     // parse an XML document into a DOM tree
    Document document = null;

   try {

       DocumentBuilderFactory parserFactory = DocumentBuilderFactory.newInstance();
        parserFactory.setNamespaceAware(true);
        DocumentBuilder parserdb = parserFactory.newDocumentBuilder();
        doc = parserdb.parse(new InputSource( new StringReader(xml)  ));

       SchemaFactory factory = SchemaFactory.newInstance(
                      XMLConstants.W3C_XML_SCHEMA_NS_URI);     //here the emulator raises an exception

        Source schemaFile = new StreamSource(new File(xsd));
        Schema schema = factory.newSchema(schemaFile);

        Validator validator = schema.newValidator();

        // validate the DOM tree
        validator.validate(new DOMSource(doc));
        System.out.println("Validation OK!");
    } catch (SAXException e) {
        // instance document is invalid!
             System.err.println("Validation ERROR!");
            e.printStackTrace();

    } catch (ParserConfigurationException e) {
                    // TODO Auto-generated catch block
             System.err.println("Validation ERROR!");
                    e.printStackTrace();
    } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
             System.err.println("Validation ERROR!");
            } catch (IOException e) {
                    // TODO Auto-generated catch block
                     System.err.println("Validation ERROR!");
                    e.printStackTrace();

            }

    return doc;

}

My Eclipse Simulator throw an exception:
E/AndroidRuntime(4770): Caused by: java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
In this line:
SchemaFactory factory = SchemaFactory.newInstance(
                          XMLConstants.W3C_XML_SCHEMA_NS_URI);
Why??

A: Because XML Schema isn't supported on your platform.

A: If your question was more than just why? and more of a how can I do this... then the following may be an alternative that you might like.
I found I was not able to get the regular xerces to work with Android, however I did find Xerces-for-Android, which I got working. The following are details of the setup and some example code. Good luck :)
The following worked for me:

*

*Create a validation utility.

*Get both the xml and xsd into file on the android OS and use the validation utility against it.

*Use Xerces-For-Android to do the validation.

Android does support some packages which we can use, I created my xml validation utility based on: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html
My initial sandbox testing was pretty smooth with java, then I tried to port it over to Dalvik and found that my code did not work. Some things just aren't supported the same with Dalvik, so I made some modifications.
I found a reference to xerces for android, so I modified my sandbox test of (the following doesn't work with android, the example after this does):
import java.io.File;

import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.w3c.dom.Document;

/**
 * A Utility to help with xml communication validation.
 */
public class XmlUtil {

    /**
     * Validation method.
     * Base code/example from: http://docs.oracle.com/javase/1.5.0/docs/api/javax/xml/validation/package-summary.html
     *
     * @param xmlFilePath The xml file we are trying to validate.
     * @param xmlSchemaFilePath The schema file we are using for the validation. This method assumes the schema file is valid.
     * @return True if valid, false if not valid or bad parse.
     */
    public static boolean validate(String xmlFilePath, String xmlSchemaFilePath) {

        // parse an XML document into a DOM tree
        DocumentBuilder parser = null;
        Document document;

        // Try the validation, we assume that if there are any issues with the validation
        // process that the input is invalid.
        try {
            // validate the DOM tree
            parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            document = parser.parse(new File(xmlFilePath));

            // create a SchemaFactory capable of understanding WXS schemas
            SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

            // load a WXS schema, represented by a Schema instance
            Source schemaFile = new StreamSource(new File(xmlSchemaFilePath));
            Schema schema = factory.newSchema(schemaFile);

            // create a Validator instance, which can be used to validate an instance document
            Validator validator = schema.newValidator();
            validator.validate(new DOMSource(document));
        } catch (Exception e) {
            // Catches: SAXException, ParserConfigurationException, and IOException.
            return false;
        }

        return true;
    }
}

The above code had to be modified some to work with xerces for android (http://gc.codehum.com/p/xerces-for-android/). You need SVN to get the project, the following are some crib notes:
download xerces-for-android
    download silk svn (for windows users) from http://www.sliksvn.com/en/download
        install silk svn (I did complete install)
        Once the install is complete, you should have svn in your system path.
        Test by typing "svn" from the command line.
        I went to my desktop then downloaded the xerces project by:
            svn checkout http://xerces-for-android.googlecode.com/svn/trunk/ xerces-for-android-read-only
        You should then have a new folder on your desktop called xerces-for-android-read-only

With the above jar (Eventually I'll make it into a jar, just copied it directly into my source for quick testing. If you wish to do the same, you can making the jar quickly with Ant (http://ant.apache.org/manual/using.html)), I was able to get the following to work for my xml validation:
import java.io.File;
import java.io.IOException;

import mf.javax.xml.transform.Source;
import mf.javax.xml.transform.stream.StreamSource;
import mf.javax.xml.validation.Schema;
import mf.javax.xml.validation.SchemaFactory;
import mf.javax.xml.validation.Validator;
import mf.org.apache.xerces.jaxp.validation.XMLSchemaFactory;

import org.xml.sax.SAXException;

/**
 * A Utility to help with xml communication validation.
 */public class XmlUtil {

    /**
     * Validation method.
     *
     * @param xmlFilePath The xml file we are trying to validate.
     * @param xmlSchemaFilePath The schema file we are using for the validation. This method assumes the schema file is valid.
     * @return True if valid, false if not valid or bad parse or exception/error during parse.
     */
    public static boolean validate(String xmlFilePath, String xmlSchemaFilePath) {

        // Try the validation, we assume that if there are any issues with the validation
        // process that the input is invalid.
        try {
            SchemaFactory  factory = new XMLSchemaFactory();
            Source schemaFile = new StreamSource(new File(xmlSchemaFilePath));
            Source xmlSource = new StreamSource(new File(xmlFilePath));
            Schema schema = factory.newSchema(schemaFile);
            Validator validator = schema.newValidator();
            validator.validate(xmlSource);
        } catch (SAXException e) {
            return false;
        } catch (IOException e) {
            return false;
        } catch (Exception e) {
            // Catches everything beyond: SAXException, and IOException.
            e.printStackTrace();
            return false;
        } catch (Error e) {
            // Needed this for debugging when I was having issues with my 1st set of code.
            e.printStackTrace();
            return false;
        }

        return true;
    }
}

Some Side Notes:
For creating the files, I made a simple file utility to write string to files:
public static void createFileFromString(String fileText, String fileName) {
    try {
        File file = new File(fileName);
        BufferedWriter output = new BufferedWriter(new FileWriter(file));
        output.write(fileText);
        output.close();
    } catch ( IOException e ) {
       e.printStackTrace();
    }
}

I also needed to write to an area that I had access to, so I made use of:
String path = this.getActivity().getPackageManager().getPackageInfo(getPackageName(), 0).applicationInfo.dataDir;

A little hackish, it works. I'm sure there is a more succinct way of doing this, however I figured I'd share my success, as there weren't any good examples that I found.


text:
Q: jQuery SerializeArray/Param get the class name? I have a form that had live appended input type hiddens with a name, value, and class and they all mean something. I want to take this and post to my php the json values. So I am doing
var storage = $.param($('form input[type=hidden]').serializeArray(), true);

and that works fine, however it only gets the name, and value. I need the class also because it has a unique id stored in it, which I can't store in the name or value because those also store unique ids.
So my question/options are.

*

*Can I somehow store two unique ids in the name that would be processed as such? Maybe a {id1:1,id2:2} or something as the name value?

*Can I make serializeArray also get the class name?

Example of input type hidden I add
<input type="hidden" class="photo_spot_1" name="photo_spot_5" value="../uploads/2462df38db374653720daa42b7aefec4/g6qjcn30kw_c.png">
Notice the two different id's at the end of name and class.

A: You cannot have an element id like {id1:1,id2:2} and also serializeArray will not get the class information from input fields but you can write your own logic to get that.
var data = [], obj;
$('form input[type=hidden]').each(function(){
    obj = {};
    obj[this.name] = this.value;
    obj["class"] = this.className
    data.push(obj);
});

Now you can use data which will contain each hidden input with is name/value and class information.

A: Your best bet will likely be to take those unique classes, and throw them onto a hidden input before you serialize your form and do your post.  This will give your server side code much easier access to these values.
Something like this:
$("#hiddenInput1").val($("#el1")[0].className);
var storage = $.param($('form input[type=hidden]').serializeArray(), true);


text:
Q: RGB to Lab conversion I am trying to convert an image from RGB to Lab.
The math formulas i've used are from here : https://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html#cvtcolor
double fun(double t) {
    if (t > 0.008856) return pow(t, (1 / 3));
    else return ((7.787 * t) + (16 / 116));
}

void convertRGBtoLab() {
    char fname[MAX_PATH];
    openFileDlg(fname);

    Mat src = imread(fname, CV_LOAD_IMAGE_COLOR);
    Mat lab(src.rows, src.cols, src.type());
    double X, Y, Z, a, b, L;
    double B, G, R;

    for (int i = 0; i < src.rows; i++) {
        for (int j = 0; j < src.cols; j++) {
            B = src.at<Vec3b>(i, j)[0];
            G = src.at<Vec3b>(i, j)[1];
            R = src.at<Vec3b>(i, j)[2];

            R /= 255.0;
            B /= 255.0;
            G /= 255.0;

            X = 0.412453 * R + 0.357580 * G + 0.180423 * B;
            Y = 0.212671 * R + 0.715160 * G + 0.072169 * B;
            Z = 0.019334 * R + 0.119193 * G + 0.950227 * B;

            X = X / 95.0456;
            Y = Y / 100.0;
            Z = Z / 108.8754;

            if (Y > 0.008856) L = 116 * pow(Y, 1 / 3) - 16;
            else L = 903.3*Y;

            a = 500 * (fun(X) - fun(Y)) + 128;
            b = 200 * (fun(Y) - fun(Z)) + 128;

            lab.at<Vec3b>(i, j)[0] = b + 128;
            lab.at<Vec3b>(i, j)[1] = a + 128;
            lab.at<Vec3b>(i, j)[2] = L * 2.55;
        }
    }

    imshow("RGB", src);
    imshow("Lab", lab);
    Mat cvmat(src.rows, src.cols, src.type());
    cvtColor(src, cvmat, CV_RGB2Lab, 0);
    imshow("Correct", cvmat);
    waitKey(0);
}

The result(image) I get is pretty different from the image obtained with cvtColor function.
Thanks.


text:
Q: Does "lifetime of up quark" have a physical meaning? I saw this question about the lifetime of an up quark.
As far as I know, free quarks are never observed in experiments. Then what is the significance of a statement like "the lifetime of an up quark is X units"?
I am looking for a physical explanation without involving much mathematics. I am not very familiar with the mathematical formulation of QCD, but I know about Feynman diagrams.

A: No, "lifetime of an up quark" is utterly meaningless (at least here, but I'd be hard pressed to find legitimate contexts for it...).
The lifetime discussed is that of a neutral pion, decaying by the F diagram (sorry)
In words, the pion "resolves" to virtual states of its valence quarks, u or d, which then couple to two real photons, to which the pion thus decays with a given width (/lifetime) thus computed.
The lifetime discussion never applied to the quarks, but only to the size of the amplitude represented by this diagram/process. This size eventually determines the probability of decay per unit of time, related to the lifetime.


text:
Q: How can a fragment control another fragment? I set a button in  A_fragment. I want to change a picture(in B_fragment) when the button is pressed, but when I write the following code, the program flashes back after the button is pressed. How can I do to control B_fragment's picture by the button in A_fragment?Thanks in advance!
public class A_Fragment extends Fragment {

     public View onCreateView(LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

       Button btn_confirm=(Button)root.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {

                ImageView i1 = (ImageView)root.findViewById(R.id.picture123);
                i1.setVisibility(View.GONE);

            }
        });
        return root;
   }
}

Here's the logcat of crash
2021-10-02 10:44:51.291 7624-7624/com.example.lili_nav E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.lili_nav, PID: 7624
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setVisibility(int)' on a null object reference
        at com.example.lili_nav.ui.right.SettingFragment$1.onClick(SettingFragment.java:91)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)

A: Should get the B_fragement's object
FragmentManager fm = getActivity.getSupportFragmentManager();
xxxFragment = (xxxFragment)fm.findFragmentByTag("xxx")

Then you can control it.


text:
Q: Why is the number of elements in a list referred to as "size" while the length of an array referred to as "length"? Why is the number of elements in a list referred to as "size", while the length of an array referred to as "length"?
package com.mycompany.javatest;

import java.util.*;

public class JavaTest {

    public static void main(String[] args) {

        List<String> stringList = new ArrayList<String>();
        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        System.out.println("Size of list is: " + stringList.size());

        String[] stringArray = {"one", "two", "three"};
        System.out.println("Length of array is: " + stringArray.length);
    }
}

A: Take a look at the definition of both words from Oxford Dictionaries:
Size: The relative extent of something; a thing's overall dimensions or magnitude; how big something is:
'the schools varied in size'
'a forest the size of Wales'
Length: The measurement or extent of something from END TO END; the greater of two or the greatest of three dimensions of an object:
'the delta is twenty kilometres in length'
Even if both can be understood as "extent of something", they differ in terms of measurement. Length measures the END to END of something, that's very appropriated to an Array. Size measures the size of a List, how big is the List?
The fact that Lists are dynamic (it can grow) and Arrays are Not helps you to visualize why length for Array and why size for List.
Greetings


text:
Q: How to open url in incognito mode using requests (without selenium/playwright) I want to scrap following medium article:
Link: article
To get full content of the article It should be opened in incognito mode.
So, when I use selenium/playwright with incognito mode for opening the url. It responds with full article.
But with requests it responds only the half content.
Is there any way to get incognito with Requests?
My code:
from bs4 import BeautifulSoup
import requests
html = requests.get("https://duregger.medium.com/growth-hacking-25e1db3b79cc")
bs = BeautifulSoup(html.text, 'html.parser')

A: To get full text of the article you have to make request to their GraphQL api:
import json
import requests

api_url = "https://duregger.medium.com/_/graphql"

query = [
    {
        "operationName": "PostViewerEdgeContentQuery",
        "query": "query PostViewerEdgeContentQuery($postId: ID!, $postMeteringOptions: PostMeteringOptions) {\n  post(id: $postId) {\n    ... on Post {\n      id\n      viewerEdge {\n        id\n        fullContent(postMeteringOptions: $postMeteringOptions) {\n          isLockedPreviewOnly\n          validatedShareKey\n          bodyModel {\n            ...PostBody_bodyModel\n            __typename\n          }\n          __typename\n        }\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n}\n\nfragment PostBody_bodyModel on RichText {\n  sections {\n    name\n    startIndex\n    textLayout\n    imageLayout\n    backgroundImage {\n      id\n      originalHeight\n      originalWidth\n      __typename\n    }\n    videoLayout\n    backgroundVideo {\n      videoId\n      originalHeight\n      originalWidth\n      previewImageId\n      __typename\n    }\n    __typename\n  }\n  paragraphs {\n    id\n    ...PostBodySection_paragraph\n    __typename\n  }\n  ...normalizedBodyModel_richText\n  __typename\n}\n\nfragment PostBodySection_paragraph on Paragraph {\n  name\n  ...PostBodyParagraph_paragraph\n  __typename\n  id\n}\n\nfragment PostBodyParagraph_paragraph on Paragraph {\n  name\n  type\n  ...ImageParagraph_paragraph\n  ...TextParagraph_paragraph\n  ...IframeParagraph_paragraph\n  ...MixtapeParagraph_paragraph\n  ...CodeBlockParagraph_paragraph\n  __typename\n  id\n}\n\nfragment ImageParagraph_paragraph on Paragraph {\n  href\n  layout\n  metadata {\n    id\n    originalHeight\n    originalWidth\n    focusPercentX\n    focusPercentY\n    alt\n    __typename\n  }\n  ...Markups_paragraph\n  ...ParagraphRefsMapContext_paragraph\n  ...PostAnnotationsMarker_paragraph\n  __typename\n  id\n}\n\nfragment Markups_paragraph on Paragraph {\n  name\n  text\n  hasDropCap\n  dropCapImage {\n    ...MarkupNode_data_dropCapImage\n    __typename\n    id\n  }\n  markups {\n    type\n    start\n    end\n    href\n    anchorType\n    userId\n    linkMetadata {\n      httpStatus\n      __typename\n    }\n    __typename\n  }\n  __typename\n  id\n}\n\nfragment MarkupNode_data_dropCapImage on ImageMetadata {\n  ...DropCap_image\n  __typename\n  id\n}\n\nfragment DropCap_image on ImageMetadata {\n  id\n  originalHeight\n  originalWidth\n  __typename\n}\n\nfragment ParagraphRefsMapContext_paragraph on Paragraph {\n  id\n  name\n  text\n  __typename\n}\n\nfragment PostAnnotationsMarker_paragraph on Paragraph {\n  ...PostViewNoteCard_paragraph\n  __typename\n  id\n}\n\nfragment PostViewNoteCard_paragraph on Paragraph {\n  name\n  __typename\n  id\n}\n\nfragment TextParagraph_paragraph on Paragraph {\n  type\n  hasDropCap\n  codeBlockMetadata {\n    mode\n    lang\n    __typename\n  }\n  ...Markups_paragraph\n  ...ParagraphRefsMapContext_paragraph\n  __typename\n  id\n}\n\nfragment IframeParagraph_paragraph on Paragraph {\n  iframe {\n    mediaResource {\n      id\n      iframeSrc\n      iframeHeight\n      iframeWidth\n      title\n      __typename\n    }\n    __typename\n  }\n  layout\n  ...getEmbedlyCardUrlParams_paragraph\n  ...Markups_paragraph\n  __typename\n  id\n}\n\nfragment getEmbedlyCardUrlParams_paragraph on Paragraph {\n  type\n  iframe {\n    mediaResource {\n      iframeSrc\n      __typename\n    }\n    __typename\n  }\n  __typename\n  id\n}\n\nfragment MixtapeParagraph_paragraph on Paragraph {\n  type\n  mixtapeMetadata {\n    href\n    mediaResource {\n      mediumCatalog {\n        id\n        __typename\n      }\n      __typename\n    }\n    __typename\n  }\n  ...GenericMixtapeParagraph_paragraph\n  __typename\n  id\n}\n\nfragment GenericMixtapeParagraph_paragraph on Paragraph {\n  text\n  mixtapeMetadata {\n    href\n    thumbnailImageId\n    __typename\n  }\n  markups {\n    start\n    end\n    type\n    href\n    __typename\n  }\n  __typename\n  id\n}\n\nfragment CodeBlockParagraph_paragraph on Paragraph {\n  codeBlockMetadata {\n    lang\n    mode\n    __typename\n  }\n  __typename\n  id\n}\n\nfragment normalizedBodyModel_richText on RichText {\n  paragraphs {\n    markups {\n      type\n      __typename\n    }\n    codeBlockMetadata {\n      lang\n      mode\n      __typename\n    }\n    ...getParagraphHighlights_paragraph\n    ...getParagraphPrivateNotes_paragraph\n    __typename\n  }\n  sections {\n    startIndex\n    ...getSectionEndIndex_section\n    __typename\n  }\n  ...getParagraphStyles_richText\n  ...getParagraphSpaces_richText\n  __typename\n}\n\nfragment getParagraphHighlights_paragraph on Paragraph {\n  name\n  __typename\n  id\n}\n\nfragment getParagraphPrivateNotes_paragraph on Paragraph {\n  name\n  __typename\n  id\n}\n\nfragment getSectionEndIndex_section on Section {\n  startIndex\n  __typename\n}\n\nfragment getParagraphStyles_richText on RichText {\n  paragraphs {\n    text\n    type\n    __typename\n  }\n  sections {\n    ...getSectionEndIndex_section\n    __typename\n  }\n  __typename\n}\n\nfragment getParagraphSpaces_richText on RichText {\n  paragraphs {\n    layout\n    metadata {\n      originalHeight\n      originalWidth\n      id\n      __typename\n    }\n    type\n    ...paragraphExtendsImageGrid_paragraph\n    __typename\n  }\n  ...getSeriesParagraphTopSpacings_richText\n  ...getPostParagraphTopSpacings_richText\n  __typename\n}\n\nfragment paragraphExtendsImageGrid_paragraph on Paragraph {\n  layout\n  type\n  __typename\n  id\n}\n\nfragment getSeriesParagraphTopSpacings_richText on RichText {\n  paragraphs {\n    id\n    __typename\n  }\n  sections {\n    startIndex\n    __typename\n  }\n  __typename\n}\n\nfragment getPostParagraphTopSpacings_richText on RichText {\n  paragraphs {\n    layout\n    text\n    codeBlockMetadata {\n      lang\n      mode\n      __typename\n    }\n    __typename\n  }\n  sections {\n    startIndex\n    __typename\n  }\n  __typename\n}\n",
        "variables": {
            "postId": "25e1db3b79cc",
            "postMeteringOptions": {"referrer": ""},
        },
    }
]

data = requests.post(api_url, json=query).json()

# uncomment this to print all data:
# print(json.dumps(data, indent=4))

data = data[0]["data"]
for p in data["post"]["viewerEdge"]["fullContent"]["bodyModel"]["paragraphs"]:
    print(p["text"])
    print()

Prints:
Growth Hacking

integrated marketing for the digitally connected

great growth hacking by — https://beatsmusic.com/

To be honest, I don't like this term, but it's a buzzword in today's tech climate… So. I guess a bit of an explanation is in order.

This concept of "growth hacking" is a recognition that when you focus on understanding your users and how they discover and adopt your products, you can build features that help you acquire and retain more users, rather than just spending marketing dollars.

- an excerpt from What is "Growth Hacking" really? by Josh Elman.

In short it's integrated marketing for the digitally connected.

Email marketing is a dinosaur, a very hard to kill dinosaur. Companies and businesses can't ignore the productivity (read "click throughs") email marketing gives them for their dollar, but also can't see that it
's just digitized junk mail. Yes — it works, but it's costly.

What do I mean? Well, let's see if I can't make some sense of this…

...and so on.


text:
Q: Why cant I branch a TFS project? Its driving me crazy already, I have a folder converted into a branch, when I try to branch this one, the dialog suggests a name, which I accept, then after confirming that I really want to branch I get the nice error message:
TF10175: The MYPROJECT-branch team project does not exist.

Althoug the branch dialog clearly states: "The new branch will be created and commited as single operation"
Ok, so, when I branch to a existing but empty folder (converted to a branch according the MS doc) I get the opposite message:
The item $/MYPROJECT-TEST already exists.

So what is it now? It really drives me crazy. I just cant branch this damn project.

A: Please follow these steps to delete the workspace:

*

*In "Team Explorer" select "Pending Changes"

*Beside the "Check In" button click on "Actions" and select "Manage Workspaces…"

*Select the Workspace and press "Remove"

Then follow these steps to branch a TFS project

when I branch to a existing but empty folder

We cannot specify an existing folder as a target. It will create a new folder based on the target path you entered, we should branch to a folder that does not exist. Then we can convert the folder to a branch via the button convert to branch.
Steps:
a.

b. Check in the new folder
c. Convert the folder test to branch:

Update1
Branch a TFVC project
Steps:

*

*Select the TFVC project and convert the project to branch via the button Convert to branch.

*Branch the TFVC project to an existing project repository folder.

Note: The target folder should not exist until the branch is completed. And we just can branch the project to another project repo folder.


text:
Q: Linking Oracle with SQL Server I'm trying to link SQL Server 2005 to an Oracle 10g database.  I've installed the Oracle client on the SQL server and validated that I can connect to the Oracle database using both tnsping and sqlplus.  When I try to run a query in SQL Server I get the following:
OLE DB provider "OraOLEDB.Oracle" for linked server "ORA_CSSA2APD" returned message "ORA-12154: TNS:could not resolve the connect identifier specified".
Msg 7303, Level 16, State 1, Line 1
Cannot initialize the data source object of OLE DB provider "OraOLEDB.Oracle" for linked server "ORA_CSSA2APD".
Any ideas?  I've tried both of the following queries with no luck:
select * from openquery(ORA_CSSA2APD, 'select count(rowid) from eservice_op.agent')
select count(rowid) from ORA_CSSA2APD..eservice_op.agent

A: I suspect an environment setting. That is, your session is picking up the TNSNAMES.ORA file but the session underlying SQL Server is not. I'd check were ORACLE_HOME and, possibly, TNS_ADMIN are being set and pointing to.
Are you able to use the easy connect syntax for the database with the SQL Server connection .
IE replace ORA_CSSA2APD with hostname:1521/service_name

A: ORA:12154 generally means that the alias of the db you're trying to connect to wasn't found in the tnsnames.ora file. (See http://ora-12154.ora-code.com/ a more detailed explanation.)
You need to make sure that the Data Source is an alias that the tnsnames file knows about (on the server where SQL Server resides, regardless of where you're running the queries from); SQL Server is going to be just like any other Oracle client and needs to know where to connect to and without the tnsnames.ora file, it's not going to know the details of where the Oracle db is.
If you don't have access to the SQL Server server (there's one from the department of redundancy department), you'll need to get the server admin to set that up for you.
(The Data Source property of the linked server should be the alias in tnsnames.ora alias for the db you're trying to link to.)
HTH...

A: TNS error messages generally means the connection is flawed (eg host is unobtainable/timesout on the specified port, or that is simply doesn't know what ORA_CSSA2APD is supposed to point to).
One thing to consider is, are you using a 64-bit Windows and are you using a 32-bit or 64-bit Oracle client (or possibly both). If you've got a 32-bit app running on a 64-bit OS trying to call Oracle, it needs a 32-bit Oracle client. Using a 32-bit client on a 64-bit OS can be tricky and it is safer to NOT install it in the "Program Files (x86)" folder.
Also bear in mind the following

In a 64-bit version of Windows Server
  2003 or of Windows XP, the
  %WinDir%\System32 folder is reserved
  for 64-bit applications. When a 32-bit
  application tries to access the
  System32 folder, access is redirected
  to the following folder:
  %WinDir%\SysWOW64

So for 64-bit windows, the 32 bit stuff is in the SysWOW64 folder and the 64 bit stuff is in the system32 folder.

A: This issue happened to me, as well, but only with certain Windows user accounts.  A combination of enabling the "Allow inprocess" provider option for the OraOLEDB.Oracle provide (SSMS > Server Objects > Linked Servers > Provides > OraOLEDB.Oracle), restarting the SQL Server Windows service and lastly adjusting the permissions on the TNSNAMES.ora file directly.

A: We found that SQL Server, for some unknown reason, started looking for the TNSNAMES.ORA file in default Oracle locations.
We were able to place the TNSNAMES.ORA files in the following locations, with successful results:
For SQL Server 32-bit on 32-bit OS or 64-bit on 64-bit OS
%ProgramFiles%\Oracle
%ProgramFiles%\Oracle\network\admin

For SQL Server 32-bit on 64-bit OS
%ProgramFiles% (x86)\Oracle
%ProgramFiles% (x86)\Oracle\network\admin

We too were able to connect using SQL*Plus, but SQL Server could not. It is important to note that SQL*Plus did not use the same TNSNAMES.ORA file. This is why one worked.


text:
Q: C#: Dynamicly Add Items to Scrollview Control in WPF Application Currently I am trying to code a WPF application that will store books and users for an imaginary library(I need to prove someone wrong). In my code, I have a class for Books and one for users. Inside of each will be a static list that keeps track of them all. What I would like to do is list out all the books and users so the viewer can see them. I thought I could do this with a scrollview and add labels to it that store the information(This would be in a separate window than the main screen, you would get there by pressing a button). However, I have been having some trouble with this.
LibraryCore:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LibraryCore
{
class User
{

}
class Books
{
    public static List<Books> bookslist = new List<Books>();

    public static void NewBook(string _title, string _author, string _publisher, int _isbn, int _count = 1)
    {
        bookslist.Add(new Books(_title, _author, _publisher, _isbn, _count));
    }

    public static void AddBook(string _title, int _amount)
    {
        bookslist[bookslist.FindIndex(b => b.Title.ToUpper() == _title.ToUpper())].Count += _amount;
    }
    public List<Books> currentLoans = new List<Books>();

    public string Publisher { get; private set; }
    public string Author { get; private set; }
    public string Title { get; private set; }

    public int ISBN { get; private set; }
    public int Count { get; private set; }

    Books(string _title, string _author, string _publisher, int _isbn, int _count = 1)
    {
        Title = _title;
        Author = _author;
        Publisher = _publisher;
        ISBN = _isbn;
        Count = _count;
    }
}
}

MainWindow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LibraryCore;

namespace LibraryLikeWpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnNewBook_Click(object sender, RoutedEventArgs e)
    {
        Books.NewBook("Odessy", "SOME OLD GUY", "Athens Inc.", 0);
        //Books.NewBook("OLD YELLER", "SOME OLD GUY", "Athens Inc.", 2);
        //Books.NewBook("This old man", "SOME OLD GUY", "Athens Inc.", 1);
    }

    private void btnInfo_Click(object sender, RoutedEventArgs e)
    {
        BookList bookList = new BookList();
        bookList.Show();
    }
}
}

BookListWindow:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using LibraryCore;

namespace LibraryLikeWpf
{
/// <summary>
/// Interaction logic for BookList.xaml
/// </summary>
public partial class BookList : Window
{
    public BookList()
    {
        InitializeComponent();
        for(int b = 0; b < Books.bookslist.Count; b++)
        {
            Label lbl = new Label();
            lbl.VerticalAlignment = VerticalAlignment.Top;
            lbl.Content = String.Format("Title: {0} Author: {1} Publisher: {2} ISBN: {3}",Books.bookslist[b].Title,Books.bookslist[b].Author, Books.bookslist[b].Publisher, Books.bookslist[b].ISBN);
            lbl.Width = 100000;
            scrollGrid.Children.Add(lbl);
        }
    }
}
}

This code works, but if I add several Books, the BookListWindow will just overlap the labels and I would like to know how to change their position when they are instantiated. Also, the labels get cut off even though their width shouldn't inhibit that. Why does that happen and how can I fix it? Also, is there a better way to list out ALL of the items in a list in a better looking way?

A: If your are using XAML, try to use ListView with Binding.
Create a ObservableCollection of Books and bind this to your ListView, this way you can control show your items are shown.


text:
Q: Laravel create FormRequest only for authorizarion There is some endpoint like users/{user_id}/events/. It's available only with auth token -
Route::group(['middleware' => 'auth:api'], function ()

But I need one more level of protection. This endpoint should be available only for the user which id is equal to user_id. I mean users/1/events/ is available for the user with id 1.
I know two ways to solve it:

*

*Create FormRequest and check all inside authorize method.

*Check it inside the method in the Controller.

I prefer the first approach to have thin controllers. But have doubts, is it good to do it thus or there is a better solution?

A: If you don't want to handle it inside controller, you can use FormRequest or Middleware. FormRequest is a good choice for you task.


text:
Q: React native ListItem image url passing variable I wanted to pass some variable into my image url for avatar but this is not working it seems:
renderItem = ({ item }) => (
 <ListItem
      title= {item.name}
      subtitle={
        <View style={styles.subtitleView}>
          <Text style={styles.ratingText}>Price: {item.price}</Text>
          <Text style={styles.ratingText}>Stock: {item.stock}</Text>
        </View>
      }
     avatar={{ uri: 'https://test.com/${item.ver}/${item.cid}.jpg',}}
    />
)

This is for rendering my ListItem and I need those variable to get different avatar picture for different items but this is not working for me. Any other way of doing this?

A: Here is a preview for your requirement. https://codesandbox.io/s/3v0qn6j0zp . ES6 comes up with a new type of string literal, using the back-tick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated..
    let fb = "facebook";

    <Image
        source={{
          uri: `https://${fb}.github.io/react-native/docs/assets/favicon.png`
        }}
      />


text:
Q: How can I make Emil show up at the Resistance Camp? I've been trying for a while now to get Emil to show up at the Resistance Camp so that I can buy his weapons and advanced crafting components. So far, the only way I've made any progress towards that is by following this guide. It basically recommends alternating interacting with him and completing story events in chapter 14-1. By doing that, I got him to take a longer route that passes through the crater and by both the factory and his original area. I also got the described email from him, plus another email. But he never seems to go near the Resistance camp, even if I teleport out of the city and back, or walk out and back, or save and reload. Is there anything else I need to do to make him go near the Resistance camp.
If it matters, I already

 fought him and got the Emil Heads weapon

A: Technically, there is not a way to make Emil drive by the Resistance Camp; it's random where he spawns, but that route is definitely less common than the one in front of the Desert Zone. All you can do is make him respawn and hope he shows up on the route that takes him by the Resistance Camp. I personally reloaded the area repeatedly until he was in the right place, but according to this video I found, you can make him respawn without reloading the area, which vastly reduces the amount of time you will spend trying to get him to show up by the Resistance Camp.
The video says to do this in Chapter 7-1.
The steps laid out in the video are:

*

*Finish the Forest Kingdom chapter

*Talk to Emil at least once

*Run (don't fast travel) to the abandoned commercial facility

*Run about halfway across the bridge back to the City Ruins and check on Emil's location.

*Run back into the abandoned commercial facility if he is not on the correct route.

Repeat the last two steps until he shows up.
It's worth mentioning that you need to shoot Emil at the right time for him to land in front of the Resistance Camp, as there have been numerous reports of Emil not selling the good stuff even though he was driving along the correct route. The proper timing of this is also included in that video around the 3:10 mark.

A: I disagree, the best method for me is using the elevator you use to go down to the large underground cave system and see emil, just inside the broken white pipe. Said pipe is round the city ruins where the huge white tower is at the end of the game. (See other sources) You just go down the elevator and go back up again and it resets the whole area. This worked best for me playing as A2 but that may be bias on my part as I play as A2 a lot and have not repeated this test as 9S or 2B. Hope this helped recent players looking for an updated solution


text:
Q: SSD Performance Dropping over time, is this expected behavior? In reference to this, I found the below in an ad:

I recently bought these drives a few weeks ago and then saw his picture. Do all SSDs suffer from such substantial performance drops over time and why?

A: It may seem a dramatic drop but that's not the case. Still, the chart is meaningless without knowledge of the underlying load of the drive, so mostly marketing drivel.
But yes, technically all SSDs suffer from a performance drop when faced with heavy write scenarios due to a fundamental limitation of the underlying technology itself(NAND flash).
The flaw is that data can be written on page level(e.g. 4KB) but can only be erased on the block level(e.g. 512KB).
And when you have no more free blocks, the controller is forced to perform an erase cycle(which is awfully slow compared to the other operations). This also leads to a phenomenon known as Write Amplification.
It's also why most drives come with a certain amount of over-provisioning that's hidden away by the controller, just for the purpose of maintaining a good performance level - it allows the controller more flexibility on when it performs its garbage collection routines, to minimize impact on performance.
On a historical note, this used to be a bigger problem earlier when the TRIM command wasn't as ubiquitous as it is now. It was a solution to a problem arising from the abstraction of logical blocks from the physical blocks that the drive's controller performed which itself was necessitated by the need for wear-levelling.
Source: Anandtech (I've come to regard them as THE resource when it comes to SSD technology and testing). If you wish a more in-depth take on the matter read THIS. It's a little bit old, but much of it still holds.


text:
Q: Can space-time get torn apart? Here's an interesting comment from phsyics forums

I think that there are a variety of interpretations of the underlying structure of the universe. However, you can think of energy as creating the fabric in which it exists. Each particle has an energy distribution and the energy at a particular point in space is determined by the sum of the energy contibutions of every particle in the universe at that point in space. The total energy density at each point provides a type of thickness to the universe at that point, where energy is like rubber in that it pulls in the universe together (think of a rubber band that is stretched and that is thicker at some points). Accordingly, in high energy density (thick) space, space is smaller and time is slower If you look at a ruler in high energy density area while standing in a low energy density area, the ruler will be smaller and a clock will tick slower.
Anyway, if you have a rip in space time (an area of zero energy density), particles or waves directed at the rip would appear to be reflected away from it sort of like anti-gravity (quantum mechanically, a rip is similar a forbidden zone, although if you were completly encircled by a rip, you couldn't tunnel through). You wouldn't be able to see the rip. If you were encircled by a rip, it would make you invisible. It would be the same as creating your own island universe. It is similar to what happens with a black hole. In an expanding universe, from the frame of the black hole, the outer universe between black holes is so thin as to almost be a rip. You can think about the universe as being a giant ballon with the thickness of the rubber being determined by the energy density of the baloon and particles are like accoustic waves traveling through the baloon. A rip in space time will affect particle waves in a similar way as a hole in the ballon affects accoustic waves, except that the universe wouldn't deflate.

Further;

As I see it, the energy density of mass extends beyond the position of the mass, so that the energy density of a black hole extends infinetly in an inverse square manner form the black hole even though all of the mass of the black hole is at a point. It is the gradient of the energy density that creates the appearence of gravitational acceleration. Also, the energy density provides a thickness to the universe. The extreme thinning of energy density is like a whole in space in the same sense that a worn thin part of a bed sheet is seen to have a hole. Although, it is a relative concept.
Accordingly, my idea for a "ripped space force field" is to locally redistribute the energy density such that all of the energy density in one region of space is displaced into the adjacent region which creates a sort of rip in space, since it creates a large energy density gradient that causes particles to gravitationally accelerate away from the gap such that almost no energy would flow through the energy density gap.

I've heard that we cannot have absolute zero energy anywhere in the universe, due to Heisenberg uncertainty principle.  And a "rip" in spacetime means zero energy density, so this is not possible? A slightly above layman but well below  physics degree explanation would be nice.
Topology change of space-time is probably impossible in general relativity, or
that's what I managed to gather. But what about it in string theory, is this an actual possibility or am I talking science fiction here.
I know this has been asked before, but the answers weren't satisfactory to me.
Thanks.
Reference https://www.physicsforums.com/threads/can-you-rip-the-space-time-fabric.391606/page-2


text:
Q: How to call preferredVideoStabilizationMode in GPUImage3? I'm in the process of rebuilding an iOS app from ObjC + GPUImage to Swift + GPUImage3 (and a rank amateur coder!).
I previously used:
m_videoCamera.videoCaptureConnection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeOff;

to set the stabilisation mode, but in GPUImage3 there seem to be no capture connections available. Can anyone suggest a way to access the capture connections to set preferredVideoStabilizationMode?

A: Turns out it wasn't so difficult, by repurposing some of the code from within GPUImage3 Camera input I got it to work. Now there may be some obvious problem with this but it seems to be working so far
let device = videoCamera

if ((device?.inputCamera.activeFormat.isVideoStabilizationModeSupported(AVCaptureVideoStabilizationMode.standard))!){
        var captureConnection: AVCaptureConnection!
        if #available(iOS 13.0, *) {
            for connection in (device?.captureSession.connections)! {
                for port in connection.inputPorts {
                    if port.mediaType == AVMediaType.video {
                        captureConnection = connection
                        captureConnection.preferredVideoStabilizationMode = .standard
                        print("capture connection from within startStabilization is \(String(describing: captureConnection))")
                        print("preferred video stab mode set to on")
                        let currentStabMode = captureConnection.activeVideoStabilizationMode.rawValue
                        print("active stabilization mode from startStabilization is \(currentStabMode)")
                    }
                }
            }
        } else {
            // put in warning pop up if stabilization not available
            print("startStabilization failed")
        }
}


text:
Q: Using c# to set the source of a mediaElement I am trying to set the source of a media element using c# coding (the video is located in the project's assets folder), my coding is as follow:
//Defined as such in my XAML
mediaElement.Source = new Uri(@"Assets\HarlemCampus.wmv");
mediaElement.Play();

...but I am receiving the following error when I click the button to play the video:

I don't want to preset the source in XAML because I want to dynamically change the media element's source, according to the radiobutton selected by the user at runtime, if there's a way to do this?

A: You'll have to use a resource file Uri:
mediaElement.Source = new Uri("ms-appx:///Assets/HarlemCampus.wmv");


text:
Q: asp.net core rewrite middleware not rewriting, possible regex issue (I am using VS2017 and asp.net core v1.1.1)
Hi,
I am trying to make my url's more seo friendly, I have added the .net core rewriting middleware via nuget, and followed this guide https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting
For some reason my URL's are not being re-written.
My URL's are currently /Albums?slug=first-test and I want them to be Albums/first-test
This is what I have come up with (from startup.cs) :
 var options = new RewriteOptions()
.AddRewrite(@"^(.*)?slug=(.*)", "$1/$2", skipRemainingRules: true)
.AddRewrite(@"^Albums?slug=(.*)", "Albums/$1", skipRemainingRules: true);
 app.UseRewriter(options);

As you can see I am attempting 2 varations that I hope to have the same outcome, this is because I also have /Galleries?slug=first-test and I was hoping that I could get away with one rule for both.

A: So, it seems I made a noob mistake.  All I needed to do was map new routes!
I noticed how Controller/Action/id didn't contain ?id= which reminded me of my earlier days of learning, in fact day one of it lol.  So here's what I added:
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{slug?}");

    });

Edit:
Changed the optional in the end as adding new routes broke my home index.


text:
Q: Parsing HTML passed in from JavaScript routine - in IE it comes back with Html tags capitalised - need work around! Ultimately my application is pattern matching based on a text selection within a web browser, generating regEx code so that a portion of a page can be revisited and read anagrammatically.
I'm currently pulling a portion of the text by walking up the dom and then returning innerHtml.
The issue that I have is the text value of the innerHtml property is not consistent, and not properly representative of the literal text.
Tags are capitalised, quotes removed etc, and it varies between browsers.
Is there a way to deal with this client side. I can already read in the literal page text using HttpRequest, but matching using the whole page may be less accurate.
Is this a common issue in JavaScript and is there a way around it?

A: innerHTML is indeed bad practice. Apparently it is something introduced by Microsoft in IE that got popular. The thing is, HTML is a DOM; it is not a string. Because innerHTML is not a standard, there is not standard way for converting the DOM into a string, and therefore you will get inconsistent results.
The HTML DOM is very extensive - you can do everything you might want to do with innerHTML with standardized DOM instead. If you really need to get the text value of a node, the use the property nodeValue of that node.
Most of what I am saying came from an article that is a little outdated but still accurate, about innerHTML alternatives.


text:
Q: setcookie on click and selection I want to write a cookie when a visitor to my site clicks a link, and a "remember my choice" checkbox is selected. I'm new to cookies; what's the easiest way to do this?

A: I would very advantageous to use jquery. Jquery cookie plugin is link below:
https://github.com/carhartl/jquery-cookie
Code is here:
$.cookie('the_cookie', 'the_value');

Sample app for your case.
http://jsfiddle.net/B3u7y/

A: You should use javascript to do this. Check out this link.
Alternatively using jQuery (much better in my opinion), there is a plugin for this!
An example of the jQuery method using this plugin would be:
$.cookie('the_cookie', 'the_value', { expires: 7 });


text:
Q: Anyway to just run the code in the ide window from pressing F5 in visual studio code? I keep getting this in my python terminal :
Keeps Mapping to Path
I just want to just run the code itself in the python shell (am using Visual Studio Code as the IDE) .. how do I remove the path from running

A: from the python shell, you could simply enter:
>>> execfile('path_to_file.py')


text:
Q: Should we have "Migrate to programmers.stackexchange.com" when closing a question? I apologize if that has been discussed before, didn't find anything when searching.  But I think it would be convenient if there was an option to vote to close/migrate questions to programmers.stackexchange.com.  (In fact, I believe that is in part why that site exists -- to get rid of those questions from SO)  Is this planned already?  Or is it too early because it's still in beta?

A: It should happen - eventually.
But right now, the site is still in beta. Which means two thing:

*

*It may well be killed off. In which case, questions migrated there would be lost. Not that that's necessarily a bad thing...

*It isn't fully defined yet. So it wouldn't necessarily be clear which questions were appropriate for migration. The original definition of the site implied subjective-programming and programmer-related questions would be the focus, but discussion is ongoing


text:
Q: Running Docker Engine API behind Nginx I'm trying to run and use docker behind nginx as a reverse proxy. Everything works fine except when docker responds with a raw stream "application/vnd.docker.raw-stream" instead of normal HTTP response. This is happening with endpoints /start, /attach, etc. documented here: https://docs.docker.com/engine/api/v1.21/#operation/ExecStart
This is when my nginx configuration doesn't forward the docker response to the client. I tried searching it up and there's just one blog article suggesting a patch to actual nginx C file: https://blog.yadutaf.fr/2014/12/12/how-to-run-docker-behind-an-nginx-reverse-proxy/
I followed the blog above completely, however, setting r->upstream->upgrade = 1; seems to have no effect on the /start HTTP endpoint in docker. Nginx simply doesn't respond. Is there any way around this? This is my nginx.conf file at the moment:
daemon off;
error_log /dev/stdout info;
# error_log logs/error.log debug;

events {
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                               '$status $body_bytes_sent "$http_referer" '
                               '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /dev/stdout main;
    # include       mime.types;
    # default_type  application/octet-stream;
    # sendfile        on;
    # keepalive_timeout  65;

    upstream dockerpool {
        # session_sticky cookie=sessionid fallback=off mode=insert option=indirect;
        # backup server
        # server nginx_dev_test:80;
        server socat:2376;
    }

    server {
        listen 80;

        location / {
            # The upstream here must be a nginx variable
            set $ups dockerpool;
            proxy_buffering off;
            proxy_pass http://$ups;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
        }
    }

}

A: For anyone struggling with the same problem, I did extensive research on internet and there's no sane method to get what I wanted to work with Nginx, and even if you solve this, you'll blow your heads off autoscaling/load-balancing this architecture.
Today, I moved to HAProxy using stick tables, works like a charm. Nginx is not suitable for this use case.
Update: STUPID ME. This COULD work with nginx and/or HAProxy, just make sure you upgrade (downgrade?) your HTTP connection to TCP connection when running docker commands, etc.


text:
Q: get notification while app in background after capture image from camera My app is running background and now i capture image from camera , is it possible to get image or any notification in my app after capture image?

A: Your application can notify the user \ you only about what's going on inside the eco system of  your application. There's no way to handle other processes that are running on iOS such as the camera unless it was called from inside your app.


text:
Q: Reading the value of a custom control property through a Control object I have 3 custom controls, all of them have a property with a name "MyCustomProperty", let's say i need to use
foreach (control c in this.controls)

how can i reach MyCustomProperty through the object c ?
Thanks

A: Step 1. Give your controls a common interface that exposes the property.
interface IPropertyHolder
{
    string MyCustomProperty { get; }
}

class MyCustomControl1 : TextBox, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

class MyCustomControl2 : Form, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

class MyCustomControl3 : Control, IPropertyHolder
{
    public string MyCustomProperty { get; set; }
}

Step 2. Either cast it:
foreach (var c in this.controls)
{
    var custom = c as IPropertyHolder;
    if (custom != null)
    {
        var temp = c.MyCustomProperty;
    }
}

Or only include controls that have the interface:
foreach (var c in this.controls.OfType<IPropertyHolder>())
{
    var temp = c.MyCustomProperty;
}

A: You could use reflection to identify controls with your property, then use a dynamic to access the property:
using System.Reflection;

if (c.GetType().GetProperty("MyCustomProperty") != null)
{
  string something = ((dynamic)c).MyCustomProperty; //Assuming your property is a string
}

A: Test that the control is of the proper type, then cast it by giving it a name (myC here):
if (c is MyCustomControl myC)
{
  var something = myC.MyCustomProperty;
}

The following is the equivalent, but could be easier to understand:
if (c is MyCustomControl)
{
  var myC = (MyCustomControl)c;
  var something = myC.MyCustomProperty;
}


text:
Q: How can I get a field inside a type () inside an implementation using Reflection on Java TLDR: I need a method to get the  being implemented as an interface in a class using reflection. (read the last line too, please...)
The problem is simple, but I can't solve it, I have an interface EventListener, with the following code:

public @IndexSubclasses interface EventListener<T> {
    public void onEvent(T event);
}

And I have an implementation, the JoinEventSampleBase (which is only a sample to be copied), with the following code:
@Scope.Server @FrameworkEvent
public class JoinEventBaseSample implements EventListener<JoinEvent> {
    @Override
    public void onEvent(JoinEvent event) {
        // Code here
    }
}

I had tried the following on my EventManager:
 Class<?> eventIndication = Arrays.stream(listener.getInterfaces())
       .filter(aClass -> aClass.getName().equals(EventListener.class.getName()))
 .findFirst().get().getComponentType();

It is confuse because it was only a test.
I got the following error:
java.lang.NullPointerException: Cannot invoke "java.lang.Class.getDeclaredField(java.lang.String)" because "eventIndication" is null

The line that is doing the error after the "eventIndication" var is the following:
Object instance = eventIndication.getDeclaredField("instance").get(null);

Finally, my objective is access the instance method into the eventIndication field which is into the JoinEvent class in
implements EventListener<JoinEvent>

A: It works, thanks (:
My code:

ParameterizedType parameterizedType = (ParameterizedType) listener.getGenericInterfaces()[0];
Class<?> eventIndication = (Class<?>) parameterizedType.getActualTypeArguments()[0];


text:
Q: Adding html tags with regex/python, sub code not working So I have an assignment where I need to add HTML tags to a poem, and I want each line to have a paragraph tag with a class ID. I have made the code, but when I print it, it doesn't show.
I have made a regex (re) sub for each line that starts again when the line is an empty list item. I then print the list after the loop, but it looks the same as before the loop. Why is that?
I have also tried the first part of the sub on regex101, so it should catch the entire sentence. The second should sub with everything in the sentence, but add the p tags. \1 is used to refer back to the (.+)
textList = text.split("\n")

sentenceCount = 0

for sentence in textList:
    if sentence == "":
        sentenceCount = 0
    elif sentenceCount == 0:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 1:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 2:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 3:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 4:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 5:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1
    elif sentenceCount == 6:
        sentence = re.sub(r"^(.+)$", r"
\1
", sentence)
        sentenceCount += 1

print(textList)

This is the part of the code for this problem. The textList variable works fine, the problem is with the for loop somewhere.


text:
Q: Is there a word for petals falling without withering? When roses whither, the petals shrivel and dries up before falling. Is there a word like withering, but doesn't imply that the petals shrivel and dries up? Is there a word that refers to just petals falling like in the beauty in the beast?

A: Looking through the Glossary of botanical terms, I found the term abscission

The normal separation of flowers, fruit, and leaves from plants.

which describes the process you're referring to quite accurately.


text:
Q: How to set custom app for contact view in android? I want to build Contact+ clone, and I want to know how can I make my app to be shown in the choosing list when the user want to see the contact information.
What intent should I add to my AndroidManifest file? How can I retrieve the selected contact in the activity ?