text:
Q: Проблема получения ответа от Wikipedia API Формирую такой запрос к API для получения информации с статьи которую нашёл:
https://ru.wikipedia.org/w/api.php?action=opensearch&namespace=0&search=Трактор&limit=1&format=json&prop=info

Но в ответ я получаю это:
["\u0422\u0440\u0430\u043a\u0442\u043e\u0440",["\u0422\u0440\u0430\u043a\u0442\u043e\u0440"],[""],["https://ru.wikipedia.org/wiki/%D0%A2%D1%80%D0%B0%D0%BA%D1%82%D0%BE%D1%80"]]

Вижу что он нашёл нужную страницу, но информационный текст с этой статьи он не выдает, лишь ссылка, prop=info указан подскажите пожалуйста что не так и почему он не возвращает текст статьи в ответе?(

A: Воспользовавшись песочницей можно получить требуемые параметры для вывода статьи:

*

*action=parse Анализирует содержимое и возвращает вывод

*format=json

*page=Трактор
Не может использоваться вместе с текстом и заголовком

*prop=wikitext
Какую информацию получить:

*text
Выдает проанализированный текст викитекста.

*langlinks
Предоставляет языковые ссылки в проанализированном викитексте.

*categories
Предоставляет категории в проанализированном викитексте.

*categorieshtml
Предоставляет HTML-версию категорий.

*links
Предоставляет внутренние ссылки в проанализированном викитексте.

*templates
Предоставляет шаблоны в проанализированном викитексте.

*images
Предоставляет изображения в проанализированном викитексте.

*externallinks
Предоставляет внешние ссылки в проанализированном викитексте.

*sections
Предоставляет разделы в проанализированном викитексте.

*revid
Добавляет идентификатор редакции проанализированной страницы.

*displaytitle
Добавляет заголовок проанализированного викитекста.

*subtitle
Добавляет подзаголовок для проанализированной страницы.

*headhtml
Выдает проанализированный тип документа, открытие , элемент и открытие страницы.

*modules
Предоставляет модули ResourceLoader, используемые на странице. Для загрузки используйте mw.loader.using(). Либо, jsconfigvarsлибо encodedjsconfigvarsдолжны запрашиваться вместе с modules.

*jsconfigvars
Предоставляет переменные конфигурации JavaScript, специфичные для страницы. Чтобы применить, используйте mw.config.set().

*encodedjsconfigvars
Предоставляет переменные конфигурации JavaScript, специфичные для страницы, в виде строки JSON.

*indicators
Предоставляет HTML-код индикаторов состояния страницы, используемых на странице.

*iwlinks
Предоставляет межвики-ссылки в проанализированном викитексте.

*wikitext
Предоставляет исходный проанализированный викитекст.

*properties
Предоставляет различные свойства, определенные в проанализированном викитексте.

*limitreportdata
Предоставляет отчет о лимитах в структурированном виде. Не выдает данных, если установлен disablelimitreport .

*limitreporthtml
Предоставляет HTML-версию отчета о лимитах. Не выдает данных, если установлен disablelimitreport .

*parsetree
Дерево синтаксического анализа XML содержимого редакции (требуется модель содержимого wikitext)

*parsewarnings
Выдает предупреждения, возникшие при парсинге контента (в виде вики-текста).

*parsewarningshtml
Выдает предупреждения, возникшие при разборе содержимого (в формате HTML).

*formatversion=2
Форматирование вывода:

*1
Обратно-совместимый формат (логические значения в стиле XML, * ключи для узлов содержимого и т. д.).

*2
Современный формат.
последний
Используйте последний формат (в настоящее время 2), может быть изменен без предупреждения.


text:
Q: How to Open a File with SUDO from within nnn File Manager While using nnn, I need to edit a file that requires sudo privileges.
I love that I'm able to navigate quickly to the file I want to edit using nnn, and how it immediately opens the file in my editor. Yet upon making modifications, I cannot save the file without root privileges.
This really breaks the flow of what I like about nnn. Is there a quick way I can launch the editor from a file in nnn (with sudo)?

A: nnn will use whatever editor you have defined in the environment variable VISUAL as the editor when editing a file by pressing e in the browser, or it will pick some system default editor.
This means that you may set VISUAL to e.g. sudo vi before invoking nnn:
VISUAL='sudo vi' nnn

Note that this globally changes the behaviour of the e action in the browser.
The other way to do this is to open the file using o from the browser.  nnn will then ask you what to open the file with, and you may, for example, use sudoedit or sudo vi etc.   It will then ask you whether the program you are opening uses a command line or a graphical interface. Then it will open the file in the editor appropriately.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access Sybase #temp table created in one proc from a sub procedure I have created a # table in TestProc and calling SubProc within TestProc. Now, with SubProc, I am trying to refer the # table that I created in TestProc. Is it possible? Below code for your reference:
-- Main Procedure
create procedure TestProc (
      @id smallint,
      @name varchar
 ) as
 select id, name into #myTab from myTable
 exec SubProc @rVal output

 -- Sub Procedure
 create procedure SubProc (
      @rVal integer output
 ) as
 select @rVal=count(1) from #myTab

A: That's not possible and you should avoid it.
You can put create the table in tempdb database but I advice you to also avoid it!

A: Yes, this is entirely possible though not ideal but this is one of the ways wherein you could fully utilise the index creation on the 'parent' proc when using it under the 'child' proc.


text:
Q: Why my count is not working? my count_1 and count_2 are not being counted balance = 600
count_1=0
while True:
 option = input("Press (A) Make a deposit, (B) Make a withdrawal, (C) Balance report, (D) exit: ")
if option == "A" or option == "a":
  def deposit(count_1):
    deposit = int(input("Enter amount to be deposited: "))
    if deposit < 0:
      print("Please enter a valid number")
      return balance
    else:
      new_balance = balance + deposit
      print("Amount left in your account MXN: " + str(new_balance))
      count_1 += 1
      return (new_balance)
  balance = deposit(count_1)

elif option == "C" or option == "c":
  print("Deposits made: ", count_1 )
  print("Withdraws made: ", count_2 )
  print("Current Balance: ", balance)

MY OUTPUT:
Press (A) Make a deposit, (B) Make a withdrawal, (C) Balance report, (D) exit: a
Enter amount to be deposited: 500
Amount left in your account MXN: 1100
Press (A) Make a deposit, (B) Make a withdrawal, (C) Balance report, (D) exit: c
Deposits made:  0
Current Balance:  1100

A: You are passing count_1 as an argument to a function, this means it will only be changed INSIDE it, the passed global value will be the same. This is example of your code:
option = 'a'
count_1 = 0

if option == 'a':
    def deposit(count_1):
        count_1 += 1
        print("Within a function", count_1)
    deposit(count_1)

print("Out", count_1)

Output:
Within a function 1
Out 0

What you WANT to do is to change the GLOBAL attribute. You can either change it inside the function or return it with new_balance and change it after deposit() function was called. Try 2:
option = 'a'
count_1 = 0

if option == 'a':
    def deposit():
        global count_1 # Points on global variable
        count_1 += 1
        print("Within a function", count_1)
    deposit()

print("Out", count_1)

Output:
Within a function 1
Out 1


text:
Q: Tadpole-free condition Tadpole-free is a very important condition for perturbative string theory (which is equivalent to the theory to be expanded around the "right" vacuum). For simplicity, let's consider closed string only. 1-point insertion to a sphere vanish (for obvious reason, as the volume of the conformal group there is infinite), and for nonzero genus, it might be interesting.
Assume that the conformal invariance $Sp(2g, \mathbb{Z})$ condition (which is only needed to confirm for torus $SL(2,\mathbb{Z})$ modular invariant, and higher genus will follow) is satisfied.
How can I check for the disappearance of all 1-point insertion to the nonzero genus? Is it enough to check it for 1-point insertion to the torus, and higher genus will follow after that (just like with modular invariance)?
Can all these argument be generalized to worlsheets with boundaries (let's also include modular invariance condition here)?


text:
Q: String substitution where the old and new strings are in columns Let´s say you have the following DataFrame:
DF <- as.data.frame(cbind(c("Aa1","aB1","aA1"),c("A","B","A"),c("D","F","G")))
colnames(DF)[1] <- "State1"
colnames(DF)[2] <- "StringToBeReplaced"
colnames(DF)[3] <- "StringToTakeItsPlace"

which should yield
  State1 StringToBeReplaced StringToTakeItsPlace
1    Aa1                  A                    D
2    aB1                  B                    F
3    aA1                  A                    G

The names kind of give my objective away: I want to replace the strings occurring in State1, from "StringToBeReplaced"
to "StringToTakeItsPlace".
Is there any way to obtain a new column that is like State1 in all aspects, except that the string substitution has been carried out?
In other words, the desired output is
  State1 StringToBeReplaced StringToTakeItsPlace  State2
1    Aa1                  A                    D   Da1
2    aB1                  B                    F   aF1
3    aA1                  A                    G   aG1

Many thanks!

A: Use mapply with gsub:
transform(DF,
  State2 = mapply(gsub, StringToBeReplaced, StringToTakeItsPlace, State1, fixed = TRUE))

giving:
  State1 StringToBeReplaced StringToTakeItsPlace State2
1    Aa1                  A                    D    Da1
2    aB1                  B                    F    aF1
3    aA1                  A                    G    aG1

or with dplyr:
library(dplyr)

DF %>%
 rowwise() %>%
 mutate(State2 = gsub(StringToBeReplaced, StringToTakeItsPlace, State1, fixed = TRUE)) %>%
 ungroup

A: Using stringr and tidyverse
Library(tidyverse)

DF <- tibble(
  State1 = c("Aa1","aB1","aA1"),
  StringToBeReplaced = c("A","B","A"),
  StringToTakeItsPlace=c("D","F","G")
)

  DF %>%
  mutate(State2 = str_replace(State1,
                                StringToBeReplaced,
                                StringToTakeItsPlace ))
#> # A tibble: 3 x 4
#>   State1 StringToBeReplaced StringToTakeItsPlace State2
#>   <chr>  <chr>              <chr>                <chr>
#> 1 Aa1    A                  D                    Da1
#> 2 aB1    B                  F                    aF1
#> 3 aA1    A                  G                    aG1

Created on 2018-03-03 by the reprex package (v0.2.0).


text:
Q: Abealian A of order $p^2q^3$ (distinct primes) contains an element of order $q^2$. Show all A that have a cyclic p-Sylow group I have the following practice problem:
Abealian group A of order $p^2q^3$ (distinct primes) contains an element of order $q^2$.
Show all A up to isomorphism that have a cyclic p-Sylow group:
I know that I have a p-Sylow groups of order $p^2$. So A must have an element of order $p^2$. So my answer is there is only one:
$Z_{p^2} \times Z_{q^2} \times Z_{q}$
Is this correct?


text:
Q: How to print a pdf using python without opening a PDF viewer I have a python aplication that creates a pdf using reportlab and print it. The current application just uses Adobe Acrobat to print it using the command:
os.startfile('.\\template.pdf','print')

What i really want is to print it in python without nedding to use Adobe Acrobat or any other pdf viewer. I just want to communicate directly with the printer.
Is there any way of to do this in python? I would be grateful if someone could help me with this.


text:
Q: Correct/Incorrect to ignore some React useEffect dependency warnings? Here's some sample code I've written that works fine:
useEffect(() => {
  if (!rolesIsLoading && rolesStatus === 200) {
    customer.roles = rolesData.roles;
  }
}, [rolesIsLoading, rolesStatus]);

I'm getting this warning in the console:

React Hook useEffect has missing dependencies: 'customer.roles' and 'rolesData.roles'. Either include them or remove the dependency array                                                                                react-hooks/exhaustive-deps

The thing is, the code works fine now and, in some cases, when I add such dependencies, as instructed, I end up with an endless loop or some other problem.
I'd appreciate any advice you might have as to how you resolved this when you've encountered a similar situation.

A: From React DOCS:

Conditionally firing an effect
The default behavior for effects is to fire the effect after every completed render. That way an effect is always recreated if one of its dependencies changes.
However, this may be overkill in some cases, like the subscription example from the previous section. We don't need to create a new subscription on every update, only if the source props has changed.
To implement this, pass a second argument to useEffect that is the array of values that the effect depends on. Our updated example now looks like this:
useEffect(
 () => {
   const subscription = props.source.subscribe();
   return () => {
     subscription.unsubscribe();
   };
 },
 [props.source],
);

So, from the exercpt above we see that the dependencies array serves the purpose to conditionally fire an effect.
That warning you're getting is because you're using some external (from the effect's perspective) variables in your effect function that you're not mentioning in the dependency array.
React is worried that you might be getting new values for those variables in future renders, and since your effect uses them, React "default intent" is to re-run that effect with the new variables values. So your effect would always be up to date.
So you need to think if you want to re-run your effect if/when those variables change in the future.
Basic recommendations:

*

*Add them to the dependency array

*If they never change, there will be no difference

*If they change, add some conditionals to your effect to decide whether you should do something based on the new variables values or not

*If they're changing only in reference, but not in value (like functions, arrays, objects, etc), you can use the useCallback or useRef hook to preserve the "reference" for those variables from the first render and not get new references on every render.


text:
Q: check if text box is empty then run code I have the following jquery and want to check if the text box is empty before the code is run:
<script type="text/javascript">
    $(document).ready(function () {
        if ($("#FNameTB").val().length < 0) {
            $("input#FNameTB").labelify({ labelledClass: "greylabel" });
        }
</script>

but its not working.

A: Length will never be less than 0.
if ( $("#FNameTB").val().length === 0 )

You can even add in a trim() to be thorough
if ( $("#FNameTB").val().trim().length === 0 )

A: Try
if ($("#FNameTB").val() == '')

A: Try the following
if ($('#FNameTB').val() === '') {
  // It's empty
}


text:
Q: node: npm start: how to run on 0.0.0.0:3000 I have a reactjs project made using create-react-app
In nodejs how to run npm start for 0.0.0.0:3000
I tried
npm start --host 0.0.0.0:3000

But i am not able to connect from any ip
package.json
{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
   ........
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.9.0"
  }
}

A: You can't just connect using CLI flags. You need to have files for example, to connect to port 3000 you'll need something like this:
const http = require('http')

const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.write('
Hello, Node.js!
');
    }
    res.end();
});

server.listen(3000)

this will create a web server listening to port 3000


text:
Q: Plotting different dataframe data in subplots I'm trying to plot data in two dataframes in two subplots. I'm referring to this link
import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt

df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))

plt.figure()
fig, axes = plt.subplots(nrows=1, ncols=2)

df1.plot(ax=axes[0, 0], style='o-')
axes[0, 0].set_xlabel('x')
axes[0, 0].set_ylabel('y')
axes[0, 0].set_title('ttl')

df2.plot(ax=axes[0, 1], style='o-')
axes[0, 1].set_xlabel('x')
axes[0, 1].set_ylabel('y')
axes[0, 1].set_title('ttl')

However, I get the following error
df1.plot(ax=axes[0, 0], style='o-')
IndexError: too many indices for array

Any suggestions on how to resolve this will be really helpful.
EDIT: The answer provided below works for 1 row with 2 cols
I'm facing an error for 2 rows and 2 cols
import pandas as pd
import numpy as np
from pprint import pprint
from matplotlib import pyplot as plt

df1 = pd.DataFrame(np.random.randn(10, 10))
df2 = pd.DataFrame(np.random.randn(10, 10))
df3 = pd.DataFrame(np.random.randn(10, 10))
df4 = pd.DataFrame(np.random.randn(10, 10))

pprint(df1)

plt.figure()
fig, axes = plt.subplots(nrows=2, ncols=2)

df1.plot(ax=axes[0], style='o-')
axes[0].set_xlabel('x')
axes[0].set_ylabel('y')
axes[0].set_title('ttl')

df2.plot(ax=axes[1], style='o-')
axes[1].set_xlabel('x')
axes[1].set_ylabel('y')
axes[1].set_title('ttl')

df3.plot(ax=axes[2], style='o-')
axes[2].set_xlabel('x')
axes[2].set_ylabel('y')
axes[2].set_title('ttl')

df4.plot(ax=axes[3], style='o-')
axes[3].set_xlabel('x')
axes[3].set_ylabel('y')
axes[3].set_title('ttl')

plt.show()

Error:
AttributeError: 'numpy.ndarray' object has no attribute 'get_figure'

Any suggestions?

A: Axes are one dimensional, you have to do like this:
df1.plot(ax=axes[0], style='o-')
df2.plot(ax=axes[1], style='o-')

I suggest reading this, look at the squeeze parameter and you will understand this is happening.


text:
Q: Dynamic select boxes based on previous choice I want to have on my site a single select box that will then populate new select boxes depending on what is chosen.
Say, if the user chooses "cat", then a new select box will appear with breeds of cats, or if they choose "dog", then a new select box will appear with a list of breeds of dogs. But before they choose either "dog" or "cat", then the second box will not exist.
Is there any way I can do this with CSS/HTML only, or do I HAVE to use javascript?
If I can do it with CSS/HTML only, please provide an example or link. If I have to use javascript, I do not need an example, just to be told that I have to use it.
Thank you for any help.

A: You will have to use javascript.  You cannot make ccs rules based on selections from a select.


text:
Q: Repeating values in Pascals triangle code I'm having an issue with printing the same values too many times in the same rows. The printInt method is what I'm using to create spacing between the values being printed and might be the cause of the issue. The nChoosek method is using the binomial equation to calculate the values being placed into the rows. The print method is the main printing method using all the helper methods.
    public class P2ascalsTriangle extends PascalsTriangleBase{
   protected int nChooseK(int n, int k) {
     int x= fac(n);
     int y= fac(k) * fac(n-k);
     int fac_n_y = (int) (x/y);
     return fac_n_y;
   }
   protected void printInt(int n){
      int[]   c= new int[n];
      for (int i=0; i<c.length; i++){
        System.out.printf("%5d",n);
      }
   }
   private static int fac(int num){
     int product = 1;
     for (int i=1; i<=num; i++){
       product*=i;
     }
     return product;
   }
   protected boolean heightOutOfRange(int height) {
     if(height<0);
        return false;
   }
    public static void main(String[] args){

    P2ascalsTriangle pascal = new P2ascalsTriangle();

    pascal.printTriangle(0);
    pascal.printTriangle(10);
    pascal.printTriangle(5);
    pascal.printTriangle(2);
  }
}

public class PascalsTriangleBase {

    /**
     * This field controls the line spacing of the output triangle.
     */
    protected boolean doubleSpace;

    /**
     * Simple constructor to set the value for the field.
     */
    public PascalsTriangleBase() {
        doubleSpace = false;
    }

    /**
     * This method is the primary printing method for the triangle.
     * Override this method to control the spacing between values in
     * the output triangle.
     * @param n The value to be printed
     */
    protected void printInt(int n) {
        System.out.print(n);
    }

    /**
     * This method calculates the binomial coefficient, n choose k. These
     * values are used to construct Pascal's Triangle. They are called
     * binomial coefficients because "n choose k" is the value of
     * the coefficient of the xk term in the expansion of
     * (1 + x)n.
     *
For this assignment, it should use the factorial algorithm; that is
     * the return value should be calculated as n! / (k! (n-k)!).
     * @param n The power for the binomial expansion
     * @param k The order of the term in the binomial expansion
     * @return The coefficient of the kth term.
     */
    protected int nChooseK(int n, int k) {
        return k;
    }

    /**
     * The is a special method that is used to print the first value in each
     * row of Pascal's triangle. The amount of "indent" for the line can be
     * determined by the parameter values.
     * @param row The number of the row being printed
     * @param height The height of the completed triangle
     */
    protected void printOne(int row, int height) {
        printInt(1);
    }

    /**
     * A simple input validation routine to see if the height is ok.
     * @param height The requested height for the triangle
     * @return True if the requested height is out of range
     */
    protected boolean heightOutOfRange(int height) {
        return false;
    }

    /**
     * The core method for this assignment. It prints out the triangle,
     * using the helper methods defined above. This method is marked with
     * the final keyword. This means that this method cannot be
     * overridden in a subclass. Notice that all of the helper methods
     * are not declared final, so they are all available for
     * overriding.
     * @param height The requested height for the triangle to be printed.
     */
    public final void printTriangle(int height) {
        System.out.println("Pascal\'s Triangle of height " + height);
        if(heightOutOfRange(height)) {
           System.out.println("Height is out of range. Cannot print Pascal's triangle.");
           return;
        }
        System.out.println();
        for(int row = 0; row < height + 1; row ++) {
            printOne(row, height);
            for(int col = 1; col < row + 1; col ++) {
                printInt(nChooseK(row, col));
            }
            System.out.println();
            if(doubleSpace) {
                System.out.println();
            }
        }
        System.out.println();
        System.out.println();
    }

}

A: I am having trouble following your code but I just wrote a method that prints a pascal's triangle for you:
public static void printPT(final int n) {
    ArrayList<Integer> layer = new ArrayList<>();
    layer.add(1);
    for (int i = 0; i < n; i++) {
        ArrayList<Integer> newLayer = new ArrayList<>();
        newLayer.add(1);
        for (int j = 0; j < i; j++) {
            newLayer.add(layer.get(j) + layer.get(j + 1));
        }
        newLayer.add(1);
        for (int num : layer) {
            System.out.print(num + " ");
        }
        layer = newLayer;
        System.out.println();
    }
}


text:
Q: How do I save a NamedTemporaryFile into a model FileField in Django? I created a NamedTemporaryFile, added some content in it and now I want to save it into a model FileField.
The problem is that I get a SuspiciousOperation because the tmp directory is not within the FileSystemStorage directory.
What's the proper way to do this?

A: You want django to check it for you because it ensures file is put inside MEDIA_ROOT dir so it's accessible for download.
In any case you want to put files outside MEDIA_ROOT (in this case '/tmp') you should do something like this:
from django.core.files.storage import FileSystemStorage
fs = FileSystemStorage(location='/tmp')

class YourModel(models.Model):
    ...
    file_field = models.FileField(..., storage=fs)

see Django documentation

A: I ended up doing the oposite way romke explains: I'm creating the temporary file in the MEDIA_ROOT.
Another solution could be working with the file in /tmp and then moving it to MEDIA_ROOT.
My initial confusion comes from the way forms are working with uploaded files: they are located in the /tmp directory (or in memory) and then moved automatically to the upload_to directory. I was looking for a generic way of doing it in Django.


text:
Q: While trying to encode a pointcloud I keep getting the same errors. I have tried to changing my environment and updating Glibcxx version and yet $ python vmuc.py compress /home2/kubra/JPEG/Stanford_Area_2.ply ../models/Geometry-only/Codec/0.00025/checkpoint_best_loss.pth.tar ../results/G0.00025
Traceback (most recent call last):
  File "/home2/kubra/JPEG/JPEG_PCC_VM/jpeg-pleno-pc-vm-main/src/vmuc.py", line 13, in <module>
    import loss_functions
  File "/home2/kubra/JPEG/JPEG_PCC_VM/jpeg-pleno-pc-vm-main/src/loss_functions.py", line 3, in <module>
    from sklearn.neighbors import NearestNeighbors
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/sklearn/__init__.py", line 82, in <module>
    from .base import clone
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/sklearn/base.py", line 17, in <module>
    from .utils import _IS_32BIT
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/sklearn/utils/__init__.py", line 29, in <module>
    from .fixes import parse_version, threadpool_info
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/sklearn/utils/fixes.py", line 19, in <module>
    import scipy.stats
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/stats/__init__.py", line 467, in <module>
    from ._stats_py import *
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/stats/_stats_py.py", line 39, in <module>
    from scipy.spatial.distance import cdist
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/spatial/__init__.py", line 105, in <module>
    from ._kdtree import *
  File "/home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/spatial/_kdtree.py", line 5, in <module>
    from ._ckdtree import cKDTree, cKDTreeNode
ImportError: /lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.29' not found (required by /home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/spatial/_ckdtree.cpython-39-x86_64-linux-gnu.so)``

I'm currently working on point clouds codec. I tried encoding a point cloud but I keep getting the same error:
"/lib/x86_64-linux-gnu/libstdc++.so.6: version \`GLIBCXX_3.4.29' not found (required by /home/kubra/anaconda3/envs/myenv/lib/python3.9/site-packages/scipy/spatial/\_ckdtree.cpython-39-x86_64-linux-gnu.so)"

It says, apparently the version of GLIBCXX is not found whatsoever.. I tried updating my libstdc, creating new env with updated packages etc but it didnt workk for me. I have no idea  of why it doesn't work and what I need to do. Could anyone please tell me what should I do?


text:
Q: Solve $\int_{A} \frac{x^2y + y^3 - y}{x^2 + y^2} \, dx + \frac{x^3 + xy^2 + x}{x^2 + y^2} \, dy$ Solve $\displaystyle
\int_{A} \frac{x^2y + y^3 - y}{x^2 + y^2} \, dx
       + \frac{x^3 + xy^2 + x}{x^2 + y^2} \, dy
       $ , $A$ is the unit circle.
My attempt:
$\displaystyle
\int_{A} \frac{x^2y + y^3 - y}{x^2 + y^2} \, dx
       + \frac{x^3 + xy^2 + x}{x^2 + y^2} \, dy
       =\int_A ydx+xdy-(\frac{y}{x^2 + y^2}dx+\frac{x}{x^2 + y^2}dy)=\displaystyle\int_A ydx+xdy+\int_A(\frac{y}{x^2 + y^2}dx+\frac{x}{x^2 + y^2}dy)$
First,using Green's theorem  $\displaystyle\int_A ydx+xdy =0 $.
Second, $\int_A(\frac{y}{x^2 + y^2}dx+\frac{x}{x^2 + y^2}dy)$
Denote $x=\cos\theta,y=\sin\theta \implies dx=-\sin\theta,dy=\cos\theta$.
Therefore , $\int_A(\frac{y}{x^2 + y^2}dx+\frac{x}{x^2 + y^2}dy)=\int_0^{2\pi}-sin^2(\theta)+cos^2(\theta)=0$
$\displaystyle
\int_{A} \frac{x^2y + y^3 - y}{x^2 + y^2} \, dx
       + \frac{x^3 + xy^2 + x}{x^2 + y^2} \, dy=0$
My answer isn't correct , can't find out what I am doing , appreciate any help.

A: It's just a sign mistake. You should have that
$$\int_{A} \frac{x^2y + y^3 - y}{x^2 + y^2} \, \mathrm{d}x+ \frac{x^3 + xy^2 + x}{x^2 + y^2} \, \mathrm{d}y=I_1+I_2\, ,$$
where
$$I_1=\int_A \left(y~\mathrm{d}x+x~\mathrm{d}y\right)\, ,$$
$$I_2=\int_A \left(\color{red}{-}\frac{y}{x^2+y^2}~\mathrm{d}x+\frac{x}{x^2+y^2}~\mathrm{d}y\right)\, .$$
As you correctly noted, $I_1=0$ by Green's theorem. You can compute $I_2$ either by using the same method you have tried, i.e. using the parametrisation $x=\cos(\theta)$, $y=\sin(\theta)$, or by simply noting that
$$-\frac{y}{x^2+y^2}~\mathrm{d}x+\frac{x}{x^2+y^2}~\mathrm{d}y=\mathrm{d}\left(\arctan\frac{y}{x}\right).$$


text:
Q: Inconsistent behaviour with pages created with onenote-api - fixed with OneNote update Looking for some help please from the onenote team! I have a page generated by the onenote api that could be opened by the previous version of onenote for mac, ios and android but now fails (most other pages generated by the onenote-api work fine). It still opens fine in the online version of onenote. If I copy the page to the same section online then both pages can be opened on the tablet devices.It would be great to work out if this is a problem in the onenote-api or the recent onenote update.I'm happy to send a copy of the affected onenote section or link to a dummy notebook.The current work around is to roll all the android tablets at work back to the previous working version, but this is not so easy with ios devices.
FURTHER FURTHER UPDATEThanks Vishaal. The latest ios + android updates fix the issue.Cheers Steve


text:
Q: Designing a simple library database I am currently developing a simple book library system in ms access 2007 and need some help with the database design. I want to register books, borrowers and loans, so I assume that my database could consist of these three entities.

*

*Borrower

*Loan

*Book

The relationships between the tables are as so:
Borrower has a 1 to many relationship with Loan.
Loan has a 1 to many relationship with Book.
The problem with this approach is that you can not create a row in the Book table without assigning a foreign key value; thus referencing the foreign key loanId of Book table with the related primary key in the Loan table. It breaks the referential integrity and it's not possible to create a book without relating it to a loaner.
So I think I need a join table between Book and Loan. This table should consist of the 2 primary keys from Book and Loan (a composite key). So there is a 1 to many relationship between Book and BookLoan and a 1 to many between Loan and BookLoan.
Is my way of thinking correct ? I can't figure out why I need the join/junction table between loan and book. Is there a more simple solution to my problem?
Thanks in advance :)
EDIT: I have added a E/R-diagram which has been corrected in respect to the answer, I have received.

A: I believe you are assigning the Foreign key on Book to Loan. It should be just the opposite and be on Loan to Book. The Book doesn't need a comparative loan but every loan needs a comparative book.
Both of your foreign keys should exist on Loan.


text:
Q: Why are the Xi baryons called "cascade" also? Between the Lambda, Sigma, Xi, and Omega baryons, only the Xi family has an alternate name - cascade. This must be a result of the "particles zoo" and my guess is that the particles cascade in the accelerator is related. Why is this family the only one with this "unconventional" name?

A: The first observation  paper:

Neutral Cascade Hyperon Event
Luis W. Alvarez, Philippe Eberhard, Myron L. Good, William Graziano, Harold K. Ticho, and Stanley G. Wojcicki
Phys. Rev. Lett. 2, 215 – Published 1 March 1959

Has the world Cascade Hyperon in the title
And in this wiki article

Ξ0 and Ξ− are also known as "cascade" hyperons, since they go through a two-step cascading decay into a nucleon.

If the discovery paper did not mention the new particle as Ξ ( I do not have access to the PRL) it is the same reason as the J/psi double name, two different namings, the "cascade" part honoring the first discovery.
Ξ is the next unused letter after Λ , μ being used for muon, and ν used for the neutrino.

A: That one's easy: the Greek letter for "Xi" is $\Xi$, which looks like a three-step cascade.


text:
Q: Applescript conversion to Bash I would like to make sure that an applescript can be converted to bash. Are there any ideas on how to do this? And if so, I'll place a simple applescript below to give you an example of how the script runs. In more clarity, I simply want a bash script or shell script to do what my applescript is doing. I want it to "enable" or change the default of the switch in system preferences, under "energy saver" that reads ...'start up automatically after a power failure'...:
set uiScript to "click checkbox \"Start up automatically after a power failure\" of list 2 of group 1 of window \"Energy Saver\" of application process \"System Preferences\""
run script "tell application \"System Events\"
" & uiScript & "
end tell"

*

*any ideas on how to convert this script?

Thanks,
-Unimachead

A: You may not actually need to convert it - you can run AppleScript from within a bash script, using osascript.
$ man osascript
Note that you can run AppleScript either from a file or just include the source on the command line.


text:
Q: Instantiating objects within another class in Excel VBA I'm working on a project using Excel VBA where I have a number of datasets, each populated with a number of 'patients' which have a number of parameters (such as treatment, outcome etc.). To handle this, I intend to create a class called 'patient', with properties such as treatment and outcome. Then create a class called 'dataset', with a public property of 'patient'. I've created the classes, and I can instantiate a dataset object. But how do I go about instantiating patient object, or ideally an array of patient objects within the dataset object?
Dataset class module:
Private pNumber As Integer
Public Patient As Patient

Public Property Get Number() As Integer
    Number = pNumber
End Property
Public Property Let Number(p As Integer)
    pNumber = p
End Property

Patient class module:
Private pID As Integer
Private pTreatment As Boolean
Private pResponse As Single

Public Property Get ID() As Integer
    ID = pID
End Property
Public Property Let ID(p As Integer)
    pID = p
End Property

Public Property Get Treatment() As Boolean
    Treatment = pTreatment
End Property
Public Property Let Treatment(p As Boolean)
    pTreatment = p
End Property

Public Property Get Response() As Single
    Response = pResponse
End Property
Public Property Let Response(p As Single)
    pResponse = p
End Property

Main Module
Sub main()

Dim data1 As Dataset
Set data1 = New Dataset

'code to instantiate array of patient within data1 here

End Sub

A: The dataset will be better appointed something like this.
I would call the class what it is intended to be, so Patients:
private colPatients as new collection

public function add(aPatient as patient)
  colPatients.add aPatient, aPatient.Id
end function

public property get count() as long
  count = colPatients.count
end property

public property get items() as collection
  set items = colPatients
end property

public property get item(vItem as variant) as patient
  set item = colPatients(vItem)
end property

public sub remove(vItem as variant)
  colPatients.remove vItem
end sub

So to use:
dim patientCollection as patients
Sub main()

Set patientCollection = New patients

'code to instantiate array of patient within data1 here
IDs = Array(1,2,3)
treats = array("x","y","z")

dim x as integer
dim p as patient
for x = lbound(IDs) to Ubound(IDs)
   set p= new patient
   p.id = IDs(x)
   p.treatment = treats(x)
   patientCollection.add p
   set p = nothing
next x

End Sub


text:
Q: how can I add a new value and delete the old one from a .innerText I'm starting to study programming and I am trying to make a calculator with html css js with my learning so far. But I got stuck in one part: my calculator shows the value typed in currentvalue.innerText and when it receives an operation, the value appears on top of it, in previousvalue.innerText, I wanted the currentvalue to be reset only when the person inserts a new number, then I could extract the new value in a variable called num2 and use it to do the math
this is the part of the function that I am talking about:
function insert(value){

    if (value === '/'|| value ==='*'|| value === '-'|| value === '+'){

        previousOperation.innerText = currentOperation.textContent + ` ${value}`;
        num1 = previousOperation.innerText.slice(0, -2);

        op = value;

        return
    }

    if(value === '.') {
        currentOperation.innerText += '.'; // O '0' inicial permanece e é adicionado um ponto
    } else if (currentOperation.innerText === '0'){ // Exclui o 0 inicial e adiciona o value digitado direto
        currentOperation.innerText = value;
    } else {
        currentOperation.innerText += value;
    }
}

I tried resetting the currentvalue.innerText, but only when the previoustvalue.innerText already had a value, but doing that it only shows one number at a time in my currentvalue.innerText, it doesn't save the value and show all the others typed

A: You must convert 'currentOperation.innerText' and 'value' to numbers before applying the formula.
if(value === '.') {
    currentOperation.innerText += '.'; // O '0' inicial permanece e é adicionado um ponto
} else if (currentOperation.innerText === '0'){ // Exclui o 0 inicial e adiciona o value digitado direto
    currentOperation.innerText = value;
} else {
    const previousNumber = parseInt(currentOperation.innerText)
    const currentNumber = parseInt(value);

    currentOperation.innerText = `${previousNumber + currentNumber}`;
}


text:
Q: Each loop with return false only shows first result I would like to show a point score and user name for 10 entries (class "horse") on button click, which concatenates the value in an image's alt and title tags, attached to a class "lane" for each entry. If I include "return false" to end the each() loop, this function only shows the value for the first entry on each entry. If I exclude return false, all of the values appear on all of the entries. I need help understanding how to display just the value of each entry on the respective entry.
Adding HTML sample by request:

$('.showLabels').on('click', Labels);

function Labels() {
    $('.horse').each(function() {
        var imgTitle = (AJS.$(this).attr('title'));
        var imgAlt = (AJS.$(this).attr('alt'));
        var fullTag = "
" + imgAlt + " - "
                          + imgTitle + "
";

        // show image title
        AJS.$('.lane').before(fullTag);

        // return false stops the each loop.
        return false;

    });
};

A: You should use a predicate instead if you need to use the return boolean of the function you are applying on each element:
$('.showLabels').on('click', Labels);
var predicate = true;
function Labels() {
    $('.horse').each(function () {
        var imgTitle = (AJS.$(this).attr('title'));
        var imgAlt = (AJS.$(this).attr('alt'));
        var fullTag = "
" + imgAlt + " - " + imgTitle + "
";
        AJS.$('.lane').before(fullTag);
        predicate = predicate && false;
    });
};

//do something with predicate

This is just an idea, the "false" will always change your predicate to false, instead of "false" you should use whatever condition you need to use there.

A: Try this code
$('.showLabels').on('click', Labels);
function Labels() {
$('.horse').each(function(i,val) {
var imgTitle = (AJS.$(this).attr('title'));
var imgAlt = (AJS.$(this).attr('alt'));
var fullTag = "
" + imgAlt + " - "
                    + imgTitle + "
";

// show image title
AJS.$('.lane').before(fullTag);

// return false stops the each loop.
if(i==9)
return false;

});
};


text:
Q: I want to use command "bin/nutch inject" to inject my crawling URLs I want to use command bin/nutch inject to inject my crawling URLs but I get an error
'nutch' is not recognized as an internal or external command,
operable program or batch file.

Where do I enter this command? I am presently typing this command on the path C:\Users\Gaurav Kandpal\Desktop\elastic\apache-nutch-2.3-src\apache-nutch-2.3\runtime\local\b on command prompt.

A:
Follow steps to install nutch in windows :

1) download and install cygwin from : https://www.cygwin.com/
2) download nutch from : http://nutch.apache.org/downloads.html
3) paste nutch downloaded and extracted file into C:\cygwin64\home\
4) open cygwin terminal and type given commands

 - $ cd C:
 - $ cd cigwin64
 - $ cd home
 - $ cd apache-nutch
 - $ cd src/bin
 - $ ./nutch

you will get given output :

Usage: nutch COMMAND
where COMMAND is one of:
 inject         inject new urls into the database
 hostinject     creates or updates an existing host table from a text file
 generate       generate new batches to fetch from crawl db
 fetch          fetch URLs marked during generate
 parse          parse URLs marked during fetch
.
.
.
.

A: First, please check did you compile the Nutch source code. Then, you should try to run from here /path/to/nutch/runtime/deploy/bin as well in the case you deploy Nutch on a cluster.


text: Q: Python: How do I create something that will show the coordinates of my screen when I click? I've been trying to create a cool auto clicker as a little project. How exactly can I create something that will tell me what my mouse coordinates are when I click?


text:
Q: How to use macro function for multiple  in xml with xPath? I need to extract address, telephone no using xPath from my html page. My
address is sometimes within one `<p>`, else within two `<p>`. I have 11
stores.
This is the html tag
 in my xml. (Just an example)

 ==$0

36 rue de la Verrerie 75004 PARIS

Tél : 0111 222 222

 ==$0

11 rue des archives

75004 PARIS

Tél : 01 11 11 11 11

1st shop: P1 =address P2= tel
2nd shop P1= address P2 = tel P3 = fax
3rd shop P1=address line 1 P2 = address line 2 P3= tel
4th : P1 = address P2 = tel
5th : P1= add P2 = tel
Shops 6,7,8,9,11 : P1 = add line 1 P2 = add line 2 ( they have no
telephone)
10th shop : P1= add line 1 P2= addline 2, P3= tel, P4= space P5 = email

I tried with,

{
            "name": "store Addr",
            "key": "Address",
            "xPath": "(//div[@class='info-block-value']/p)[1] |
                     (//div[@class='info-block-value']/p)[2]",
            "level": 0,
            "enabled": true,
            "values": []
          },
          {
            "name": "Tel No",
            "key": "TelephoneNumber",
            "xPath": "(//div[@class='info-block-value']/p)[2]|
                     (//div[@class='info-
                     block-value']/p)[3]",
            "regex": "Tél : ((\d+\s*)+)+",
            "level": 0,
            "enabled": true,
            "values": []
          }

But I'm not getting the correct results. Can someone help me this?

Results:

id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives                   01 11 11 11 11

Expecting results
id name address                               phone
1  a    36 rue de la Verrerie 75004 PARIS     0111 222 222
2  b    11 rue des archives  75004 PARIS      01 11 11 11 11

A: You basically need all the
 but the last one for the address, and the last one for the telephone number.
So, get the address with
//div[@class="info-block-value"]/p[position() < last()]

and similarly, the telephone number is under
//div[@class="info-block-value"]/p[last()]


text:
Q: problema de URL no codeigniter 3 Eu tenho uma aplicação em um servidor:
http://192.168.0.200/aplicacao
Quando faço autenticação para acessar aparece este erro:

The requested URL /aplicacao/auth/login was not found on this server.

Pesquisei e vi que pode ser no arquivo .htaccess. Alterei ele mas continua igual:
Options +FollowSymLinks
Options -Indexes
DirectoryIndex index.html index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /aplicacao/index.php/$1 [L,QSA]

Ocorre o mesmo erro citado acima.
Quando eu tinha a aplicação no localhost, funcionava sem problemas e eu configurei os arquivos do codeigniter para url amigável.

A: Pode ser o .htaccess mesmo e relacionado com a sobrescrita de URL do servidor. Para usar URL amigável (excluindo o index.php da URL) é preciso configurar o .htaccess da raiz do projeto da seguinte forma:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php/$0 [PT,L]

Em seguida é preciso verificar se a sobrescrita de URL está ativa no servidor. você deve ativar da seguinte forma:

*

*Abra o arquivo httpd.conf do servidor web;

*Descomente a linha LoadModule rewrite_module modules/mod_rewrite.so retirando o # do início da linha (ou outro caracter de comentário que existir);

*Reinicie o servidor.


text:
Q: prove that $3$ does not divide $n^2+1$ How do I prove that $3$ does not divide $n^2+1$, for all $n\in\mathbb{Z}$, thought of in separate cases, but did not get, induction also was unable to ....

A: Hint:
The squares of the elements in $\mathbb{Z}/3\mathbb{Z}$ are $\bar{0}^2=\bar{0},\bar{1}^2=\bar{1},\bar{2}^2=\bar{1}$.

A: Suppose $\,3\mid \color{#0a0}{n^2+1}.\ $ Note $3$ divides one of $\,n\!-\!1,\ n,\ n\!+\!1.\,$ But $\,3\nmid \color{#c00}n\,$ else $\,3\mid 1 = \color{#0a0}{n^2+1}-\color{#c00}n\cdot n$.
Hence $\,3\mid \color{#c0d}{n\!-\!1}\,$ or $\,3\mid \color{#c0d}{n\!+\!1}\,$ so $\,3\mid 2 = \color{#0a0}{n^2+1}-\color{#c0d}{(n\!-\!1)(n\!+\!1)},\,$ contradiction
Said modly, $\ {\rm mod}\ 3\!:\ \color{#c00}{n\equiv 0}\,\Rightarrow\, n^2+1\equiv 1,\ $ and $\, \color{#c0d}{n\equiv \pm1} \,\Rightarrow\, n^2+1\equiv 2$

A: I don't know if you know modular arithmetic or not, but write $n = 3k + r$ where $r$ is $0, 1, $ or $2$.  Then $n^2 = (3k + r)^2 = 9k^2 + 6kr + r^2 = 3k' + r^2$, where $k'$ is a different number as you see.  So $n^2 + 1 = 3k' + r^2 + 1$.  What can $r^2$ possibly be?  Well, $r$ can be $0, 1,$ or $2$.  In which case you have $r^2 + 1 = 1$, $2$ or $5$.  In none of these cases do you see that 3 divides $n^2 + 1$.  If you know modular arithmetic, see user1337's post.

A: Hint:
For 3 to divide $n^2 + 1$ then $n^2+1$ must be of the form 3k. Then look at $n^2$ for any integer of the form $2k$ or $2k+1$. $(2k)^2 = 4k^2$ or $2(2k^2)$, even, and $(2k+1)^2 = (2k+1)(2k+1) = 4k^2+4k+1 = 2(2k^2+2k)+1$, odd.
You can then easily see that any integer of the form $n^2+1$ is either of the form $2k+1$ or $2k+2$, and clearly neither are divisible by 3.

A: Here is a stronger result:
If a prime $3 \pmod 4$ divides the sum of two integer squares, it must also divide each of those squares.


text:
Q: gsutil cp failed with "Redirected more times than rediection_limit allows" I am copying a tarball from a GKE container to GCS, and I am seeing the error "Redirected more times than rediection_limit allows" once a while.
The command I ran:
gsutil -o GSUtil:parallel_thread_count=1 -o GSUtil:parallel_composite_upload_threshold=250M -o GSUtil:parallel_process_count=18 cp XXX.tar.gz gs://path/to/object
And when I tried to resume the upload, I still got:
Redirected more times than rediection_limit allows.
CommandException: Some temporary components were not uploaded successfully. Please retry this upload.
What could be the cause of this issue and how can I solve/alleviate this issue?
gsutil will try to reuse some of the temporary files from last upload, could this be the reason why the upload can not be resumed?


text:
Q: Use CSS grid to make multiple different-width columns wrap? I am testing CSS grid for my new responsive layout, but I am having a problem with wrapping.
I have a nav bar with a header that should be pushed to the left and 4 buttons that should be pushed to the right. The problem right now is that using:
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr))

Makes, as expected 5 evenly spaced and responsive grid cells. The problem is that I want the button cells to be significantly smaller than the header. So instead of it being 1fr 1fr 1fr 1fr 1fr, I want 8fr 1fr 1fr 1fr. How can I do this while still keeping the wrapping/responsive properties of using repeat autofit?
Codepen example illustrating the problem: https://codepen.io/johnpyp/pen/ZJxdYK

.grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
}

.grid>* {
  align-text: center;
  background-color: lightgreen;
  height: 200px;
}

I want this to be 8fr, but it is 1fr like the rest.

1fr

1fr

1fr

A: You can tell the first grid item to span 8 columns:
.grid > div:first-child {
  grid-column: span 8;
}

https://codepen.io/anon/pen/JyLQRB?editors=1100

A: .grid {
  display: grid;
  grid-gap: 10px;
  grid-template-columns: 8fr 1fr 1fr 1fr;
}

https://css-tricks.com/snippets/css/complete-guide-grid/#fr-unit


text:
Q: Kotlin unresolved reference to local package File ./Main.kt:
import numbers

fun main() {
    var value = numbers.sum(7, 4)
}

File ./numbers/Operations.kt:
package numbers

fun sum(val1: Int, val2: Int): Int {
    return val1 + val2
}

Running the command kotlinc Main.kt outputs:
Main.kt:1:8: error: unresolved reference: numbers
import numbers

Main.kt:4:17: error: unresolved reference: numbers
var value = numbers.sum(2, 3)

If I try to add import java (I am new in Kotlin ans I saw someone imported this. I thought it is a part of a standard library) then output also contains:
Main.kt:1:8: error: packages cannot be imported
import java

What I did wrong?
SOLUTION (Thanks to @gidds):
Was need to pass each file to the complier, not like with Java compiler (javac)
kotlinc Main.kt numbers/Operations.kt

A: numbers is a package.  And, as the error says, packages cannot be imported.  Only classes, functions, or properties.
If you import numbers.sum, you should find you can call it with e.g. sum(7, 4).
Or you could call its fully-qualified name directly, without the import: numbers.sum(7, 4).
It's the same with java, which is also a package.  You can import java.util.concurrent.ConcurrentHashMap (a class), but not java, java.util, nor java.util.concurrent (which are all packages).  (Java has the same restriction.)


text:
Q: Calling python method I am newbie to python object oriented programming. I am trying to understand binary tree implantation code using python.
My understanding is object.method is the way to call the function. But here the object is called as object[key]="value" without explicitly calling the function like object.put("key","value) . Please help me to understand this code.

A: Like many languages that support object-oriented programming, Python has operators that can be overloaded by different classes as appropriate.
For example, when you write x + y, that calls x.__add__(y) (slightly oversimplified, but not in ways that are relevant here).
The [] here is just another operator. When you write object[key]="value", that calls object.__setitem__(key, "value").
So, you are doing object-oriented method calling, just with a little bit of syntactic sugar on top to make it more readable.


text:
Q: Setting RDP initial program via local group policy I'm on Windowws 2008 server and I am trying to set the startup application for Remote Desktop sessions via the Local Group Policy Snap-in.
When I log in via RDP it does run my configured application, but it does not use the Working Directory I specified (It is always c:\windows\system32 no matter what I put in the box).  Are there any known issues with this functionality?
The same thing also happens when I configure an individual users 'Environment' settings to launch an app during login.

A:
Try to do this from Remote Desktop Session Host Configuration


text:
Q: The `%in%` operation is not correct for integer64 The %in% operator is not providing correct output for integer64
x <- bit64::as.integer64("9219348897572232380")
y <- bit64::as.integer64("9221407835133917342")
x == y
# FALSE
x %in% y
# TRUE

A: The issue was that I didn't call the library(bit64), hence, bit64 specific %in% wasn't dispatched. Thanks @akrun
library(bit64)
x <- bit64::as.integer64("9219348897572232380")
y <- bit64::as.integer64("9221407835133917342")
x == y
# FALSE
x %in% y
# FALSE


text:
Q: css precedence with same levels Consider the following example https://jsfiddle.net/wdvpubau/4/.
In this example both display:block and float:left are of same specificity which is 2.Still why , display:block is overriden and float:left takes precedence.
Ideally display:block should have displayed 4 divs one below the other

A: display and float don't interact the way you think. Elements that have display: block can still float next to each other if their width allows it.
In other words, float has precedence over display when it comes to placing elements.


text:
Q: Drawing a half-full bottle in TikZ I want to fill half of the bottle. I tried these kind of commands:
%\filldraw[color=black!100, fill=cyan!30, very thick](-3,-2.4) arc (180:230:2.5) .. controls (-2,-5) and (-1.9,-5.2) .. (-1.8,-5.5) ;
But I failed. Here is the bottle:
\documentclass[11pt,a4paper,oneside]{article}
\usepackage[a4paper,left=3cm,right=2cm,top=2.5cm,bottom=2.5cm]{geometry}
\usepackage[utf8x]{inputenc}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}[xscale=1,yscale=1]

\draw[very thick](0,0) arc (0:180:1.5);
\draw[very thick] (-3,0) -- (-3,-2.5);
\draw[very thick] (0,0) -- (0,-2.5);
\draw[color=black!100,very thick](-3,-2.5) arc (180:235:3);
\draw[color=black!100,very thick](0,-2.5) arc (0:-55:3);
\draw[very thick] (-1.25,-4.95) -- (-1.25,-5.2) -- (-1.7,-5.2) -- (-1.7,-4.95);

\end{tikzpicture}
\end{document}

What I want:

A: \documentclass[border=5pt,tikz]{standalone}

\begin{document}
    \begin{tikzpicture}[xscale=1,yscale=1]
    \fill[blue!20] (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);

    \fill[white] (0,0) arc(0:180:1.5) --+ (0,-2) -| cycle;

    \fill[blue!10] (-1.5,-2) circle ({1.5cm-0.4pt} and 0.5cm); % Thank you, marmot! ;)

    \draw[very thick] (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);
    \end{tikzpicture}
\end{document}

Output: See below
Explanation:
Maybe beginners don't know the clip option and maybe the want just a type of "trivial" answer, so I had the following idea:
Let's fill the whole bottle with blue color and the just fill the upper part of it with white color. So we get at the end a bottle, which just a part is colored blue. The line
\fill[white] (0,0) arc(0:180:1.5) --+ (0,-2) -| cycle;

Does the following: It constructs the following path: It fills the arc at the top of the bottle, so we moved from point (-3,0) to the point (0,0). Now, we are going from the last point two cm down, but we want TikZ to calculate that point, so we write … (x_1,y_1) --+ (0,-2), which gives us the coordinate (x_1,y_1 + (-2)) = (x_1,y_1-2). Now we have got three points, and want to cycle the path. The option -| gives us the y coordinate from the point (x_1,y_1 + (-2)) = (x_1,y_1-2) and the x coordinate of the point (0,0). The word cycle means that we draw our path to the initial point.
P.S.: {1.5cm-0.4pt} (from the circle): in curly braces we let TikZ calculate the difference; 4pt is the thickness of the line of the bottle.
EDIT:
A little bit better solution:
\documentclass[border=5pt,tikz]{standalone}

\begin{document}
    \begin{tikzpicture}[xscale=1,yscale=1]
    \clip (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);

    \fill[blue!20] (-3,-5.5) rectangle ++(3,3.5);

    \fill[blue!10] (-1.5,-2) circle ({1.5cm-0.4pt} and 0.5cm);

    \draw[very thick] (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);
    \end{tikzpicture}
\end{document}

Explanation:
We can just "clip" the bottle: everything, what we draw, is now in the area of the bottle. Everything outside that area is invisible. So we just clip the bottle and fill a rectangle, such it fills a certain area of the bottle.
Output:

EDIT:
For Sebastiano:
\documentclass[border=5pt,tikz]{standalone}
\usetikzlibrary{decorations.text,backgrounds}
\definecolor{wine}{RGB}{216,198,62}
\definecolor{bottle}{RGB}{76,163,58}
\tikzset{
    my/.style={
        postaction={decorate},decoration={text along path,
            text={#1},text align=center}
    }
}
\begin{document}
    \begin{tikzpicture}
        \begin{scope}
            \clip (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);
            \fill[inner color=bottle!50,outer color=bottle] (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);
                \fill[wine!60] (-3,-5.5) rectangle ++(3,3.5);
                \fill[wine!40] (-1.5,-2) circle ({1.5cm-0.4pt} and 0.5cm);
            \foreach \x in {-5,-4.9,...,5}
            \foreach \y in {-5,...,-3}
            {
                \pgfmathsetmacro\opacity{random(1,10)*(1/10)}
                \pgfmathsetmacro\radius{random(1,2)*(.05/2)}
                    \fill[white,opacity=\opacity] (\x+1.3*rnd,\y+1.4*rnd) circle(\radius);
            }
            \draw[very thick] (0,-2.5) --+ (0,2.5) arc (0:180:1.5) -- (-3,-2.5) arc (180:235:3) --+ (0,-.25) --+ (.45,-.25) --+ (.45,.015) (0,-2.5) arc (0:-55:3);
            \path[my={The magic of Ti{\emph{\color{orange}k}}Z}] (-3.5,.5) arc(-180:0:2 and 1);
           \end{scope}
    \end{tikzpicture}
\end{document}

Output:

A: This looks like a code golfing challenge ;)
\documentclass[tikz,border=7pt]{standalone}
\usetikzlibrary{svg.path}
\begin{document}
  \begin{tikzpicture}[scale=3]
    \draw svg{M6 0V8A6 6 0 0 1-6 8V0};
    \draw[fill=blue!20] svg{M6 0c0-9-3-11-5-13v-1h-2v1c-2 2-5 4-5 13};
  \end{tikzpicture}
\end{document}


text:
Q: Fitting curve to non-decreasing data I have the below data. I want to fit a non-decreasing curve for this data.
But, althouhg its grağh seems so regular, I couldn't find a suitable form of function. What kind of function may be suitable for the data.
I will be very glad for any help. Thanks a lot.
1   0,732624193
2   1,200108125
3   1,68811084
4   2,24460301
5   2,639797804
6   3,129340857
7   3,59578095
8   4,075671738
9   4,499706618
10  4,938809576
11  5,357368819
12  5,775935121
13  6,152748142
14  6,542909935
15  6,917884709
16  7,318374759
17  7,706887198
18  8,024342485
19  8,386742193
20  8,759473838
21  9,096697903
22  9,442161132
23  9,776189454
24  10,04685275
25  10,44737472
26  10,73286187
27  11,07501659
28  11,34340416
29  11,61706181
30  11,91219663
31  12,19997992
32  12,46160562
33  12,64493511
34  12,87722319
35  13,09525623
36  13,33787142
37  13,57410201
38  13,78410808
39  13,96788738
40  14,19974498
41  14,40126277
42  14,63074118
43  14,91062441
44  15,20221408
45  15,42637581
46  15,63486103
47  15,82855433
48  15,97395587
49  16,16364445
50  16,34061186
51  16,46713061
52  16,60904203
53  16,77117154
54  16,93843089
55  17,15597228
56  17,3065981
57  17,4533185
58  17,57796846
59  17,72241579
60  17,86958431
61  18,08499505
62  18,22227803
63  18,34658856
64  18,4970054
65  18,62637386
66  18,75224401
67  18,82904471
68  18,92908889
69  19,01882395
70  19,12175476
71  19,21370787
72  19,29834989
73  19,36350613
74  19,48827906
75  19,54979572
76  19,63089052
77  19,72275485
78  19,77992057
79  19,85039546
80  19,93103915
81  20,03867987
82  20,13624479
83  20,16631002
84  20,27487258
85  20,36274989
86  20,41147668
87  20,50257231
88  20,51992914
89  20,55399805
90  20,59546524
91  20,6024585
92  20,65952735
93  20,72986288
94  20,76867903
95  20,85908945
96  20,94532696
97  20,96286849
98  21,00325095
99  21,06156886
100 21,08856307
101 21,12465402
102 21,17790176
103 21,17790176
104 21,22095988
105 21,24269251
106 21,28008352
107 21,31208712
108 21,33563444
109 21,3535785
110 21,37156164
111 21,38304028
112 21,39212703
113 21,42192738
114 21,42192738
115 21,43789942
116 21,47142078
117 21,51139773
118 21,53466036
119 21,54447502
120 21,5572884
121 21,5572884
122 21,59681046
123 21,6070952
124 21,6070952
125 21,6070952
126 21,6507205
127 21,66113255
128 21,6718944
129 21,6718944
130 21,6718944
131 21,6718944
132 21,72442301
133 21,74277312
134 21,74277312
135 21,74277312
136 21,74277312
137 21,74277312
138 21,74277312
139 21,75454642
140 21,78481196
141 21,80021715
142 21,80021715
143 21,80021715
144 21,82023616
145 21,82023616
146 21,84075406
147 21,85645695
148 21,8723175
149 21,88529702
150 21,88529702
151 21,93374357
152 21,94666325
153 21,94666325
154 21,94666325
155 21,96344402
156 21,96344402
157 21,96344402
158 21,96344402
159 21,96344402
160 21,96344402
161 21,96344402
162 21,96344402
163 21,96344402
164 21,96344402
165 21,98154907
166 21,9994693
167 21,9994693
168 21,9994693
169 21,9994693

Where its graph is like that

A: My equation search found that an inverse Harris yield density model:
y = x / (a + b*pow(x, c))
with fitted parameters of
a =  1.9953497744180733E+00
b =  4.6314864228655921E-03
c =  1.3877857961620943E+00
yields R-squared = 0.9997 and RMSE = 0.0988

A: I've worked with similar curves some time ago. Fitting $y=a(1-e^{-bx})$ and $y=a\ln x +b$ separately and averaging them yielded very good fits in my case. Since the curves cannot be cast to linear model, you need to use some sort of nonlinear curve fitting tool. curve_fit in scipy.optimize can be useful if you're using Python. Instead of trying to fit a complex model, averaging two/or more basic models provides good convergence rates. Since these curve-fitting libraries apply some sort of gradient-descent approach, local minima might occasionally bother you. In such cases, resorting to the differenced version of the above curve (i.e. $x_n-x_{n-1}$), fitting exponential decay, or inverse-polynomial decay (or again averaging them) and applying cumsum in the end might also be a good approach (only if you can't fit with nonlinear fitting tool).
EDIT:
Applying the methodology to this data: (first save the data to a text file having a whitespace between the columns as separator):
from scipy.optimize import curve_fit
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt

tmp = pd.read_csv("<PATH>", sep = " ", header = None)
tmp.columns = ["ind", "data"]

def f1(x,a,b): return a*(1-np.exp(-b*x))
def f2(x,a,b): return a*np.log(x) + b

x, y = tmp.ind.values, tmp.data.values

popt1,_ = curve_fit(f1, x, y, p0 = np.random.random(2))
popt2,_ = curve_fit(f2, x, y, p0 = np.random.random(2))

f1v = f1(x,*popt1)
f2v = f2(x,*popt2)

fig, ax = plt.subplots(2,2,figsize=(18,9))
ax[0][0].plot(x,y); ax[0][0].legend(["real"]); ax[0][0].grid()
ax[0][1].plot(x,f1v,x,y); ax[0][1].legend(["exp","real"]); ax[0][1].grid()
ax[1][0].plot(x,f2v,x,y); ax[1][0].legend(["log","real"]); ax[1][0].grid()
ax[1][1].plot(x,(f1v+f2v)/2,x,y); ax[1][1].legend(["avg","real"]); ax[1][1].grid()
plt.show()

Here, $y=a(1-e^{-bx})$ fit best to the data. In my cases, the right end of the curve was having a small trend (instead of complete saturation as in here) and fitting a logarithmic curve and averaging was a useful step.  Logarithmic curve doesn't fit well to the initial sections of the data, however this model has been a good predictor for me for estimating the LTV of customers.
By the way, the best parameters for the exponential curve is ($a$ and $b$ in order):
array([22.58256696,  0.0256301 ])


text:
Q: My app is terminating with this error. Any ideas? 2012-05-08 21:33:34.279 Passwordapp[384:fb03] Setting up a Fetched Results Controller for the Entity named Role
2012-05-08 21:33:34.292 Passwordapp[384:fb03] There's stuff in the database so skipping the import of default data
2012-05-08 21:33:34.293 Passwordapp[384:fb03] -[LoginViewController viewControllers]: unrecognized selector sent to instance 0x8e7d750
2012-05-08 21:33:34.301 Passwordapp[384:fb03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[LoginViewController viewControllers]: unrecognized selector sent to instance 0x8e7d750'
*** First throw call stack:
(0x1359022 0x1742cd6 0x135acbd 0x12bfed0 0x12bfcb2 0x2db6 0x390386 0x391274 0x3a0183 0x3a0c38 0x394634 0x1f93ef5 0x132d195 0x1291ff2 0x12908da 0x128fd84 0x128fc9b 0x390c65 0x392626 0x25cd 0x2535)
terminate called throwing an exception(lldb)

#import <UIKit/UIKit.h>
#import "passconst.h"

@interface LoginViewController : UIViewController <UITextFieldDelegate>

@property (nonatomic) BOOL pinValidated;

@end

#import "LoginViewController.h"
#import "KeychainWrapper.h"

@implementation LoginViewController
@synthesize pinValidated;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.
}

// Helper method to congregate the Name and PIN fields for validation.
- (BOOL)credentialsValidated
{
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    BOOL pin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];
    if (name && pin) {
        return YES;
    } else {
        return NO;
    }
}

- (void)presentAlertViewForPassword
{

    // 1
    BOOL hasPin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];

    // 2
    if (hasPin) {
        // 3
        NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
        NSString *message = [NSString stringWithFormat:@"What is %@'s password?", user];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Password"
                                                        message:message
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"Done", nil];
        // 4
        [alert setAlertViewStyle:UIAlertViewStyleSecureTextInput]; // Gives us the password field
        alert.tag = kAlertTypePIN;
        // 5
        UITextField *pinField = [alert textFieldAtIndex:0];
        pinField.delegate = self;
        pinField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        pinField.tag = kTextFieldPIN;
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Setup Credentials"
                                                        message:@"Secure your Password list!"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"Done", nil];
        // 6
        [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
        alert.tag = kAlertTypeSetup;
        UITextField *nameField = [alert textFieldAtIndex:0];
        nameField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        nameField.placeholder = @"Name"; // Replace the standard placeholder text with something more applicable
        nameField.delegate = self;
        nameField.tag = kTextFieldName;
        UITextField *passwordField = [alert textFieldAtIndex:1]; // Capture the Password text field since there are 2 fields
        passwordField.delegate = self;
        passwordField.tag = kTextFieldPassword;
        [alert show];
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == kAlertTypePIN) {
        if (buttonIndex == 1 && self.pinValidated) { // User selected "Done"
            [self performSegueWithIdentifier:@"Loginsegue" sender:self];
            self.pinValidated = NO;
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    } else if (alertView.tag == kAlertTypeSetup) {
        if (buttonIndex == 1 && [self credentialsValidated]) { // User selected "Done"
            [self performSegueWithIdentifier:@"Loginsegue" sender:self];
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    }
}

#pragma mark - Text Field + Alert View Methods
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    // 1
    switch (textField.tag) {
        case kTextFieldPIN: // We go here if this is the 2nd+ time used (we've already set a PIN at Setup).
            NSLog(@"User entered PIN to validate");
            if ([textField.text length] > 0) {
                // 2
                NSUInteger fieldHash = [textField.text hash]; // Get the hash of the entered PIN, minimize contact with the real password
                // 3
                if ([KeychainWrapper compareKeychainValueForMatchingPIN:fieldHash]) { // Compare them
                    NSLog(@"** User Authenticated!!");
                    self.pinValidated = YES;
                } else {
                    NSLog(@"** Wrong Password :(");
                    self.pinValidated = NO;
                }
            }
            break;
        case kTextFieldName: // 1st part of the Setup flow.
            NSLog(@"User entered name");
            if ([textField.text length] > 0) {
                [[NSUserDefaults standardUserDefaults] setValue:textField.text forKey:USERNAME];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            break;
        case kTextFieldPassword: // 2nd half of the Setup flow.
            NSLog(@"User entered PIN");
            if ([textField.text length] > 0) {
                NSUInteger fieldHash = [textField.text hash];
                // 4
                NSString *fieldString = [KeychainWrapper securedSHA256DigestHashForPIN:fieldHash];
                NSLog(@"** Password Hash - %@", fieldString);
                // Save PIN hash to the keychain (NEVER store the direct PIN)
                if ([KeychainWrapper createKeychainValue:fieldString forIdentifier:PIN_SAVED]) {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:PIN_SAVED];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSLog(@"** Key saved successfully to Keychain!!");
                }
            }
            break;
        default:
            break;
    }
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pinValidated = NO;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self presentAlertViewForPassword];
    [super viewDidAppear:animated];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
    UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
    [vc setModalPresentationStyle:UIModalPresentationFullScreen];

    [self presentModalViewController:vc animated:YES];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end

A: in your project you are trying to call [loginViewControllerObject viewController]; which is a navigation controller method


text:
Q: How to remove the child added to the stackLayout I am using the scrollView and a stackLayout in it. Adding the View dynamically to the stackLayout. I am getting the following exception when I am trying to remove the View added:

The calling thread cannot access this object because a different
  thread owns it.

My code is as following
<ScrollView Orientation="Vertical" VerticalOptions="FillAndExpand"
            x:Name="MessagesScrollView">
    <StackLayout Padding="7" x:Name="MessagesStackLayout"
                 HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
    </StackLayout>
</ScrollView>

Add the code behind is:
MessagesStackLayout.Children.Clear();
foreach (var chat in messagesList)
{
    MessagesStackLayout.Children.Add(new CustomViewCell(chat));
}

A: I have a feeling it is not running the code on MainThread try the following and see if that works for you:
  Device.BeginInvokeOnMainThread(() =>
  {
     MessagesStackLayout.Children.Add(new CustomViewCell(chat));
  });


text:
Q: How to config webpack to load custom fonts into storybook? I'm new to webpack and I'm trying to load custom fonts into stroybook v4 following this tutorial https://medium.com/@mushti_dev/hey-e6faa20b910a
The workspace structure looks like this (create-react-app + storybook)
my-project/
  .storybook
     config.js
     preview-hrad.html
     webpack.config.js
  fonts
    MyCustomFont.woff
  src
    components
       Title.js
    containers
    styles
       MyCustomFont.woff
    index.js
  stories

When loading the font from the styles folder in src, the config is as follows:
webpack.config.js
const path = require('path');

module.exports = async ({ config }) => {
  // fonts
  config.module.rules.push({
    test: /\.(png|woff|woff2|eot|ttf|svg)$/,
    use: [
      {
        loader: 'file-loader',
        query: {
          name: '[name].[ext]',
        }
      }
    ],
    include: path.resolve(__dirname, '../')
  });

  return config;
};

preview-head.html

Title.js
import React from 'react';

const Title = ({ title }) => {
  return (

{title}

  );
};

export default Title;

My question is how to load MyCustomFont.woff from the fonts folder ?
I tried to update the webpack config with  name: 'fonts/[name].[ext]', and the css style with src: url('fonts/MyCustomFont.woff') format('woff'); but I'm having hard time matching the correct font path.

A: I just ran into this issue on storybook v6.1, then realised there are actually two font areas to setup:

*

*iframe preview fonts (components preview fonts in preview-head.html)

*storybook dashboard fonts (dashboard navigation fonts in manager-head.html)

What I did:

*

*make a copy of preview-head.html and rename to manager-head.html

*ensure the font url specified in @font-face is relative to static folder path specified in npm scripts with -s

*I did not change webpack config in main.js

my folder structure

|- .storybook/
   |- ...
   |- preview-head.html
   |- manager-head.html
|- src/
   |- ...
   |- fonts/
      |- font-name.otf

preview-head.html and manager-head.html

package.json

{
  ...
  "scripts": {
    ...
    "storybook": "start-storybook ... -s ./src",
    "build-storybook": "build-storybook -s ./src"
  }
}


text:
Q: Check if user closed the page in PHP? I made a chat using PHP and JavaScript chat and there is a disconnect button which removes user from the chat removing him from user list first. But if the user closes browser then he will remain in the user list. How do I check if he left?
This must be done without putting any handles on page closing in JS because if user kills the browser then he will remain in chat.
By the way , JS script always sends a request to the PHP page which constantly checks for new messages in a loop and when there are some, the script prints them out and exits. Then it repeats all over again.
EDIT : How do I make a heartbeat thing in PHP? If a user closes the page the script execution will be terminated therefore we won't be able to check if the user is still connected in the same script.

A: Sorry, there is no reliable way of doing this, that's the way HTTP was built - it's a "pull"  protocol.
The only solution I can think of is that "valid"  and logged in clients must query the server in a very small interval. If they don't, they're logged out.

A: you could send a tiny ajax call to your server every 5 seconds. and users that doesn't do this aren't in the room any more

A: You answered your own question: if you don't detect a request for new messages from a user over a given length of time (more than a few seconds), then they left the room.
The nature of HTTP dictates that you need to do some AJAX type of communication. If you don't want to listen for the "give me more messages" request (not sure why you wouldn't want to), then build in a heartbeat type communication.

A: If you can't modify the JS code for some reason, there really is little you can do. Only thing you can do with PHP is to check if there's been for example over 15 minutes from the last activity, the user has left. But this is in no way a smart thing to do – a user might just sit and watch the conversation for 15 minutes.
Only proper way to do is using AJAX polling in set intervals if you want to do it reliably.
You noted that a user polls the server for new messages constantly, can't you use that to detect if user has left?

A: Maintain a list of active users on the server, as well as the last time they connected to the chat to request new messages.
When a user connects to check for messages update their time.
Whenever your code runs iterate through this list and remove users who haven't connected in too long.
The only failure is that if the number of users in the channel drops to zero, the server wont notice until someone comes back.

A: To address your edit, you can ignore client termination by using ignore_user_abort.

A: Using javascript u can do the following :
<script type="text/javascript">

window.onunload = unloadPage;

function unloadPage()
{
 alert("unload event detected!");
}
</script>

Make the necessary ajax call on the unloadPage() function to ur PHP Script

A: Request a PHP script that goes a little something like this, with AJAX:
register_shutdown_function("disconnect_current_user");
header('Content-type: multipart/x-mixed-replace; boundary="pulse"');

while(true) {
   echo "--pulse\r\n.\r\n";
   sleep(2);
}

This way, you won't constantly be opening/closing connections.

A: The answers to all the questions asked by the OP are covered in the section in the manual about connection handling:
http://uk3.php.net/manual/en/features.connection-handling.php
No Ajax.
No Javascript.
No keep alives.
C.


text:
Q: Append string to UserAgent on Chrome? I want to append a string to the UserAgent of a PC running Chrome, and not change the UserAgent altogether because I still want the browser to be recognized as the correct Chrome version. I could just use a UserAgent switcher and enter in the current UserAgent but then it wouldn't be correct after a few updates. The website contains some WebRTC elements so it's imperative that the correct version of Chrome is detected.
The reason is this, we have developed a website for an apartment complex of elderly people. They can use it at home, but the owner of the complex has also put two all-in-one PCs in the lobby for people without PCs to use.
Those PCs run Chrome in kiosk mode, and I need to be able to detect visits coming from those PCs. Outgoing links have to be opened in an iframe (since they can't open/close tabs) and I run some javascript that automatically logs people out after 5 min. But all that only has to run on those 2 specific PCs, I don't want people to get logged out at home.
I tried detecting it simply by checking the screen height like so:
if (screen.availHeight || screen.height-30) <= window.innerHeight) {
    // code
}

But that breaks when people use Ctrl-+ to zoom in. The window.innerHeight will change and the if statement won't work. Any other methods of detecting a fullscreen website didn't work, or only detect if the browser supports fullscreen.
Is there a plugin/method of appending a string to the UserAgent so I can check for it using Javascript? Or any other way of detecting Chrome in kiosk mode? I don't want to add a query to the url, that's technically impossible for our website.


text:
Q: Python and Google Calendar API : Timezone / Time Offset issues I'm having issues with timezones and time offsets when working with Python, the Google Calendar API, and a client device operating in local time.
I have a Raspberry Pi which acts as a booking display outside a shared room. A Python script is called periodically to pull in the next upcoming calendar event from the Google Calendar API, split the result into variables, then pass those variables back to the bash script which called it.
I built it in the winter—when the UK's timezone has equivalence to UTC—and it worked perfectly. Now, in British Summer Time, it doesn't. The comparison of time objects to check whether or not the meeting is currently in progress doesn't work, and the room is showing as available when it isn't.
I've read and read (then re-read and re-read) articles and explainers about working with timezones and time offsets in Python, and I just cannot get my head around it. It doesn't help that I don't really understand object-based programming, so the example scripts provided don't mean much to me!
Ideally, I would simply like everything to work using local time. The Raspberry Pi is connected to the internet and its time is updated automatically, and the Google Calendar is correctly set to the UK timezone. How could I go about making all references to time 'local', so the time objects everywhere in the Python script are always current UK time?
Please help. Stack Overflow has been such a rich source of knowledge in the past that I've never needed to ask a question myself, but this is making my brain hurt! Thank you!
This is what I've got, which is a modified version of Google's own example script:
    service = build('calendar', 'v3', credentials=creds)

    # Call the Calendar API
    timeStamp_now = datetime.datetime.utcnow()
    timeStamp_12 = timeStamp_now + timedelta(hours = 12)
    now = timeStamp_now.isoformat() + 'Z' # 'Z' indicates UTC time
    now12 = timeStamp_12.isoformat() + 'Z' # 'Z' indicates UTC time
    events_result = service.events().list(calendarId='###############@resource.calendar.google.com', timeZone="Europe/London", timeMin=now,
                                        maxResults=1, singleEvents=True, showDeleted=False, timeMax=now12,
                                        orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        print('meetingStart="NoEvents"')
    for event in events:
        startTime=event['start'].get('dateTime')
        endTime=event['end'].get('dateTime')
        eventTitle=event['summary']
        eventOrganizer=event['creator'].get('email')
        try:
                eventConferencing=event['conferenceData'].get('conferenceSolution').get('name')
        except:
                eventConferencing=(' ')
        if startTime <= now <= endTime:
                inProgress=('true')
        else:
                inProgress=('false')
        safeEventTitle= ""
        for i in eventTitle:
                num = ord(i)
                if (num >=0) :
                        if (num <=127) :
                                safeEventTitle= safeEventTitle + i

        print('meetingStart="' + startTime + '"')
        print('meetingEnd="' + endTime + '"')
        print('meetingTitle="' + safeEventTitle + '"')
        print('meetingOrganizer="' + eventOrganizer + '"')
        print('meetingConferencing="' + eventConferencing + '"')
        print('meetingInProgress="' + inProgress + '"')

The Raspberry Pi's time is set correctly:
pi@raspberrypi:~ $ date
Fri 16 Jul 20:31:38 BST 2021

The Python script returns this when run:
pi@raspberrypi:~ python /myPythonScript.sh
meetingStart="2021-07-16T20:00:00+01:00"
meetingEnd="2021-07-16T21:00:00+01:00"
meetingTitle="Test"
meetingOrganizer="abc@def.com"
meetingConferencing=" "
meetingInProgress="false"

A: See a sample code below that will adjust your datetime to UTC regardless of Daylight Saving Time.
Code:
import datetime
import pytz

timeZone = pytz.timezone("Europe/London")
dt = datetime.datetime.utcnow()

print("datetime now is:\t", dt)
local_dt = timeZone.localize(dt, is_dst=None)
utc_dt = local_dt.astimezone(pytz.utc)
print("Non-DST time is:\t", utc_dt) # prints utc regardless of DST

Output using bst datetime:

Output using utc datetime:

In your case:
timeZone = pytz.timezone("Europe/London")
dt = datetime.datetime.utcnow()
local_dt = timeZone.localize(dt, is_dst=None)
# timeStamp_now below should be in UTC already
timeStamp_now = local_dt.astimezone(pytz.utc)

Reference:

*

*How to convert local time string to UTC?

*Python daylight savings time


text:
Q: ColdFusion: "Error Executing Database Query. FUNCTION globalgoods.fullname does not exist " Helping a nonprofit site with their recently retired CF site.  Site has been moved to new host and will be accessed only for historical needs. The URL has changed from http://globalgoodspartners.org to http://globalgoodspartners-org.securec77.ezhostingserver.com/ and that could be at least part of the issue.
Getting "Error Executing Database Query. FUNCTION globalgoods.fullname does not exist " when accessing the admin.  The error is preventing the admin menu from displaying.
Original CF dev is not available, and I do not know CF. I suspect that globalgoods.fullname needs to be redefined to match the new URL, but that's just a guess.
Any help appreciated.


text:
Q: PHP mail message variables This is most likely a simple fix, I have my php form
<?php

$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];

$to = "email";
$subject = "Quiz Entries";
$message = $_POST['email'];
$message = $_POST['name'];
$from = "website";
$headers = "From:" . $from;

mail($to,$subject,$message,$headers);

echo "Mail Sent.";

?>

I want the email message to contain the users email and name, when i declare the variable a second time it just overwrites it so only sends name.

A: $message = $_POST['email'];
$message .= " ".$_POST['name'];

In that way ( .= ) you append second variable to first and, obviously, no overwrites will be done

A: You want to concatenate name to the message (notice the . operator).  In  your code you are just overwriting $message with $_POST['name'].
$message = $_POST['email'];
$message .= $_POST['name'];


text:
Q: Problem in plotting the difference between two columns in Dataframe over 4 quarters (Q1, Q2, Q3 and Q4) in a year I have a problem in plotting the Diversity graph which shows me the difference between two columns in a datafarme over 4 quarters of the year. This is the dataframe which I have:
df_Total2 =

       Quarters     X1     X2

1        Q1       390000  375000

2        Q1       675000  693000

3        Q1       350000  346000

4        Q1       950000  925000

5        Q2       395000  382000

6        Q2       800000  837000

7        Q2       350000  342000

8        Q2       850000  890000

9        Q3       400000  390000

10       Q3       750000  713000

11       Q3       350000  340000

12       Q3       875000  976000

13       Q4       410000  408000

14       Q4       750000  790000

15       Q4       350000  367000

16       Q4       900000  930000

This is my code:

library(plotly)
library(readxl)

df =read_excel("DeptYearlyPerfChange.xls")

df

df_Q1 <- cbind (df$Q1Budget,df$Q1Actual)

df_Q2 <- cbind (df$Q2Budget,df$Q2Actual)

df_Q3 <- cbind (df$Q3Budget,df$Q3Actual)

df_Q4 <- cbind (df$Q4Budget,df$Q4Actual)

df_Total <- rbind (df_Q1,df_Q2,df_Q3,df_Q4)

Quarters <- c ("Q1", "Q1","Q1", "Q1",  "Q2", "Q2","Q2", "Q2", "Q3", "Q3","Q3", "Q3"
               , "Q4", "Q4","Q4", "Q4")

df_Total2 <- cbind (Quarters, df_Total)

df_Total2 <- data.frame(Quarters, df_Total)

# Shaded region

ggplot(df_Total2, aes(x=Quarters, y= as.factor(df_Total2[,2]))) +

                  geom_ribbon(aes(ymin=as.factor(df_Total2[,2])-as.factor(df_Total2[,3]),

                  ymax=as.factor(df_Total2[,2])+as.factor(df_Total2[,3])),

                  alpha=0.2) + geom_line()

I would like to know what is the error of my code. Honestly, I did my best to solve this problem and I need really to your help.

A: If we need to plot the difference
library(dplyr)
library(ggplot2)
df_Total2 %>%
  mutate(Diff = X1 - X2, Sum = X1 + X2) %>%
  group_by(Quarters) %>%
  mutate(min = min(Diff), max = max(Sum)) %>%
  ggplot(aes(x = Quarters, y = X1)) +
    geom_ribbon(aes(ymin = first(min), ymax = first(max)), alpha = 0.2) +
    geom_line()

data
df_Total2 <- structure(list(Quarters = c("Q1", "Q1", "Q1", "Q1", "Q2", "Q2",
"Q2", "Q2", "Q3", "Q3", "Q3", "Q3", "Q4", "Q4", "Q4", "Q4"),
    X1 = c(390000L, 675000L, 350000L, 950000L, 395000L, 800000L,
    350000L, 850000L, 400000L, 750000L, 350000L, 875000L, 410000L,
    750000L, 350000L, 900000L), X2 = c(375000L, 693000L, 346000L,
    925000L, 382000L, 837000L, 342000L, 890000L, 390000L, 713000L,
    340000L, 976000L, 408000L, 790000L, 367000L, 930000L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16"))


text:
Q: Exception is not being thrown or test method is not recognizing the thrown exception? [Here's the uml diagram of the Taxi class. There is another class name "Rank" that is why I set the property "rank" to have variable of a class called "Rank".]

I have this test method:
[TestMethod]
public void _07_SetRankToNullThrowsException()
{
    Taxi t = new Taxi(1);
    Assert.ThrowsException<Exception>(() => t.rank = null);
}

I'm supposed to throw an exception if "rank" is null which is clearly seen in this code but the test explorer just won't recognise the thrown exception or the exception is just isn't being thrown:
public string rank {
    get { return rank; }

    set
    {

        if (rank == null)
        {
            throw new Exception("Rank cannot be null");
        }
        else
        {
            rank = null;
        }

    }
    }

In the UML diagram, I'm supposed to make the property "rank" to have a variable of a class called "Rank.cs" (the code below) I've tried running this code as well but it also doesn't throw the exception.:
public Rank rank {
    get { return rank; }

    set
    {

        if (rank == null)
        {
            throw new Exception("Rank cannot be null");
        }
        else
        {
            rank = null;
        }

    }
}

A: It appears to me that part of the problem may be in the naming - you have a property named rank in which you access the property itself to discover it's value.
In a property setter, the incoming value (the one being set) is accessed using the keyword value. You can use this to determine if the incoming value is null or not:
You also need to have a backing field to store the property value, which you haven't shown. Typically a backing field is private and is camelCase, while the associated property is PascalCase. This difference is helpful in this case because we can access rank from Rank.
Something like this should do the trick:
// Backing field to store the value for the 'Rank' property
private string rank = string.Empty;  // It could technically be set to 'null' here :)

public string Rank
{
    get { return rank; }

    set
    {
        if (value == null)
        {
            throw new Exception("Rank cannot be null");
        }
        else if (rank != value)
        {
            rank = value;
        }
    }
}

A: Because you are accessing your property in it's own getter, it is forever looping in itself. You can see this if you add code to write to console -
public Rank rank {
    get
    {
         Console.WriteLine("uh oh"); //Here
         return rank;
    }

    set
    {

        if (rank == null)
        {
            throw new Exception("Rank cannot be null");
        }
        else
        {
            rank = null;
        }

    }
}

You'll see a massive amount of these written out.  You need to use a different name, and different variable to be the backing field to this property.


text:
Q: How to disable FTPloy? I recently connected my Bitbucket account to FTPloy for easy deployment, and it worked great.  The trouble is now I need to move the repo to my team account, so I'd like to update the bitbucket account settings in FTPloy so it can connect to the new repo, but as far as I can tell there isn't anywhere on the entire site you can edit settings.  Once you've linked a repo to an FTP that's it - you don't seem to be able to edit it.
I read somewhere that for Github you have to revoke access by FTPloy from the Github side, but I can't find how to do this with Bitbucket, and even if I do manage to do it, since I can't amend the details of the old FTPloy account, do I just have to leave the FTPloy account unused and setup a new account with a new e-mail every time I want to change my FTP or Bitbucket details?  This seems ridiculous.
Hopefully I'm just being stupid and there's a nice big button somewhere under my nose that I've missed...  But if not I find it difficult to understand why anyone would offer a service that is clearly only half finished!

A: There was a nice big button under my nose - thought it was just a menu header, doh!

A: It looks like OP has already solved his problems. Unfortunately, that did not work for me.
I solved this by using Bitbucket Access Management settings.
Select Access Management > OAuth
In OAuth integrated applications page, you should be able to see a list of authorized apps. You can revoke access for each app there.


text:
Q: How to use managed identity with Bridge to Kubernetes? Has anyone managed to use managed identity with Bridge to Kubernetes?
I've been reading these articles:
https://learn.microsoft.com/en-us/visualstudio/bridge/managed-identity?view=vs-2019
https://learn.microsoft.com/en-us/visualstudio/bridge/overview-bridge-to-kubernetes
https://learn.microsoft.com/en-us/visualstudio/bridge/configure-bridge-to-kubernetes
but I cannot get this to work
enableFeatures:
    ManagedIdentity

I think there may be a documentation issue because it refers to both KubernetesLocalProcessConfig.yaml and KubernetesLocalConfig.yaml
I've tried both names. If I put the above yaml in KubernetesLocalProcessConfig.yaml I get a yaml serialization error. If I put it in KubernetesLocalConfig.yaml it doesn't seem to do anything so I suspect KubernetesLocalProcessConfig.yaml is the correct name, but I can't find any details of the correct yaml other than on the "Use managed identity with Bridge to Kubernetes" page linked above.

A: I worked it out by decompiling the extension. It is a documentation issue.
The correct file name is indeed KubernetesLocalProcessConfig.yaml
and the below yaml will work (note the - was missing in the docs)
version: 0.1
enableFeatures:
  - ManagedIdentity


text:
Q: Can not update Bugzilla Parameters I'm running Bugzilla 4.4.5 on Windows 2008 r2 with IIS 7.5. My path to Index.cgi is C:\Inetpub\wwwroot\bugzilla-4.4.5
The URL I'm using is http://localhost/bugzilla
I can bring the website up and login, but when I edit the parameters and click "Save" I get this message:
Software error:
Error in tempfile() using template data\params.XXXXX: Could not create temp file     data\params.I19Ig: Permission denied at Bugzilla/Config.pm line 270.

For help, please send mail to this site's webmaster, giving this error message and the time and date of the error.
[Wed Sep 17 13:14:16 2014] editparams.cgi: Error in tempfile() using template data\params.XXXXX: Could not create temp file data\params.I19Ig: Permission denied at Bugzilla/Config.pm line 270.

I ran process monitor (from sysinternals) on it and noticed this interesting line:
"Time of Day","Process Name","PID","Operation","Path","Result","Detail"

"12:11:37.2166449 PM","w3wp.exe","1172","CreateFile","C:\Inetpub\wwwroot\bugzilla-4.4.5\editparams.cgi\web.config","PATH NOT FOUND","Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a"

Any ideas about what I need to change?
ETA:
I verified that permissions for IUSR are Full Control for ALL folders, subfolders & files. No changes were made.
It doesn't work.

A: In IIS, navigate to the settings for the site (or Application if you have set it up as one) and in Features view, open the CGI feature.
Change Impersonate User to False, and restart IIS (or the site)
Regardless of your Application Pool settings, the CGI setting is forcing Perl to use a user account, which doesn't have permission. This fixed it for me.