text:
Q: ¿Como enviar un dato a javascript desde php? Resulta que estoy tratando de pasar un valor de PHP a Javascript para que me haga una validación si ya existe cierto dato.
El script de PHP hace su trabajo si el dato existe devuelve 1 y si no devuelve 0, el problema es que no se como tomar ese valor de nuevo en Javascript.
Les dejo el código para ver si alguien me puede ayudar.
HTML:
!DOCTYPE html>

    <meta charset = "UTF-8">
    <title>Formulario de registro</title>
    <link rel="stylesheet" href="../css/reg.css">

Formulario de registro

    <form  method= "post" class = "form-registro">

 Crear capitanes

            <input type = "number" id = "cedula" name = "cedula" placeholder = "Cedula" class = "input-100" required>
            <input type = "text" id = "nombre" name = "nombre" placeholder = "Nombres" class = "input-48" required>
            <input type = "text" id = "apellido" name = "apellido" placeholder = "Apellidos" class = "input-48" required>
            <input type = "text" id = "user" name = "user" placeholder = "Usuario" class = "input-48" required>
            <input type = "text" id = "pwd" name = "pwd" placeholder = "Contraseña" class = "input-48" required>
            <select name = "congregacion" id = "cmbCongregacion" class = "input-100" required>
            </select>
            <input type = "submit" value = " Registrar capitan" class = "btn-enviar" id = "btn-enviar">

    </form>

JAVASCRIPT:
window.onload = function(){
    var btnEnviar = document.getElementById("btn-enviar");
    btnEnviar.onclick = enviarForm;
    var cedula = document.getElementById("cedula");
    cedula.onblur = repetido;
    $.post("../php/llenar1.php",function(data){
        $("#cmbCongregacion").html(data);
    });

}

function repetido(){
    var cedula = document.getElementById("cedula");
    var valor;
    valor = cedula.value;
    $.post("../php/repetido.php", {cedula: valor}, function(data){
        $("#cedula").html(data);
        alert(html(data));
    });
}

RESPUESTA SCRIPT PHP:

A: Después de que la petición se ejecuta correctamente, los datos que devuelve el servidor llegan como parámetro a la función que se ejecuta al finalizar la petición (success), en tu caso has llamado al parámetro data
$.post("../php/repetido.php", {cedula: valor}, function(data){
    $("#cedula").val(data); // para elementos de formulario (inputs, select, etc) no se usa `.html()` si no `.val()`
    alert(data);
});

Por lo cual hacer un alert(data); debería de mostrarte dicha respuesta.
NOTA: es importante que desde PHP estés devolviendo el valor por medio de un echo

A: Para ver una variable de PHP en Javascript basta con imprimirla dentro del mismo javascript. Necesito que expliques mejor que es lo que exactamente quieres. Cual variable quieres ver en javascript? Por favor edita tu pregunta o comenta en mi respuesta. Aquí la solución

A: Tu problema se presenta porque estas usando la funcion html de jquery para llenar el input, debes cambiarlo por val:
Lo tienes asi:
$("#cedula").html(data);

Debe ser asi:
$("#cedula").val(data);


text:
Q: Dynamic Pivot without Null value This is a dynamic crosstab query in Northwind database:
DECLARE @COUNTRY NVARCHAR(MAX) ='', @COUNTRY2 NVARCHAR(MAX)

SELECT @COUNTRY = @COUNTRY + QUOTENAME(Country)+', '
FROM Customers
GROUP BY Country

SET @COUNTRY= LEFT(@COUNTRY, LEN(@COUNTRY)-1)

SET @COUNTRY2 = REPLACE(@COUNTRY, ',' , '+')

DECLARE @SQL NVARCHAR(MAX)

SET @SQL = 'SELECT * , '+@COUNTRY2+' AS TOTAL
           FROM (SELECT E.EmployeeID, E.LastName,
                        ISNULL( OD.Quantity, 0)* ISNULL(OD.[UnitPrice],0) QU,
                        O.ShipCountry AS CO
                 FROM Orders O JOIN Employees E ON O.EmployeeID = E.EmployeeID
                      JOIN [dbo].[Order Details] OD ON OD.OrderID = O.OrderID) AS T
PIVOT(SUM(QU) FOR CO IN ('+@COUNTRY+')) AS PVT
ORDER BY 1'
EXEC(@SQL)

I need to change the code in a way that have Null values replaced by 0.

A: DECLARE @COUNTRY NVARCHAR(MAX) = '' ,
  @COUNTRY2 NVARCHAR(MAX);

SELECT  @COUNTRY = @COUNTRY + COALESCE(QUOTENAME(Country) + ', ', '')
FROM    Customers
WHERE   EXISTS ( SELECT *
                 FROM   [Orders] AS [o]
                 WHERE  o.[CustomerID] = Customers.[CustomerID] )
GROUP BY Country;

SET @COUNTRY = LEFT(@COUNTRY, LEN(@COUNTRY) - 1);

SET @COUNTRY2 = REPLACE(@COUNTRY, ',', '+');

DECLARE @SQL NVARCHAR(MAX);

SET @SQL = 'SELECT * , ' + @COUNTRY2 +
  ' AS TOTAL
           FROM (
           SELECT  oe.EmployeeID, oe.LastName, oe.ShipCountry AS CO,
        COALESCE(OD.Quantity * OD.UnitPrice, 0) AS QU
FROM    (
          SELECT  EmployeeID, LastName, ShipCountry
          FROM    (
                    SELECT DISTINCT
                            ShipCountry
                    FROM    Orders
                  ) o ,
                  Employees
        ) oe
LEFT JOIN Orders O ON O.EmployeeID = oe.EmployeeID AND
                  [oe].[ShipCountry] = [O].[ShipCountry]
LEFT JOIN [Order Details] OD ON OD.OrderID = O.OrderID
           ) AS T
PIVOT(SUM(QU) FOR CO IN (' + @COUNTRY + ')) AS PVT
ORDER BY 1';

EXEC(@SQL);

A: You need to change the SELECT * to:
SELECT ISNULL(Argentina,0) AS 'Argentina' , INSNULL(Belgium,0) AS 'Belgium' , ....

Ofcourse, you would need to change your dynamic query to reflect the ISNULL functions.
Good Luck

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keyboard shortcut to close the execution tab in mysql workbench? After i execute a query in mysql workbench, a tab pops up showing the result. How do i close it with a keyboard shortcut? Thanks!
see screenshot here:
http://www.tiikoni.com/tis/view/?id=23d51ff

A: http://dev.mysql.com/doc/workbench/en/wb-keys.html
states that it should be Ctrl + W

A: There's no shortcut to close the resultset tab. You can only use ⌘ + W to close the owning tab (the editor tab). However you still can click the close button on the tab (right beside the title when you hover with the mouse over the tab) to close it.
Btw. on Windows it is not Ctrl + W but Ctrl + F4 (which is the system standard). The web page needs an update.

A: on OS X create your own shortcut:

*

*Apple menu -> System Preferences -> Keyboard -> Shortcuts -> App Shortcuts

*plus button on the left

*in 'Application' find mysqlworbench

*in 'Menu Title' type 'View->Panels->Hide Output Area'

*in 'Keyboard Shortcut'... You know what to do ^^

peace!


text:
Q: Patching and compiling Ext4 as a kernel module I'm currently patching Ext4 for academic purposes (only linux/fs/ext4/*, like file.c, ioctl.c, ext4.h) . I'm working on the QEMU virtual machine, and to speed up the whole process I've selected Ext4 to compile as a kernel module. The problem occurs when it comes to test new changes, as, even though I run make modules ARCH=x86 && make modules_install ARCH=x86 and reboot the machine (/ is Ext4), they are not visible unless I recompile the whole kernel. It's a little bit weird as I have a variety of signs that the Ext4 has been compiled as a module:

*

*It is configured as that:
$ grep EXT4 .config
CONFIG_EXT4_FS=m

*It does compile as a module:
$ make modules ARCH=x86
(...)
CC [M]  fs/ext4/ioctl.o
LD [M]  fs/ext4/ext4.o
Building modules, stage 2.
MODPOST 3 modules
LD [M]  fs/ext4/ext4.ko

*After $ make modules_install ARCH=x86 the files in /lib/modules/3.13.3/kernel/fs/ have proper time stamp.

*Finally:
$ lsmod
Module                  Size  Used by
ext4                  340817  1
(...)

For some reason I have to do $ make all ARCH=x86 in order to see my changes appear in the runtime. What have I missed? Thanks!

A: Most boot processes use an "initial ramdisk" (initrd) which contains all kernel modules which the kernel needs to load to be able to do anything - after all, to read files from an Ext4 file system, the kernel needs a driver for this file system and if the driver is on said file system, well, ...
So the solution is to pack all those files into an archive (the initial ramdisk) and save the hard disk blocks as a list of numbers in the boot loader. It can then use a primitive IDE/SATA driver to load the blocks directly, extract the drivers and load them.
Check the documentation of your linux distro to find out how to update initrd. On my Ubuntu Linux, it's mkinitramfs.
Related:

*

*Linux initial RAM disk (initrd) overview


text:
Q: Python Flask get json data to display I'm currently trying to display a list of values that get updated every 5 seconds to a sqlite database.
I can manage to convert the results to a JSON format by using the following code:
@app.route('/_status', methods= ['GET',  'POST'])
def get_temps():
    db = get_db()
    cur = db.execute('select sensor_name, temp from cur_temps ORDER BY sensor_name')
    #cur_temps = cur.fetchall()
    return jsonify(cur.fetchall())

Navigating to the webpage through a browser returns
{
  "BoilerRoom": 26.44,
  "Cylinder1": 56.81,
  "Cylinder2": 39.75,
  "Cylinder3": 33.94
}

I would like to have this data updated on a webpage periodically without loading the whole page again.  I'm getting stuck at the first hurdle and cant get the actual data to display.
The HTML code I'm using is
{% extends "layout.html" %}
{% block body %}

{% endblock %}

I've picked code from examples but I'm in need of a pointer.
SOLVED!!
New HTML Code

        Location
        Temperature

        Cylinder Top

        Cylinder Middle

        Cylinder Bottom

        Boiler Room

A: Your AJAX call should auto-detect a JSON response, but it won't hurt to explicitly tell jQuery about it:
$.ajax({
    type: "GET",
    url: $SCRIPT_ROOT + "_status",
    dataType: 'json',
    success: function(data) {
        $('#Result').text(data);
    }
);

The contentType parameter is only used for a POST request, telling the server what type of data you sent.
The data object contains whatever your Flask jsonify() response returned; in this case it'll be a JavaScript Object with the BoilerRoom, etc. keys.
Since you are loading JSON over a GET request, you may as well use the jQuery.getJSON() method here:
$.getJSON(
    $SCRIPT_ROOT + "_status",
    function(data) {
        $('#Result').text(data);
    }
);

This does exactly the same as the $.ajax() call but you get to omit the type and dataType parameters, and the url and success parameters are just positional elements.


text:
Q: A function not equal to its Taylor series. I have been given this problem as a practice for an upcoming exam and I am unsure how to approach it.
Give and example of a function that has derivatives of all orders, but is not equal to the sum of its Taylor series. Justify your example.

A: What you're looking for is a non-analytic smooth function. See: https://en.wikipedia.org/wiki/Non-analytic_smooth_function


text:
Q: 'DataFrame' object has no attribute 'label' I'm trying to plot k-means but I get this error:
'DataFrame' object has no attribute 'label'

I found this similar question, but it does not give me the answer I need.
print(df.head().to_dict())

{'CUST_ID': {0: 10001, 1: 10002, 2: 10003, 3: 10004, 4: 10005}, 'BALANCE': {0: 40.900749, 1: 3202.467416, 2: 2495.148862, 3: 1666.670542, 4: 817.714335}, 'BALANCE_FREQUENCY': {0: 0.818182, 1: 0.909091, 2: 1.0, 3: 0.636364, 4: 1.0}, 'PURCHASES': {0: 95.4, 1: 0.0, 2: 773.17, 3: 1499.0, 4: 16.0}, 'ONEOFF_PURCHASES': {0: 0.0, 1: 0.0, 2: 773.17, 3: 1499.0, 4: 16.0}, 'INSTALLMENTS_PURCHASES': {0: 95.4, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}, 'CASH_ADVANCE': {0: 0.0, 1: 6442.945483, 2: 0.0, 3: 205.788017, 4: 0.0}, 'PURCHASES_FREQUENCY': {0: 0.166667, 1: 0.0, 2: 1.0, 3: 0.083333, 4: 0.083333}, 'ONEOFF_PURCHASES_FREQUENCY': {0: 0.0, 1: 0.0, 2: 1.0, 3: 0.083333, 4: 0.083333}, 'PURCHASES_INSTALLMENTS_FREQUENCY': {0: 0.083333, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0}, 'CASH_ADVANCE_FREQUENCY': {0: 0.0, 1: 0.25, 2: 0.0, 3: 0.083333, 4: 0.0}, 'CASH_ADVANCE_TRX': {0: 0, 1: 4, 2: 0, 3: 1, 4: 0}, 'PURCHASES_TRX': {0: 2, 1: 0, 2: 12, 3: 1, 4: 1}, 'CREDIT_LIMIT': {0: 1000.0, 1: 7000.0, 2: 7500.0, 3: 7500.0, 4: 1200.0}, 'PAYMENTS': {0: 201.802084, 1: 4103.032597, 2: 622.066742, 3: 0.0, 4: 678.334763}, 'MINIMUM_PAYMENTS': {0: 139.509787, 1: 1072.340217, 2: 627.284787, 3: 864.2065423050816, 4: 244.791237}, 'PRC_FULL_PAYMENT': {0: 0.0, 1: 0.222222, 2: 0.0, 3: 0.0, 4: 0.0}, 'TENURE': {0: 12, 1: 12, 2: 12, 3: 12, 4: 12}}

plt.scatter(df["BALANCE"][df.label == 0], df["PURCHASE"][df.label == 0],s=80,c='magenta',label='Careful')
plt.scatter(df["BALANCE"][df.label == 1], df["PURCHASE"][df.label == 1],s=80,c='yellow',label='Standard')
plt.scatter(df["BALANCE"][df.label == 2], df["PURCHASE"][df.label == 2],s=80,c='green',label='Target')
plt.scatter(df["BALANCE"][df.label == 3], df["PURCHASE"][df.label == 3],s=80,c='cyan',label='Careless')
plt.scatter(df["BALANCE"][df.label == 4], df["PURCHASE"][df.label == 4],s=80,c='burlywood',label='Sensible')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=300, c='red',
label = 'Centroids')
plt.title('Customers Segmentation based on their Credit Card usage bhaviour')
plt.xlabel('BALANCE')
plt.ylabel('PURCHASE')
plt.legend()
plt.show()

<ipython-input-72-532d227bb220> in <module>
----> 1 plt.scatter(df["BALANCE"][df.label == 0],
      2             df["PURCHASE"][df.label == 0],s=80,c='magenta',label='Careful')
      3 plt.scatter(df["BALANCE"][df.label == 1],
      4             df["PURCHASE"][df.label == 1],s=80,c='yellow',label='Standard')
      5 plt.scatter(df["BALANCE"][df.label == 2],

C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py in __getattr__(self, name)
   5463             if self._info_axis._can_hold_identifiers_and_holds_name(name):
   5464                 return self[name]
-> 5465             return object.__getattribute__(self, name)
   5466
   5467     def __setattr__(self, name: str, value) -> None:

AttributeError: 'DataFrame' object has no attribute 'label'

A: The error 'DataFrame' object has no attribute 'label' is trying to tell you that your code is asking the DataFrame for a column called "label" but the issue is: you don't have a column in that DataFrame called 'label'.
So which column do you actually want to use?


text:
Q: Make text undetectable in Opencv I have an image and i want to add some text on it that cannot be detected by text detection programs.
How should i draw the text?I was thinking about changing the lightning or saturation to match the image.


text:
Q: Многослойный адаптивный background, как реализовать? Посетила идея делать многослойный адаптивный background.
Сейчас имею следующее:
CSS
html{
height: 100vh;
width: 100vw;
max-width: 100%;
background: center top url(/img/fon.jpg) no-repeat;
background-size: cover; }

и для адаптивности:
@media only screen and (width : 375px) and (orientation : portrait) {

html {
width: 100vw;
background: center top url(/img/fon_small.jpg) no-repeat;
background-size: cover; }

Но ЕСТЬ нюанс, фон многослойный. Голову сломал как сделать чтобы каждый слой двигался в свое место (выравнивался по левому, низ и т.п.), например:

а когда запускаю на мобильном, то получается примерно так:

Подскажите как подобное реализовать? При условии что фон рисуется в слоях в Photoshop. Спасибо за мысли!

A: Вижу цель - не вижу препятствий!

body {
  margin: 0;
  height: 100vh;
  background-color: rgba(255, 255, 255, 1);
  background-image: linear-gradient(#fa08, #fa08), linear-gradient(#f408, #f408),
    linear-gradient(#0808, #0808), url("https://i.stack.imgur.com/m9NKc.png"),
    radial-gradient(#fff8, #000f);
  background-position: 0% 0%, 100% 0%, 0% 100%, 0% 0%, 0% 0%;
  background-size: 47.5% 47.5%, 47.5% 47.5%, 100% 47.5%, auto, auto;
  background-repeat: no-repeat;
}
@media only screen and (max-width: 375px) and (orientation: portrait) {
  body {
    background-position: 0% 0%, 0% 50%, 0% 100%, 0% 0%, 0% 0%;
    background-size: 100% 30%, 100% 30%, 100% 30%, auto, auto;
  }
}


text:
Q: How to check if a class already exists in Ruby How do I check if a class already exists in Ruby?
My code is:
puts "enter the name of the Class to see if it exists"
nameofclass=gets.chomp
eval (" #{nameofclass}......  Not sure what to write here")

I was thinking of using:
eval "#{nameofclass}ancestors.     ....."

A: You can use Module.const_get to get the constant referred to by the string. It will return the constant (generally classes are referenced by constants). You can then check to see if the constant is a class.
I would do something along these lines:
def class_exists?(class_name)
  klass = Module.const_get(class_name)
  return klass.is_a?(Class)
rescue NameError
  return false
end

Also, if possible I would always avoid using eval when accepting user input; I doubt this is going to be used for any serious application, but worth being aware of the security risks.

A: Kernel.const_defined?("Fixnum") # => true

A: Here's a more succinct version:
def class_exists?(class_name)
  eval("defined?(#{class_name}) && #{class_name}.is_a?(Class)") == true
end

class_name = "Blorp"
class_exists?(class_name)
=> false

class_name = "String"
class_exists?(class_name)
=> true

A: Here's something I sometimes do to tackle this very issue. You can add the following methods to the String class like so:
class String
    def to_class
        my_const = Kernel.const_get(self)
        my_const.is_a?(Class) ? my_const : nil
    rescue NameError
        nil
    end

    def is_a_defined_class?
        true if self.to_class
    rescue NameError
        false
    end
end

Then:
'String'.to_class
=> String
'unicorn'.to_class
=> nil
'puppy'.is_a_defined_class?
=> false
'Fixnum'.is_a_defined_class?
=> true

A: perhaps you can do it with defined?
eg:
if defined?(MyClassName) == 'constant' && MyClassName.class == Class
   puts "its a class"
end

Note: the Class check is required, for example:
Hello = 1
puts defined?(Hello) == 'constant' # returns true

To answer the original question:
puts "enter the name of the Class to see if it exists"
nameofclass=gets.chomp
eval("defined?(#{nameofclass}) == 'constant' and #{nameofclass}.class == Class")

A: In just one line, I would write:
!!Module.const_get(nameofclass) rescue false

that will return trueonly if the given nameofclass belongs to a defined class.

A: You can avoid having to rescue the NameError from Module.const_get if you are looking the constant within a certain scope by calling Module#const_defined?("SomeClass").
A common scope to call this would be Object, eg: Object.const_defined?("User").
See: "Module".

A: Class names are constants. You can use the defined? method to see if a constant has been defined.
defined?(String)    # => "constant"
defined?(Undefined) # => nil

You can read more about how defined? works if you're interested.

A: defined?(DatabaseCleaner) # => nil
require 'database_cleaner'
defined?(DatabaseCleaner) # => constant

A: I used this to see if a class was loaded at runtime:
def class_exists?(class_name)
  ObjectSpace.each_object(Class) {|c| return true if c.to_s == class_name }
  false
end

A: None of the answers above worked for me, maybe because my code lives in the scope of a submodule.
I settled on creating a class_exists? method in my module, using code found in Fred Wilmore's reply to "How do I check if a class is defined?" and finally stopped cursing.
def class_exists?(name)
   name.constantize.is_a?(Class) rescue false # rubocop:disable Style/RescueModifier
end

Full code, for the curious:
module Some
  module Thing
    def self.build(object)
      name = "Some::Thing::#{object.class.name}"
      class_exists?(name) ? name.constantize.new(object) : Base.new(object)
    end

    def self.class_exists?(name)
      name.constantize.is_a?(Class) rescue false # rubocop:disable Style/RescueModifier
    end

    private_class_method :class_exists?
  end
end

I use it as a factory which builds objects depending on the class of the object passed as argument:
Some::Thing.build(something)
=> # A Some::Thing::Base object
Some::Thing.build(something_else)
=> # Another object, which inherits from Some::Thing::Base

A: If it is a simple standalone class e.g.
class Foo
end

then we can use Object.const_defined?("Foo"). And, if your class is inside any module e.g.
module Bar
  class Foo
  end
end

then we can use Module.const_get("Bar::Foo").
Please note that if Module.const_get('Bar::Foo') doesn't find the class then it will raise exception. While, Object.const_defined?('Foo') will return true or false.

A: I assume you'll take some action if the class is not loaded.
If you mean to require a file, why not just check the output of require?
require 'already/loaded'
=> false

A: If you want something packaged, the finishing_moves gem adds a class_exists? method.
class_exists? :Symbol
# => true
class_exists? :Rails
# => true in a Rails app
class_exists? :NonexistentClass
# => false


text:
Q: merging data in R but omit duplicated entries good day i hope I will be able to get help with this specific topic, I want to merge my one file to another file only if it has that specific outlet and within that specific month but the rows should not be duplicated.
so my file 1 has the Outlet, Month, Sales while file 2 I want to merge to has the Outlet, Month, Price and Salesvolume, however File 2 can have many instances of a single store for a single month hence the end result might have way too many duplicated entries for a single month.
so If i have Outlet 2453 for Feb 2016 in File 1 then only one entry should represent that particular month with the extra columns received from file2.
My current code:
    BPfac <- merge(File1, File2,by=c("Outlet","Month"))
    BPfac1 = BPfac[which(!duplicated(File1$Outlet) & !duplicated(File2$Month)),]

This doesn't generate the result that i want is there a better way of doing this, I only get two rows from a possible merge of 99K Outlets. The month is coded so Month 256 might represent Feb 2017 that's how it works. I just want the end result to take the first record only when matching between the two files.
Thanks in advance!
File 1
    Month   Sales   Outlet
    256     24      2453
    256     500     2453
    243     48      2341
    242     47      2356
    243     89      2356

File 2
     Month  Price   Salesvolume Outlet
     256        1840    222700  2453
     256        1840    237600  2453
     243        1840    277100  2341
     242        1840    279200  2356
     243        1840    451400  2356

Expected Outcome
     Month  Price   Sales   Salesvolume Outlet
     256    1840    24      222700      2453
     243    1840    48      277100      2341
     242    1840    47      279200      2356

See above the outcome only took the first outlet and month that matched between the two files and discarded the second outlet with the same Outlet and period, hope it makes sense now.

A: You can try this, using the data.table library:
library(data.table);

file_1 = read.table(
  header = TRUE,
  text = "
  Month   Sales   Outlet
  256     24      2453
  256     500     2453
  243     48      2341
  242     47      2356
  243     89      2356"
);

file_2 = read.table(
  header = TRUE,
  text = "
  Month  Price   Salesvolume Outlet
     256        1840    222700  2453
     256        1840    237600  2453
     243        1840    277100  2341
     242        1840    279200  2356
     243        1840    451400  2356
  "
);

# make files into data tables
file_1 = setDT(x = file_1);
file_2 = setDT(x = file_2);

# merge file_1 to file_2 by "Outlet"
outcome = file_1[file_2, on = "Outlet"];
outcome;

   Month Sales Outlet i.Month Price
1:   256    24   2453     256  1840
2:   256   500   2453     256  1840
3:   256    24   2453     256  1840
4:   256   500   2453     256  1840
5:   243    48   2341     243  1840
6:   242    47   2356     242  1840
7:   243    89   2356     242  1840
8:   242    47   2356     243  1840
9:   243    89   2356     243  1840
   Salesvolume
1:      222700
2:      222700
3:      237600
4:      237600
5:      277100
6:      279200
7:      279200
8:      451400
9:      451400

# then, group this table by "Outlet", and then select only the first element in
# each group. This is the given by .SD[1] and by = "Outlet", or for each data
# table created in each group, select only the first element. .SD refers to the
# Subsets of Data for each group, excluding "Outlet" (the key), and the [1] is
# an indexing operation to get the first element.
outcome = outcome[, .SD[1], by = "Outlet"]
outcome;

   Outlet Month Sales i.Month Price
1:   2453   256    24     256  1840
2:   2341   243    48     243  1840
3:   2356   242    47     242  1840
   Salesvolume
1:      222700
2:      277100
3:      279200

I hope this can help!


text:
Q: Can gravity be reversed? I'm wondering if any set of hypothetical conditions could result in us gravitating in a different direction. Specifically a reversal of gravity on the surface of Earth (or at least part of it), so that for people there, the ground would be above their heads, and everything unattached to it would fall into the sky.
At first I thought along the lines of a black hole passing by our solar system, but realized that could probably not suck things off the Earth's surface. Could anything other than a biblical rapture do this without breaking obvious physical laws? I know it's far fetched but thought I'd try anyway.

A: You suggest a black hole passing the solar system as a possibility, and indeed this could do it.
Suppose the Earth was falling into a black hole. To a first approximation the Earth and the people on it will be accelerating at the same rate, so people would not be sucked off the surface. After all, the Earth and the people on it are accelerating towards the Sun but we are not pulled off the surface every midday.
But the acceleration of the Earth and the people on it is only the same when tidal forces can be neglected. At midday on the equator your centre of mass is nearer the Sun than the Earth's centre of mass, so the Sun is pulling on you slightly more strongly than it pulls on the Earth. However the difference is tiny compared to Earth's gravity.
But suppose a small black hole, say one the mass of the Earth, were to pass just over your head. In this case the tidal forces would be strong enough to pull you off the surface of the Earth (and to a messy death!).

A: I would say a black hole passing or being sunked in is not reversing gravity. both objects are producing positive gravity. Reversing would be more like totally reversing gravity and all its effects all matter would repel itself. i doubt this would have any effect on the strong force that binds matter together but stars would explode black holes would become white holes and everything on the surface of the earth would fly off into space including the atmosphere next the matter in the crust and the molten mantle would break up and fly into space last the core would repel itself till there is and expanding cloud of matter when considering everything else in the universe has also had the same fate it would not be nice.
But would look epic.


text:
Q: TypeError: list indices must be integers or slices, not str when I try to iterate lists of strings with special characters inside some of them colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']

symbolic_numbers = ['23', '22', '21', '20', '3', '2', '1']

body = ''
for n in coloquial_numbers:
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
    #body += """    input_text = re.sub(r'""" + coloquial_numbers[n] + """', '""" + symbolic_numbers[n] + """', input_text)\n"""

print(repr(body))

output:
    input_text = re.sub(r"veinti[\s|-|]*tres", "23", input_text)
    input_text = re.sub(r"veinti[\s|-|]*dos", "22", input_text)
    input_text = re.sub(r"veinti[\s|-|]*uno", "21", input_text)
    input_text = re.sub("tres", "3", input_text)
    input_text = re.sub("dos", "2", input_text)
    input_text = re.sub("uno", "1", input_text)

The error when I iterate this lists:
Traceback (most recent call last):
    body += """    input_text = re.sub(r"{}", "{}", input_text)\n""".format(coloquial_numbers[n], symbolic_numbers[n])
TypeError: list indices must be integers or slices, not str

How could I fix this error? And why does it happen when iterating these lists of strings and with other lists it doesn't happen?

A: Here you're iterating over a list of strings:
colloquial_numbers = ['veinti[\\s|-|]tres', 'veinti[\\s|-|]dos', 'veinti[\\s|-|]uno', 'veinte', 'tres', 'dos', 'uno']
...

for n in colloquial_numbers:
    ...

n is the iterating variable, which means it's assigned the VALUE of each successive element in the list, not its index. You're then running colloquial_numbers[n] which, in actual fact, is running
colloquial_numbers['veinti[\\s|-|]tres'], which is incorrect python syntax, since you can't index a list by using a string
What you can do instead is:
for n in range(len(colloquial_numbers))

A: The problem is your loop variable:
for n in coloquial_numbers:

This pulls out each element from colloquial_numbers and assigns it to n. e.g. n = 'veinte'
What you want is the following:
for n in range(coloquial_numbers):

So that n is the index of the list. e.g. n = 0, n = 1, etc.


text:
Q: How to rewrite $R^TAR = V$ to find $A$ How to write the following equation to find $V$, the eigenvalue matrix. Note that $R$ is the orthogonal eigenvector matrix, and $A$ is one of the symmetric matrices.

A: I assume that we have $R^TAR = V$, and $R$ is an orthogonal matrix. It follows that
$$
R^TAR = V \implies\\
R(R^TAR) = RV \implies\ \\
AR = RV \implies\\
(AR)R^T = (RV)R^T \implies\\
A = RVR^T.
$$


text:
Q: Problem in loading the visualforce page on digital experience builder Cannot load the visualforce page in experience cloud site.
[Image][1]
[1]: https://i.stack.imgur.com/NT7rO.png
want to load the visualforce page on cloud builder.


text:
Q: How to apply a watermark to an uploaded picture using PHP How can I apply a watermark to an uploaded picture using PHP?
Example LINK: http://www.kitebeaches.com/kitesurf/uploadPicture/NIRVANA_Club_Village.html

A: Previously on SO:

*

*How can I add an image onto an image
in PHP like a watermark?

*Can this watermark function be
improve (PHP)?

*How to watermark GIF image with
24-bit PNG with transparency in
PHP?

*How to edit and watermark animated
gifs, preferably through php?

A: Try this (adapted from sitepoint):
<?php

header('content-type: image/jpeg');
$yourimagefile = 'something.jpg' // the image you're wanting to watermark
$watermark = imagecreatefrompng('watermark.png');  // the watermark
$watermark_width = imagesx($watermark);
$watermark_height = imagesy($watermark);
$image = imagecreatetruecolor($watermark_width, $watermark_height);
$image = imagecreatefromjpeg($yourimagefile);
$size = getimagesize($yourimagefile);
$dest_x = $size[0] - $watermark_width - 5;
$dest_y = $size[1] - $watermark_height - 5;
imagecopymerge($image, $watermark, $dest_x, $dest_y, 0, 0, $watermark_width, $watermark_height, 100);
imagejpeg($image);
imagedestroy($image);
imagedestroy($watermark);


text:
Q: Simple curdate() subtraction operation returning inconsistent results Here's my query:
SELECT cases.case_id, cases.county_id, case_name, county.county_name, date_referral,
date_flag, auto_flag, sessions.date_entry, curdate() - date_flag AS days_overdue
FROM cases
INNER JOIN county ON cases.county_id = county.county_id
LEFT JOIN sessions ON cases.case_id = sessions.case_id
WHERE date_flag <= curdate( )
AND sessions.date_entry IS NULL
AND date_flag IS NOT NULL
AND auto_flag = "0"
AND status_id = "0"
ORDER BY cases.county_id, days_overdue DESC , case_id ASC
LIMIT 0 , 30

Here's an example result set:
13-1206-B   McC v Jac   2013-08-15  91
13-0951-B   Gen v Gen   2013-08-16  90
13-1160-B   Bla v Bur   2013-08-20  86
12-3048-B   Wor v Wor   2013-08-29  77
13-0903-B   Ben v Ben   2013-09-01  5
13-0500-B   Bru v Bru   2013-09-05  1
13-1238-B   Bal v Bal   2013-09-05  1
13-0135-B   TDA v Tan   2013-09-06  0

The columns are case_id (irrelevant), case_name (irrelevant), date_flag, and the result of the equation "curdate() - date_flag" as days_overdue.
As you can see, the results are pretty inconsistent. Today is 2013-09-06 and it has not been 91 days since 2013-08-15. It has not been 77 days since 2013-08-29. But it has been 5 days since 2013-09-01, and it has been 0 days since 2013-09-06. So the latter half of the results are correct but the former...I don't even know where it's getting those numbers from.
Any ideas what's going wrong with this query?
Thanks!

A: Your problem is that you're trying to operate with dates as with normal operands via subtraction - operator. MySQL will not handle that. You should use DATEDIFF() function:
DATEDIFF(CURDATE(), date_flag) AS days_overdue

to get desired result (in days by default)


text:
Q: How To Get a Specific Column in a CSV File I'm using Spring Integration and was wondering how I can pull in a CSV file via an inbound file adapter and get a specific column from the file. The CSV file structure is shown below.
Header1, Header2, Header3
Value,   Value,   Value
...       ...      ...
...       ...      ...

What I need is to pull in all the values from the second column (Header2) and read each value.
Code below.
@Bean
@SuppressWarnings("unchecked")
public IntegrationFlow fileIntegrationTesting() {

    Gson gson = new GsonBuilder().disableHtmlEscaping().create();

    return IntegrationFlows
            .from(Files.inboundAdapter(new File(inputFilePath))
                    .filter(getFileFilters())
                    .autoCreateDirectory(true) ,
                    c -> c.poller(Pollers.fixedRate(1000))
                    )
            .channel("fileInputChannel")
            .transform(Files.toStringTransformer())
            .split(s -> s.applySequence(true).delimiters(","))
            .aggregate(a -> a.releaseStrategy(g -> g.size() >= 10)
                            .expireGroupsUponCompletion(true)
                    )

            .handle((p, h) -> gson.toJson(new RequestPayload((Collection<String>) p)))
            .enrichHeaders(eh -> eh.async(false)
                    .header("accept", "application/json")
                    .header("contentType", "application/json")
                    )
            .handle(Http.outboundGateway("URL")
                        .httpMethod(HttpMethod.POST)
                        .expectedResponseType(String.class)
                        .extractPayload(true)
                    )
            .get();

}

private FileListFilter<File> getFileFilters(){
     ChainFileListFilter<File> cflf = new ChainFileListFilter<>();
     cflf.addFilter(new LastModifiedFileListFilter(30));
     cflf.addFilter(new AcceptOnceFileListFilter<>());
     cflf.addFilter(new SimplePatternFileListFilter(fileExtention));
     return cflf;
}

A: I think you should be using a FileSplitter, not a FileToStringTransformer which will load the whole file into a single String.
Then, if you are discarding all the other columns, it would be most efficient to use .handle(myColumnSelector).
With
@Component
public class MyColumnSelector {

    @ServiceActivator
    String getCol(String in) {
        return StringUtils.delimitedListToStringArray(in)[1];
    }

}

(Adding some protection for badly formed rows).


text:
Q: Linear Algebra regarding the vector and scalar products Let us fix vectors $r_0$ and $u$ in $\mathbb{R}^3$, where $u\ne0$.
Using the identity $u×(v×w) = (u·w)v−(u·v)w$,
for vectors in $\mathbb{R}^3$, show that if $r×u = r_0 ×u$, then there exists $t ∈ \mathbb{R}$ (which you should determine) such that
$r = r_0 +tu$.
Hint: take the vector product of both sides of the equation with $u$.
My progress so far..From the hint, I have taken the vector product of both sides with $u \times u$ = $0$ on the right hand side of the equation, leaving me with $0$ =  ($u·w)v× u−(u·v)w×u$. I am unsure of what the next step to take is. The next step may be made easier if I have the equation in the form $0 = u×((u.w)v-(u.v)w)$.

A: Hint 1: Follow the hint.
Hint 2 (Alternative mathod): $(r-r_0)\times u=0$.

See also a Gowers's post about "fake difficulty".


text:
Q: Python - XML - LXML- How to use same XML tree structure from a sample XML file to create another XML file I have a XML file with some Tree structure, elements, attributes, text.
I need  to use the this XML as template (tree structure and tags) and create another XML, which might not have same number of elements (i.e. In below template there are two 'column' element, but the one I want to create has three elements 'column').
Below is the XML I want to use as template
<custom-data>
    <schema>SCHEMA</schema>
    <columns>
      <column>
        <name>ORGANIZATION</name>
        <datatype>NUMBER</datatype>
        <length/>
        <precision>18</precision>
        <not-null>Yes</not-null>
      </column>
      <column>
        <name>LOCATION</name>
        <datatype>NUMBER</datatype>
        <length/>
        <precision>18</precision>
        <not-null>Yes</not-null>
      </column>
    </columns>
</custom-data>

Instead of defining a similar tree using lxml by defining Each element one by one as below.
For example if 'df' is my pandas dataframe with data. which has columns as (Target Column, Data Type , Length, Scale, Nullable._
Target Column   Data Type   Length  Scale   Nullable
COLUMN1          NUMBER       38    0   N
COLUMN2          NUMBER       38    0   N
COLUMN3          NUMBER       38    0   N

Below is the sample python code I am using
from lxml import etree as et
root = et.Element('custom-data')
schema= et.SubElement(root, 'schema')
schema.text='SCHEMA'
columns= et.SubElement(root, 'columns')

for row in df.iterrows():
    column = et.SubElement(columns, 'columns')
    name = et.SubElement(column , 'name')
    datatype = et.SubElement(column , 'datatype')
    length = et.SubElement(column , 'length')
    precision = et.SubElement(column , 'precision')
    notnull = et.SubElement(column , 'not-null')

    name.text = str(row[1]['Target Column'])
    datatype.text = str(row[1]['Data Type'])
    length.text = str(row[1]['Length'])
    precision.text = str(row[1]['Scale'])
    notnull.text = str(row[1]['Nullable'])

xml_test=et.tostring(root, pretty_print=True).decode('utf-8')
f=open("xml_test.xml", "w")
f.write(xml_test)

Expected output is
<custom-data>
    <schema>SCHEMA</schema>
    <columns>
      <column>
        <name>COLUMN1</name>
        <datatype>NUMBER</datatype>
        <length>38</length>
        <precision>0</precision>
        <not-null>N</not-null>
      </column>
      <column>
        <name>COLUMN2</name>
        <datatype>NUMBER</datatype>
        <length>38</length>
        <precision>0</precision>
        <not-null>N</not-null>
      </column>
      <column>
        <name>COLUMN3</name>
        <datatype>NUMBER</datatype>
        <length>38</length>
        <precision>0</precision>
        <not-null>N</not-null>
      </column>
    </columns>
</custom-data>

How can I leverage the structure given in the Sample XML, so that I dont need to define it again in my code. Any simpler method?

A: You should be able to parse the XML template and use a copy of the "column" element to make new copies populated with the data from your DataFrame.
The template should be cleaned and simplified to only contain static values and a single "column" element to use as a template.
Here's an example...
XML Template (template.xml)
<custom-data>
    <schema>SCHEMA</schema>
    <columns>
        <column>
            <name/>
            <datatype/>
            <length/>
            <precision/>
            <not-null/>
        </column>
    </columns>
</custom-data>

Python
import pandas as pd
from copy import deepcopy
from lxml import etree as et

# Mock up DataFrame for testing.
data = {"Target Column": ["COLUMN1", "COLUMN2", "COLUMN3"],
        "Data Type": ["NUMBER", "NUMBER", "NUMBER"],
        "Length": [38, 38, 38],
        "Scale": [0, 0, 0],
        "Nullable": ["N", "N", "N"]}
df = pd.DataFrame(data=data)

# Create ElementTree from template XML.
tree = et.parse("template.xml")

# Map column names to element names.
name_map = {"Target Column": "name",
            "Data Type": "datatype",
            "Length": "length",
            "Scale": "precision",
            "Nullable": "not-null"}

# Select "columns" element so we can append/remove children.
columns_elem = tree.xpath("/custom-data/columns")[0]
# Select "column" element to use as a template for new column elements.
column_template = columns_elem.xpath("column")[0]

for row in df.iterrows():
    # Create a new copy of the column template.
    new_column = deepcopy(column_template)

    # Populate elements in column template based on name map.
    for col_name, elem_name in name_map.items():
        new_column.xpath(elem_name)[0].text = str(row[1][col_name])

    # Append the new column element to "columns" element.
    columns_elem.append(new_column)

# Remove original empty column template.
columns_elem.remove(column_template)

# Write tree to file.
# Note: I could've just done tree.write("output.xml"), but I used
#       XMLParser(), tostring(), and fromstring() to get the indents
#       all the same.
parser = et.XMLParser(remove_blank_text=True)
et.ElementTree(et.fromstring(et.tostring(tree),
                             parser=parser)).write("output.xml",
                                                   pretty_print=True)

XML Output ("output.xml")
<custom-data>
  <schema>SCHEMA</schema>
  <columns>
    <column>
      <name>COLUMN1</name>
      <datatype>NUMBER</datatype>
      <length>38</length>
      <precision>0</precision>
      <not-null>N</not-null>
    </column>
    <column>
      <name>COLUMN2</name>
      <datatype>NUMBER</datatype>
      <length>38</length>
      <precision>0</precision>
      <not-null>N</not-null>
    </column>
    <column>
      <name>COLUMN3</name>
      <datatype>NUMBER</datatype>
      <length>38</length>
      <precision>0</precision>
      <not-null>N</not-null>
    </column>
  </columns>
</custom-data>


text:
Q: Problem updating object properties inside a promise-aware for loop in javascript I am having a problem accessing updated object properties inside a for loop in Javascript.
let distribution = await ctx.db.query.distribution(
      {
        where: {
          id,
        },
      },
      `
    {
      id
      clients {
        id
        wallet {
          amount
        }
      }
    }`,
  );

let count = 0;

for (const client of distribution.clients) {
   await ctx.db.mutation.updateWallet({
       where: {
         id: client.id,
       },
       data: {
         amount: client.wallet.amount + someAmount,
       },
    });
    distribution.clients[count].wallet.amount = client.wallet.amount + someAmount;
    count++;
  }

In the above code, I execute a graphQL query to fetch all information associated with a distribution. I then want to iterate through the associated clients array and update each client's wallet. The same client may appear multiple times in this array and each time
their wallet must be updated.
A problem occurs when a wallet has already been updated in a previous iteration. When I try to update the amount a second time, the client.wallet.amount reflects the initial value of the wallet rather than value after the first update.
Clearly the property clients[count].wallet.amount attribute of the distribution object isn't being updated after each iteration. I thought javascript objects were passed by reference, and therefore the object should be updated after each iteration.
Could someone explain to me why the distribution object property is not being updated and how I can update it correctly?
FYI: I cannot use other loops such as forEach as it is not promise-aware and does not suppose async/await

A:
A problem occurs when a wallet has already been updated in a previous iteration.

Each wallet object is only modified once when the loop runs. Two or more wallet objects in the array may represent the same row in the database, but they are still distinct objects -- changing one will not change the other.
const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
for (const wallet of wallets) {
  wallet.amount = wallet.amount + 5
}
console.log(wallets[0]) // { id: 1, amount: 5 }
console.log(wallets[1]) // { id: 2, amount: 5 }
console.log(wallets[2]) // { id: 1, amount: 5 }

Note that we don't need to use a count variable at all. Because the const wallet is a reference to the original object in the array, if we modify it, we modify the original object.
If you want need to track the amounts by ID, you'd need to implement that logic. For example:
const wallets = [
  { id: 1, amount: 0 },
  { id: 2, amount: 0 },
  { id: 1, amount: 0 },
]
const amountsById = {}
for (const wallet of wallets) {
  amountsById[wallet.id] = (amountsById[wallet.id] || wallet.amount) + 5
}
const updatedWallets = wallets.map(wallet => ({
  ...wallet,
  amount: amountsById[wallet.id],
}))
console.log(updatedWallets[0]) // { id: 1, amount: 10 }
console.log(updatedWallets[1]) // { id: 2, amount: 5 }
console.log(updatedWallets[2]) // { id: 1, amount: 10 }


text:
Q: how to convert mindmap csv to python dict and find key here is the mindmap

and corresponding csv file is
history,Africa,Egyptian,pyramid
,Asia,Ancient India,Caste System
,,,Buddhism
,Eourp,Greece,xxx
,,Rome,yyy
,,,zzzz
I want to convert csv file to json like struct
{
    'history': [
        {
            'Africa': [
                {
                    'Egyptian': [{'pyramid': []}]
                }
            ]
        },
        {
            'Asia': [
                {
                    'Ancient India': [
                        {'Caste System': []},
                        {'Buddhism': []}
                    ]
                }
            ]
        },
        ...
    ]
}

finally a function to find the key and print the path of that key
e.g. find('Buddhism') -> history.Asia.Ancient India.Buddhism
I've tried Tree but I have no idea how to achieve this.

A: Here's a working solution:
# Load your string into list of list
m = []
for each in s.split('\n'):
    l = each.split(',')
    m.append(l)

# Create dict object that you want.
master = {}
level_indexes = [-1]*10
for i in range(len(m)):
    level = len([e for e in m[i] if e == ''])
    level_indexes[level] = i
    level_indexes[level+1:] = [-1]*(10-level-1)
    if level == 0:
        head = master
        for each in m[i]:
            head[each] = {}
            head = head[each]
    else:
        head = master
        indexes = []
        for j, e in enumerate(level_indexes[:level]):
            if e is not -1:
                indexes.append(j)
        indexes.append(level)
        last = []
        for j in range(len(indexes)-1):
            last.extend(m[level_indexes[j]][indexes[j]:indexes[j+1]])
        for j in range(level):
            head = head[last[j]]
        for j in range(level, len(m[i])):
            head[m[i][j]] = {}
            head = head[m[i][j]]

This creates a nested dictionary - master:
{'history': {'Africa': {'Egyptian': {'pyramid': {}}},
             'Asia': {'Ancient India': {'Buddhism': {}, 'Caste System': {}}},
             'Eourp': {'Greece': {'xxx': {}},
                       'Rome': {'yyy': {}, 'zzzz': {}}}}}

If you tweak it a little bit, you can put everything in list, but that will make it much more complicated:
master = []
level_indexes = [-1]*10
for i in range(len(m)):
    level = len([e for e in m[i] if e == ''])
    level_indexes[level] = i
    level_indexes[level+1:] = [-1]*(10-level-1)
    if level == 0:
        head = master
        for each in m[i]:
            head.append({each: []})
            head = head[-1][each]
    else:
        head = master
        indexes = []
        for j, e in enumerate(level_indexes[:level]):
            if e is not -1:
                indexes.append(j)
        indexes.append(level)
        last = []
        for j in range(len(indexes)-1):
            last.extend(m[level_indexes[j]][indexes[j]:indexes[j+1]])
        for j in range(level):
            head = head[-1][last[j]]
        for j in range(level, len(m[i])):
            head.append({m[i][j]: []})
            head = head[-1][m[i][j]]

output:
[{'history': [{'Africa': [{'Egyptian': [{'pyramid': []}]}]},
              {'Asia': [{'Ancient India': [{'Caste System': []},
                                           {'Buddhism': []}]}]},
              {'Eourp': [{'Greece': [{'xxx': []}]},
                         {'Rome': [{'yyy': []}, {'zzzz': []}]}]}]}]


text:
Q: Smooth UISearchController navigation bar transition I have a navigation controller with a root view controller that sets its titeView to a UISearchBar. Upon submitting their query, I push on another view controller which also has a UISearchBar populated with their query. If possible, I would like to keep this search bar in place and just transition the view controller below it. Is this possible with a navigation controller? Or do I need to make a custom container view controller.

A: One thing you can do is create a new custom view & do transition animation to the custom view upon submitting the query. This way will keep UISearchBar stay in place.


text:
Q: Trying to save a Flash video in my cache - where do temporary Flash files get stored with Firefox? I am watching a video lecture which seems to be in Adobe Flash and I want to save it. I'm using Firefox to view this website.
My about:cache result is below, if that helps.
Memory cache device

Number of entries: 212
Maximum storage size: 13312 KiB
Storage in use: 8087 KiB
Inactive storage: 6819 KiB

List Cache Entries Disk cache device

Number of entries: 3224
Maximum storage size: 500000 KiB
Storage in use: 26066 KiB
Cache Directory: C:\Documents and Settings\nvarm\Local Settings\Application Data\Mozilla\Firefox\Profiles\d74svniy.default\Cache

List Cache Entries Offline cache device

Number of entries: 0
Maximum storage size: 512000 KiB
Storage in use: 0 KiB
Cache Directory: C:\Documents and Settings\nvarm\Local Settings\Application Data\Mozilla\Firefox\Profiles\d74svniy.default\OfflineCache

List Cache Entries

A: NirSoft has a video cache viewing program at video cache view. He also has other programs to see the web caches and other interesting information like BHO's and the like. All his utilities are free.

A: Flash (flv) videos are stored in "Disk cache device". The path for the cache files is:
C:\Documents and Settings\<User>\Local Settings\Application Data\Mozilla\Firefox\Profiles\<Profile>.default\Cache

Click on "List Cache Entries" on about:cache page. Then search for your file with CTRL +F (for example, you can type in cs75.tv or .flv). Click on the related key and a new page opens. Look at the "file on disk" info and it should tell you in which subfolder your flv file is located inside Cache folder.

A: If you're using Firefox, check out this method. No downloading or installing third-party plugins/apps involved. YMMV.

A: Just use flashgot addon and save yourself the trouble.

A: If you use Firefox, I consider it would be easier to use the Download Flash and Video plugin for your task.

A: Go to the site and expand e.g. the section "Lecture 0 HTML" and then "Video". Now you can click one of the two links - "download" or "torrent" - with your left mouse button, where it says "Flash". For a torrent download you will need a BitTorrent client software, such as µTorrent.

Unless you have changed this behavior, by default, Firefox should prompt you to either save or open the Flash file on your computer. See the screenshot below.

If you don't get this prompt, you can right click on the link and then click "Save Link As". See screenshot below.

A: On the left top corner there should be an orange fire fox tab. Click that and save the page. Go to the folder you saved it to and the flash should be somewhere in there.


text:
Q: Get data out of JSON array from external URL I am relatively new to JSON. I have read the tutorial and trying to implement it but no luck.
Basically I have an external URL that gives JSON data/feed. The data is in the form of array. Now I am trying to write a JavaScript Program (on my local) that would get the data out of this URL and would put in my html.
Here is the function. It includes the external link also.
But I am not getting any result. Just empty.
Am I missing something or what I am doing wrong?
 <!doctype html>

 <meta charset="utf-8">
 <title>Index Page</title>

UPDATE:
After being pointed in the right direction by you guys (thank you very much for that), I have found that the request is being blocked by server due to some CORS error. I am studying it.
Please review the following image of the error I got in the console.
From it, can you specifically point out the solution?

A: What you are trying to do, Is a cross domain request. A cross domain request is also called a JSONP request amongst many more others and has two restrictions:
The first is that it restricts you only to "GET" requests, meaning you cannot issue a "POST" request to the cross domain server.
The second is that you are very limited by the server, meaning that if the server won't allow, you cannot get any data.
I would suggest you to read more about cross domain request before trying to go through this.

A: You are probably trying to execute an XMLHttpRequest to a domain that is different than your page is on, the browser will block this request. To allow the request you have to use CORS.
You can open the developer tools in Chrome (F12) and check for any error messages related to
"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '[domainname]' is therefore not allowed access."

A: Append --disable-web-security (at path C;...\chrome.exe) in chrome's exe properties preceded by a space.
More Elegant Solution:
Other solution will be on server side. Which is to create crossdomain.xml and clientaccesspolicy.xml file on server. It's structure is like:
crossdomain.xml:
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>

clientaccesspolicy.xml:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
  <cross-domain-access>
    <policy>
      <allow-from http-request-headers="SOAPAction">
        <domain uri="*"/>
      </allow-from>
      <grant-to>
        <resource path="/" include-subpaths="true"/>
      </grant-to>
    </policy>
  </cross-domain-access>
</access-policy>

Some of the tutorials are:
http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000469.html
http://www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html
Its specification is:
http://www.adobe.com/devnet-docs/acrobatetk/tools/AppSec/CrossDomain_PolicyFile_Specification.pdf
Other tutorials:
https://msdn.microsoft.com/en-us/library/cc197955(v=vs.95).aspx

A: Thank to Muhammad Imran, Barr J and Luuk Moret, I am finally able to solve my problem.
It was the Cross domain request that's why it was not allowing me to get data.
So what I did,

*

*I checked using test-cors.org the server to which I was sending request to see if CORS is configured or not. And the server was configured.

*Then I installed this plugin for chrome, "Allow-Control-Allow-Origin: *" This plugin allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header and Whola!. That solved my problem.

I hope this would help someone else.


text:
Q: QUOTENAME equivalent function bigquery In Bigquery result I want to each and every field in double quote. I found QUOTENAME function is available in SQL not in big query Can anyone guide me how to achieve the same result in bigquery.
Thanks for your  help in advance
Regards
Amit

A: SELECT format('%T','abc')

returns
"abc"

%t and %T behavior
The %t and %T format specifiers are defined for all types. The width, precision, and flags act as they do for %s: the width is the minimum width and the STRING will be padded to that size, and precision is the maximum width of content to show and the STRING will be truncated to that size, prior to padding to width.

*

*%t is always meant to be a readable form of the value.

*%T is always a valid SQL literal of a similar type, such as a wider numeric type. The literal will not include casts or a type name, except for the special case of non-finite floating point values.
Read more here

A: You can use String formating Which is explained in details Google Cloud Docs
Useage :
format("-%s-", 'abcd efg')
Output : -abcd efg-


text:
Q: JWPlayer - Click to play interpreted as autoplay on iOS Safari/Chrome I'm working on a custom player built around a JWPlayer. When clicking the "Play" button, I first fetch the content asynchronously, and once the content is fetched, i call jwplayer.setup(config), followed by jwplayer.play().
Listening to the "playAttemptFailed" event, i get the following error: "303210 - The play attempt was interrupted for unknown reasons".
If i set 'mute' as 'true' in the jwplayer.setup(), then everything works, which makes me believe it is related to the autoplay policies.
Is there any way to remedy this? It should not be treated as autoplay, since the user interaction (play button click) did indeed happen, right?
This only happens on iOS.

A: I had the same issue on IOS device, so I fixed calling the jwplayer when the site is loaded and call play function on click event:
    var player = null;
    var playerButton = document.getElementById('buttonPlayer');

    function initializePlayer() {
       player = jwplayer.setup({ file: '<STREAMING_URL>'});
    }

    function playButtonFunction() {
       player.play(true);
    }

    playerButton.addEventListener('click', function() {
       playButtonFunction();
    });

    window.addEventListener('load' , function() {
       initializePlayer();
    });


text:
Q: Javascript Tab Menu with sIFR I am working on a two-level menu like the Dynamic Drive examples on this page. The goal is to show a subnav layer below the main nav onmouseover, reverting to each page's default subnav layer after a timed interval. It works, except for a big problem: I am using sIFR on the main navigation items (s inside of
s). The script logic doesn't work on the sIFRized items, because it targets  tags, which have been replaced.
I tried changing the script to target the parent
s, but it just screwed up the main nav. I am not very advanced with Javascript so any advice is appreciated!
One idea: is it possible to sIFR replace each navigation  instead of replacing each
? Or would the  still be unavailable to the menu script?
I'm not married to this javascript solution, in fact I tried a few other methods of my own using simple Javascript show/hide methods. However, this script has the "reverting to default" behavior I am looking for.
--> Javascript menu source from Dynamic Drive
• Main navigation source:

    // rel="subnav1" shows the "subnav1" layer in the snippet below

Around Othello

    // rel="subnav2" shows the "subnav2" layer in the snippet below

Living Here

    // rel="subnav3" shows the "subnav3" layer in the snippet below

Link to it

What's New

Contact

Retail Hub

• sIFR replacement for main nav items
sIFR.replace(grotesqueMT, {
selector: 'li.navLi',
tuneWidth:4,
forceSingleLine:true,
ratios:[8, 1.3, 11, 1.21, 12, 1.2, 14, 1.19, 21, 1.16, 28, 1.13, 38, 1.12, 61, 1.11, 94, 1.1, 95, 1.09, 103, 1.1, 107, 1.09, 110, 1.1, 119, 1.09, 120, 1.1, 1.09],
css: ['.sIFR-root { background-color:#5a7e92; color:#ffffff; font-size:18; }'
      ,'a { color:#ffffff; text-decoration:none; }'
      ,'a:link { color:#ffffff; text-decoration:none; }'
      ,'a:hover { color:#f0eed6; text-decoration:underline; }'
      ]
});

• Subnav source (a separate code snippet)

Around Othello

 |

Your Big Backyard

 |

Explore the Area

 |

Community Buzz

Around Othello

 |

Community Buzz

Living Here

 |

Living Green

A: Seriously, save yourself the trouble and don't use sIFR here.


text:
Q:  Show a wait dialog during file creation and hide it when download is ready I have a Page that automatically generates a file and sends it to the Response. I need a Dialog to be shown during the file creation and hidden after the browser download dialog appears.
Any suggestion?
Thanks! :)

A: You can show a nice overlay busy message.
The Mark-up part:
$(function() { // when document has loaded

    ($.unblockUI); //unlock UI

    //Show busy message on click event and disable UI
    $('#btnHelloWorld').click(function() {
    $.blockUI({ message: '
Please wait...
' });

    });

});

<asp:Button ID="btnHelloWorld" runat="server" Text="Hello World" />

The Code behind:
   Protected Sub btnHelloWorld_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnHelloWorld.Click
        Label1.Text = "Hello World"
        Threading.Thread.Sleep(5000)
    End Sub

Check out jQuery BlockUI Plugin

A: I have used the RadProgressArea control from the Telerik RadControls for ASP.NET AJAX suite to report back progress of long-running operations.  It works quite well for that scenario as it polls the process for status updates.

A: Adding to Colin's response:
You can find a demo of the RadProgressArea here:
http://demos.telerik.com/aspnet-ajax/upload/examples/customprogress/defaultcs.aspx
The ProgressArea works in conjunction with the RadProgressManager to poll the server process and update the client UI. There is a client-side API for the ProgressManager that allows you to start and hide the progress area via JavaScript:
http://www.telerik.com/help/aspnet-ajax/upload_clientsideradprogressmanager.html
There is also an online demo showing you how to place ProgressArea in a RadWindow (the "dialog" in your requirements):
http://www.telerik.com/support/kb/aspnet-ajax/window/using-radupload-progress-area-in-radwindow.aspx
The ProgressManager/Area ultimately use a HttpHandler to facilitate the progress updates, and the technique does require "sticky session" if you're in a webfarm. Hope that helps.


text:
Q: Bandle Template error - Symfony 3.4 Good morning, I just started with Symfony and I've been reading errors like mine from different people but I have not finished finding the solution.
I have this folder structure
Estructura
I have this error:

Unable to find template
  "MyBundle:Default:index.html.twig" (looked into:
  C:\xampp\htdocs\Ejercicios\Symfony\proyectoSymfony\app/Resources/views,
  C:\xampp\htdocs\Ejercicios\Symfony\proyectoSymfony\vendor\symfony\symfony\src\Symfony\Bridge\Twig/Resources/views/Form).

And this routing configuration:
proyectoSymfony_hola_mundo:
    path: /holamundo
    defaults: { _controller: MyBundle:Default:index}

The controller configuration is this code:
namespace ProyectoSymfony\HolaMundoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction()
    {
        return $this>render('MyBundle:Default:index.html.twig');
    }
 }

For this line of error looked into: C:\xampp\htdocs\Exercises\Symfony\proyectoSymfony\app/Resources/views
I assume that this is the main error but I do not understand why when calling Path holamundo it goes straight to that route.


text:
Q: Only append div with certain class in Ajax success function I have a partial view that is used to return a bunch of html to my main page. In my Ajax call, I need to grab that partial view, but I only want to append certain
 elements. Is this possible?
Here is the Ajax:
    $(document).ready(function () {
        $("#addItem").click(function () {
            $.ajax({
                url: '@Url.Action("BlankDropDownItem", "DropDownValues")',
                data: { field: $('#Field').val(), displayPage: $('#DisplayPage').val() },
                dataType: 'html',
                cache: false,
                success: function (html) {
                    $("#items").append(html);
                }
            });
            return false;
        });
    });

This calls an ASP MVC controller method which returns this partial view.

        <fieldset>
            <legend>Category Information</legend>

                @Html.LabelFor(model => model.Field)

                @Html.EditorFor(model => model.Field)
                @Html.ValidationMessageFor(model => model.Field)

                @Html.LabelFor(model => model.DisplayPage)

                @Html.EditorFor(model => model.DisplayPage)
                @Html.ValidationMessageFor(model => model.DisplayPage)

        </fieldset>

        <fieldset id="items">
            <legend>Drop Down Items</legend>

                @Html.LabelFor(model => model.AllowedValue)

                @Html.EditorFor(model => model.AllowedValue)
                @Html.ValidationMessageFor(model => model.AllowedValue)

                @Html.LabelFor(model => model.DisplayValue)

                @Html.EditorFor(model => model.DisplayValue)
                @Html.ValidationMessageFor(model => model.DisplayValue)

        </fieldset>

However, I only want to append the label-field and editor-label
 elements to items.

A: You can use jQuery to search the returned html too.  Not as efficient as it could be, but probably fine for your purposes.
$("#items").append($(html).find(".label-field, .editor-label"));


text:
Q: Random "502 Error Bad Gateway" in Amazon Red Hat (Not Ubuntu) - Nginx + PHP-FPM First of all, I already searched for 502 error in Stackoverflow. There are a lot a threads, but the difference this time is that the error appears without a pattern and it's not in Ubuntu.
Everything works perfectly, but about once a week my site shows: 502 Bad Gateway.
After this first error, every connection starts showing this message. Restarting MySQL + PHP-FPM + Nginx + Varnish doesn't work.
I have to clone this instance, and make another one, to get my site up again (It is hosted in Amazon EC2).
In Nginx log it shows these line again and again:
[error] 16773#0: *7034 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 127.0.0.1

There are nothing in MySQL or Varnish log. But in PHP-FPM it shows theses type of line:
WARNING: [pool www] child 18978, script '/var/www/mysite.com/index.php' (request: "GET /index.php") executing too slow (10.303579 sec), logging
WARNING: [pool www] child 18978, script '/var/www/mysite.com/index.php' (request: "GET /index.php") execution timed out (16.971086 sec), terminating

Inside PHP-FPM slowlog it was showing:
[pool www] pid 20401
script_filename = /var/www/mysite.com/index.php
w3_require_once() /var/www/mysite.com/wp-content/plugins/w3-total-cache/inc/define.php:1478

(Inside the file "define.php" at line number 1478, it has this line of code: require_once $path;)
I thought the problem was with W3 Total Cache plugin. So I removed W3 Total Cache.
About 5 days later it happened again with this error in PHP-FPM slow log:
script_filename = /var/www/mysite.com/index.php
wpcf7_load_modules() /var/www/mysite.com/wp-content/plugins/contact-form-7/includes/functions.php:283

(Inside the file "functions.php" at line number 283, it has this line of code: include_once $file;)
The other day, the first error occurred in another part:
script_filename = /var/www/mysite.com/wp-cron.php
curl_exec() /var/www/mysite.com/wp-includes/class-http.php:1510

And again a different part of code:
[pool www] pid 20509
script_filename = /var/www/mysite.com/index.php
mysql_query() /var/www/mysite.com/wp-includes/wp-db.php:1655

CPU, RAM ... everything is stable when this error occurs (less then 20% usage).
I tried everything, but nothing worked:

*

*Moved to a better server (CPU and RAM)

*Decreased timeout from Nginx, PHP-FPM, MySQL (my page loads quickly, so I decrease timeout to kill any outlier process)

*Changed the number of PHP-FPM spare servers

*Changed a lot of configuration from Nginx and PHP-FPM

*I know that there is a bug with PHP-FPM and Ubuntu that could cause this error. But I don't think there is a bug with Amazon instances (Red Hat). (And I don't want to migrate from PHP-FPM to Socks because I've read that Socks don't works well under heavy load)

This was happening about every week since 5 months ago. I'm desperate.
I got to the point that I even put Nginx and PHP-FPM in Linux's crontab, to restart theses services every day. But it didn't work too.
Anyone has any suggestion where I can solve this problem? Anything will help!!
Server:
 Amazon c3.large (2 core and 3.75GB RAM)
 Linux Amazon Red Hat 4.8.2 64bits

PHP-FPM:
 listen = 127.0.0.1:9000
 listen.allowed_clients = 127.0.0.1
 listen.mode = 0664
 pm = ondemand
 pm.max_children = 480
 pm.start_servers = 140
 pm.min_spare_servers =140
 pm.max_spare_servers = 250
 pm.max_requests = 50
 request_terminate_timeout = 15s
 request_slowlog_timeout = 10s
 php_admin_flag[log_errors] = on

Nginx:
  worker_processes  2;
     events {
          worker_connections  2048;
          multi_accept        on;
          use                 epoll;
     }
     http {
          include       /etc/nginx/mime.types;
          default_type  application/octet-stream;
          access_log  off;
          sendfile        on;
          tcp_nopush     on;
          tcp_nodelay    on;
          types_hash_max_size 2048;
          server_tokens off;
          client_max_body_size 8m;
          reset_timedout_connection on;
          index index.php index.html index.htm;
          keepalive_timeout  1;
          proxy_connect_timeout  30s;
          proxy_send_timeout  30s;
          proxy_read_timeout  30s;
          fastcgi_send_timeout 30s;
          fastcgi_read_timeout 30s;
          listen 127.0.0.1:8080;
          location ~ .php$ {
                    try_files $uri =404;
                    include fastcgi_params;
                    fastcgi_index index.php;
                    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                    fastcgi_keep_conn on;
                    fastcgi_pass 127.0.0.1:9000;
                    fastcgi_param HTTP_HOST $host;
          }
     }

A: I would start by tuning some configuration parameters.
PHP-FPM
I think that your pm values are somewhat off, a bit higher than I've normally seen configured on server around your specs... but you say that memory consumption it's normal so that's kind of weird.
Anyway... for pm.max_children = 480, considering that by default WordPress increases the memory limit to 40MB, you would end up using up to 18 gigs of memory, so you definitely would like to lower that.
Check the fourth part on this post for more info about that: http://www.if-not-true-then-false.com/2011/nginx-and-php-fpm-configuration-and-optimizing-tips-and-tricks/
If you're using... let's say 512MB for nginx, MySQL, Varnish and other services, you would have about 3328 MB for php-fpm... divided by 40 MBs per process, pm.max_children should be about 80... but even 80 it's very high.
It's probable that you can also lower the values of pm.start_servers, pm.min_spare_servers and pm.max_spare_servers. I prefer to keep them low and only increase them it's necessary
For pm.max_requests you should keep the default of 500 to avoid server respawns. I think it's only advisable to lower it if you suspect memory leaks.
Nginx
Change keepalive_timeout to 60 to make better use of keep alive.

Other than that, I think everything looks normal.
I had this issue with Ubuntu, but request_terminate_timeout on PHP-FPM and fastcgi_send_timeout + fastcgi_read_timeout were enough to get rid of it.
I hope you can fix it!


text:
Q: Как работает QScrollArea? Объясните, пожалуйста, как можно работать со QScrollArea. В дизайнере сделал, но не работает. В интернете нормальных решений не нашел

A: QScrollArea это виджет-контейнер для виджетов, чей размер обычно очень большой и чтобы окно с ними умещалось, добавляются скролл-бары (ползунки).
Для помещения виджетов в QScrollArea нужен не layout (компоновщик), а виджет, поэтому у нее есть метод setWidget.
Например этот код создаст большое количество кнопок:
from PyQt5.QtWidgets import QApplication, QGridLayout, QPushButton, QWidget, QScrollArea

app = QApplication([])

layout = QGridLayout()
for i in range(10):
    for j in range(5):
        button = QPushButton(f'{i}x{j}')
        layout.addWidget(button, i, j)

w = QWidget()
w.setLayout(layout)

mw = QScrollArea()
mw.setWidget(w)
mw.resize(200, 200)
mw.show()

app.exec()

Окно будет выглядеть так:

При увеличении размера окна ползунки исчезнут:

QScrollArea может менять размер виджетов в ней, растягивать их. За это отвечает свойство widgetResizable, которое по умолчанию False.
Если у QScrollArea это свойство активировать (mw.setWidgetResizable(True)), то виджеты в ней растянутся:


text:
Q: enabling and disabling two text box at the same time based on selection option choice I have four category namely men, women, youth and both(men and women) when i choose men category at the select option  the text box to enter number of women is disabled and when i choose women category the text box to enter number of men is disabled, what i ask for help is how to make the two text box be active at the same time when i choose youth or both category. Below is my code.

    Group Category

         <select class="form-control" name="category"  id="category" onChange="JoinedOrNot()">
      <option value="">Select Category</option>
      <option value="Men">Men</option>
      <option value="Women">Women</option>
      <option value="Youth">Youth</option>
      <option value="Both">Both</option>
      </select>

    Number Of Men

    <input type='text' size='5' name="man" id="input1" value="" class='input' disabled></input>

    Number Of Women

    <input type='text' size='5' name="woman" id="input2" value="" class='input' disabled></input>

function JoinedOrNot(){
    var cat = document.getElementById("category");
    if(cat.value == "Men"){
        document.getElementById("input1").disabled = false;
    }else{
        document.getElementById("input1").disabled = true;
    }

 if(cat.value == "Women"){
        document.getElementById("input2").disabled = false;
    }else{
        document.getElementById("input2").disabled = true;
    }

 if(cat.value == "Both"){
        document.getElementById("input1 input2").disabled = false;
    }else{
        document.getElementById("input1 input2").disabled = true;
    }

 if(cat.value == "Youth"){
        document.getElementById("input1 input2").disabled = false;
    }else{
        document.getElementById("input1 input2").disabled = true;
    }

 }

A: Use switch instead of multiple ifs.

         function JoinedOrNot() {
           var cat = document.getElementById("category").value;
           var input1Disabled = false;
           var input2Disabled = false;

           switch(cat) {
               case "Men":
                   input2Disabled = true;
               break;
               case "Women":
                   input1Disabled = true;
               break;
           }

           document.getElementById("input1").disabled = input1Disabled;
           document.getElementById("input2").disabled = input2Disabled;

         }

          Group Category

            <select class="form-control" name="category" id="category" onChange="JoinedOrNot()">
              <option value="">Select Category</option>
              <option value="Men">Men</option>
              <option value="Women">Women</option>
              <option value="Youth">Youth</option>
              <option value="Both">Both</option>
            </select>

          Number Of Men

            <input type='text' size='5' name="man" id="input1" value="" class='input' disabled></input>

          Number Of Women

            <input type='text' size='5' name="woman" id="input2" value="" class='input' disabled></input>


text:
Q: Why do LUIS app lose endpoint key if I use it in several apps? I have several LUIS apps, 6 normal and 5 dispatch. I assign the same endpoint key from a cognitive service en Azure to all of them. But it seems that there are always two that end up losing the resource somehow.
Couldn't find any documentation about a limit on how many LUIS apps can use the same endpoint at the same time.

A: You can assign the same subscription key/endpoint key to multiple LUIS apps assuming they are in the same region. Also, the authoring key in LUIS.ai is not the same as the endpoint LUIS subscription key in portal.azure.com. The authoring key allows you to author any LUIS app and the endpoint key allows you to query any LUIS endpoint. The endpoint key allows a quota of endpoint hits based on the usage plan you specified when creating the key. This gives you a detail on the key limits for different subscriptions.


text:
Q: Why does my code stop after processing one html? I have created a code, but it stops after one html is processed. Am I overlooking something?
I would appreciate the help!
import textwrap
import os
import pandas as pd
import textwrap
import os
from bs4 import BeautifulSoup

directory ='C:/Research syntheses - Meta analysis/SeekingAlpha/Tests'
for filename in os.listdir(directory):
    if filename.endswith('.html'):
        fname = os.path.join(directory,filename)
        with open(fname,errors='ignore') as f:
            soup = BeautifulSoup(f.read(),'html.parser')

print('{:<30} {:<70}'.format('Name', 'Answer'))
print('-' * 101)
for answer in soup.find('div',class_='content_part hid', id='article_qanda').find_all('strong'):
    txt = answer.get_text(strip=True)

    s = answer.find_next_sibling()
    while s:
        if s.name == 'strong' or s.find_all('strong'):
            break
        if s.name == 'p':
            txt += ' ' + s.get_text(strip=True)
        s = s.find_next_sibling()

    txt = ('\n' + ' '*31).join(textwrap.wrap(txt))
    print('{:<30} {:<70}'.format('exec', txt))

A: Thanks to ekhumoro, the answer is:
import textwrap
import os
import pandas as pd
import textwrap
import os
from bs4 import BeautifulSoup

directory ='C:/Research syntheses - Meta analysis/SeekingAlpha/Tests'
for filename in os.listdir(directory):
    if filename.endswith('.html'):
        fname = os.path.join(directory,filename)
        with open(fname,errors='ignore') as f:
            soup = BeautifulSoup(f.read(),'html.parser')

        print('{:<30} {:<70}'.format('Name', 'Answer'))
        print('-' * 101)
        for answer in soup.find('div',class_='content_part hid', id='article_qanda').find_all('strong'):
            txt = answer.get_text(strip=True)

            s = answer.find_next_sibling()
            while s:
                if s.name == 'strong' or s.find_all('strong'):
                    break
                if s.name == 'p':
                    txt += ' ' + s.get_text(strip=True)
                s = s.find_next_sibling()

            txt = ('\n' + ' '*31).join(textwrap.wrap(txt))
            print('{:<30} {:<70}'.format('exec', txt))


text:
Q: jQuery Hide/Show with Slide on Hover... better way to do this? Basically having some trouble with using Hover to hide or show an item.
The idea is simple, on hover show a div.  When no longer hovering, hide it.  Problem is if the mouse hovers over the div and leaves too quickly, the show/hide div will stay visible.  I'm hoping this is something easily remedied and not a typical problem with the hover event.
 jQuery
 (
   function()
   {
     jQuery(".slideDiv").hide();

     jQuery(".mainDiv").hover
     (
       function()
       {
         var children = jQuery(this).children(".slideDiv");

         if (children.is(":hidden"))
         {
           children.show("slide", { direction: "left" }, 100);
         }
       },
       function()
       {
          var children = jQuery(this).children(".slideDiv");
          children.hide("slide", { direction: "left" }, 100);
       }
     );
   }
 );

Styles look like:
 .mainDiv
 {
   margin:5px;
   height:200px;
 }

 .slideDiv
 {
   background-color:Teal;
   float:left;
   height:200px;
   position:absolute;
   z-index:100;
 }

And markup

            Hover me

            Do you see me?

            Hover me too

            Do you see me now?

A: I tried your script and it did as you described. I tried removing the children.is(":hidden") from your script, but the problem still occurred.
When I rewrote it the script the div never stays visible. So, it appears that the problem is with using jQuery's children instead of find to get to the object:
Still has problems:
 jQuery (
   function(){
     jQuery(".slideDiv").hide();
     jQuery(".mainDiv").hover (
       function() {
         $(this).children(".slideDiv").show("slide", { direction: "left" }, 100);
       },function(){
         $(this).children(".slideDiv").hide("slide", { direction: "left" }, 100);
       }
     );
   }
 );

Works as intended:
 $(document).ready(function(){
   $('.slideDiv').hide();
   $('.mainDiv').hover(
     function(){
       $(this).find('.slideDiv').show('slide', { direction: 'left' }, 100)
     },
     function(){
       $(this).find('.slideDiv').hide('slide', { direction: 'left' }, 100)
     }
   )
 })

And yes, The hoverIntent plugin is nice :P

A: Use the hoverIntent plugin. This avoids anything being shown if the user simply passes the mouse over the elements, and avoids an unsightly chain of animations.


text:
Q: Feedback topologies advantages We have 4 negative feedback topologies;series-shunt, series-series, shunt-shunt, shunt-series. I'd like to know something where we use these topologies. What are advantages compared to their each other ?

A: Based on the requirements of the application, the different topologies of feedback amplifiers are used accordingly.
Operational Amplifier: an ideal one has an infinite input impedance (to avoid loading effect) and very low output impedance.
A series shunt (or voltage series) feedback amplifier topology has a high input impedance and a low output impedance. A voltage shunt (shunt shunt) feedback amplifier topology has both low input and output impedances.  A series series (current series) feedback amplifier topology offers a high input impedance as well as a high output impedance.


text:
Q: Min height of html body element I am creating a web page using HTML CSS and js. I have implemented the media queries for different width and they work perfectly as planned.
The min-height clause doesn't hold true upon window resizing. Upon vertical resizing, the webpage is getting squished even though I have declared all the section min-height (in pixels) individually.
body {
   min-height: 750px,
   height: 100vh,
   display : grid,
  ........
}

Please help

A: Your CSS code is wrong. Use ; instead of ,

body {
   min-height: 750px;
   height: 100vh;
   display : grid;
  ........
}

A: I think your CSS syntax is incorrect, you're using , instead of ; for line break.
Try using ; when closing CSS statements.
body {
   min-height: 750px;
   height: 100vh;
   display : grid;
}

A: Just use the min-height and also you need to use ; instead of ,:
body {
  min-height: 750px;
  display: grid;
}


text:
Q: What's the difference between repo id and repo name on RPM based distributions? When I run yum repolist all on a Red Hat system, it lists both a "repo ID" and "repo name". I'm confused as to how a single repository has multiple IDs. Is it because a repository can contain others?

A: repo id is the unique identification for the repo whereas repo name is just a more meaninful (perhaps) natural language description.


text:
Q: .Net 4.5 wpf printing issue, paper size is always NorthAmericaLetter I have an issue with printing in WPF. In .Net 4.5 it always prints with paper size NorthAmericaLetter. In .Net Framework 3.5 it prints on the correct paper size, which I defined in Code. I tried it in the same Solution, with the same Code and just changed the Target Framework.
My question is, am I missing something in the PrintTicket configuration or how can I set the paper size in .Net 4.5 correctly?
var visual = new DrawingVisual();

using (var context = visual.RenderOpen())
{
    context.DrawRectangle(Brushes.CadetBlue, new Pen(Brushes.Black, 2),
        new Rect(new Point(0, 0), new Size(793, 1122)));
    context.DrawRectangle(Brushes.Brown, new Pen(Brushes.Black, 2),
        new Rect(new Point(20, 20), new Size(40, 40)));
    context.DrawRectangle(Brushes.Brown, new Pen(Brushes.Black, 2),
        new Rect(new Point(20, 257), new Size(40, 40)));
}

var queue = new LocalPrintServer().DefaultPrintQueue;

queue.UserPrintTicket.PageMediaSize = queue
    .GetPrintCapabilities()
    .PageMediaSizeCapability
    .Single(x => x.PageMediaSizeName == PageMediaSizeName.ISOA4);

queue.UserPrintTicket.PageOrientation = PageOrientation.Portrait;

var writer = PrintQueue.CreateXpsDocumentWriter(queue);
writer.Write(visual);

A:         PageMediaSize pageMediaSize = new PageMediaSize(PageMediaSizeName.ISOA4);
        if (printCapabilities.PageMediaSizeCapability.Contains(pageMediaSize))
        {

            PrintTicket deltaPrintTicket = new PrintTicket {PageMediaSize = pageMediaSize };

            var result =
                queue.MergeAndValidatePrintTicket(queue.UserPrintTicket,
                    deltaPrintTicket);

            if (result.ValidatedPrintTicket.PageMediaSize == pageMediaSize)
            {
                queue.UserPrintTicket = result.ValidatedPrintTicket;
                queue.Commit();
            }
        }

You'll have to merge and validate the printticket:

A: Maybe queue.Commit(); is missing?


text:
Q: precedence over event handlers I am not sure if this is a good question or not but I would love to hear some inputs on this.
Imagine there are 2 kinds of events:
A: a mouse click
B: mouse is currently inside a box

Also, imagine there are 2 kinds of event handler functions:
f: console.log("mouse is clicked")
g: console.log("mouse is clicked inside the box")

Now what I want the code to do is, when the mouse is clicked anywhere but inside the box, display the message "mouse is clicked". However, when the mouse is clicked inside the box, display the message "mouse is clicked inside the box".
My current way of implementation looks like follows:
if (A) then {f()}
if (A and B) then {g()}

In short, I registered f as a listener for A, and created a new event that fires when both A and B hold, and registered g ans a listener for that event.
of course, when the mouse is clicked inside the box, I get two messages:
"mouse is clicked inside the box"
"mouse is clicked"
rather than the single "mouse is clicked inside the box" that I am looking for.
Is there any formal way of defining what is happening, and what is the best way to address it? In short, I want the event handler g to have precedence over the handler f, such that when g is invoked it suppresses the invocation of f.

A: What you need to read up on is event bubbling and propagation in jQuery.
A jQuery event handler callback will be passed an event object as a parameter. This contains a method that can be called to stop the event propagation, or 'bubbling' up to any parent handlers.
For your example, this means you can bind an event to the window/whole document for 'mouse is clicked', and then bind an event to only the box for 'mouse is clicked inside the box' - but stop this event from reaching the parent handler.
$(body).click(function() {
    console.log("mouse is clicked");
});

$("#box").click(function(e) {
    e.stopPropagation();
    console.log("mouse is clicked inside the box");
});

On parent handlers (event bubbling)
To be more specific, the handlers themselves do not have a parent/child relationship - they are just bound directly to the DOM elements. What do have a parent/child relationship is the DOM elements themselves.
In this example, #box is a child of the body element (although probably with other elements in between). When a click is triggered on #box, the handler will be checked for the element, and then the element's parent, and then the element's parent's parent etc ... all the way up the DOM tree. This will continue until either the event is stopped from bubbling, or the top of the tree is reached.
In this way, you could add another element inside box and add another handler to do the same thing, i.e. #button - and if you stopped propagation of the event, neither the #box or body message would appear.

A: This can be achieved with one event listener:
window.addEventListener('click', function (e) {
    if (document.getElementById('box').contains(e.target)) {
        alert('Box clicked!');
    } else {
        alert('Not box clicked!');
    }
}, false);

or jQuery:
$(window).click(function (e) {
    if ($('#box')[0].contains(e.target)) {
        alert('Box clicked!');
    } else {
        alert('Not box clicked!');
    }
});


text:
Q: Combining Sympy with scipy.optimize.least_squares I'm trying to calculate the value of the variables D and theta for which the function E attains its minimum value.
E = sqrt(x1-Dcos(theta)^2 + (y1-Dsin(theta)^2)) + sqrt(x2-2Dcos(theta)^2 + (y2-2Dsin(theta)^2)) + sqrt(x3-3Dcos(theta)^2 + (y3-3Dsin(theta)^2)).
Here, (x1,y1), (x2,y2), (x3,y3) are known. Now I calculate the partial derivatives of E wrt to D and theta and set them to zero. Now I have 2 equations and 2 unknowns, so theoretically this system should be exactly solvable. The only issue here is that this is highly non-linear. So analytical solutions are out of the question. I'm using Sympy here to calculate the partial derivatives and generate the equations to be used in least_squares from scipy.optimize. I do get a solution for D and theta but it doesn't make any physical sense. Furthermore, the cost value of least_squares is ~17, so my solutions are not very reliable, right? Could someone help me out here? Here's the code:
import sympy as sym
D, theta = sym.symbols("D, theta")
x1,x2,x3 = 9.0,22.0,24.0
y1,y2,y3 = 14.0,14.0,14.0

E = ((x1-D*sym.cos(theta))**2 + (y1-D*sym.sin(theta))**2)**0.5 + ((x2-2*D*sym.cos(theta))**2 + (y2-2*D*sym.sin(theta))**2)**0.5 + ((x3-3*D*sym.cos(theta))**2 + (y3-3*D*sym.sin(theta))**2)**0.5

gradient = sym.derive_by_array(E, (D, theta))

from scipy.optimize import least_squares as ls
grad = sym.lambdify((D, theta), gradient)
A = ls(lambda v: grad(v[0],v[1]), (8,0), bounds=([0, -22.5*np.pi/180], [12, 22.5*np.pi/180]))  #theta should be between -22.5 degree and 22.5 degree and D should be between 0 and 12 but ideally not 0.
D2, theta2 = A.x # 0.04561884938833529 -0.3926990816987241

I should also mention that calculating D and theta is part of a problem that involves fitting a line through (x1,y1), (x2,y2), (x3,y3), and (13,2). D is the distance between (13,2) and the first point closest to (x1,y1) on the fitted line, 2D is similarly the distance between (13,2) and the second point closest to (x2,y2), and so on. This analysis has to be done over all the gridpoints on a lat-lon grid of size (21,69). All alternate suggestions to solve this problem are also welcome. Thanks in advance!

A: You are looking to approximate the sequence 9, 22, 24 with an equidistant sequence like 11,18,25. This does not have a good fit, so a large residual value is reasonable.
Doing the least square sum manually gives

(a-d-9)^2 + (a-22)^2 + (a+d-24)^2 = 3*a^2 +2*d^2 - 110*a - 30*d +const

so the optimum is at a = 55/3 = 18+1/3 and d = 15/2 = 7+1/2

On a second glance, you try to minimize the sum of norms, that is, the sum of distances from points on a line parallel to the x axis to points equidistant on a line through the origin. You can do that without doing any least-squares gradient optimization (which is a strange idea anyway, why not just find the zero location of the gradient with fsolve?)
x = np.array([ 9.0,22.0,24.0])
y = np.array([14.0,14.0,14.0])
K = 1+np.arange(len(x))

target = lambda X,Y: sum(np.hypot(x-K*X, y-K*Y))

from scipy.optimize import fmin, minimize

#U = fmin(lambda u: target(*u), [4,4])
U = minimize(lambda u: target(*u), [4,4])
print(U)
X,Y = U.x
print(X,Y, np.hypot(X,Y), np.arctan2(Y,X))
K = np.arange(1+len(x))
plt.plot(x,y,'o', ms=8); plt.plot(K*X,K*Y, '-s', ms=4); plt.grid(); plt.show()

with the results
fmin:
-----
Optimization terminated successfully.
         Current function value: 16.987937
         Iterations: 49
         Function evaluations: 92

minimize:
---------
      fun: 16.987921401556633
 hess_inv: array([[2.72893764e-08, 6.01803467e-08],
       [6.01803467e-08, 1.53257534e-07]])
      jac: array([ 1.29665709, -0.08849001])
  message: 'Desired error not necessarily achieved due to precision loss.'
     nfev: 740
      nit: 29
     njev: 182
   status: 2
  success: False
        x: array([8.        , 4.66666667])

X: 8.000000, Y: 4.666667,
D: 9.261629, theta:  0.5280744


text:
Q: Regex in C# - Unrecognized escape sequence I totally get how to escape back slashes, which is why this is throwing me for a loop:

I have tried everything -- not using @ and manually escaping the back slashes, use the @ and escaping... nothing seems to work. What am I missing? What am I doing wrong?
I am using .NET Core 2.0.
Here is the code:
        var path = "this is a test/{lcc_root_whatever}/string done.";
        if (Regex.IsMatch(path, @"\Q/{lcc_root_\E[[:word:]]+\Q}/\E"))
        {

        }

A: You actually do not even need to escape anything, remove \Q and \E (that are not compatible with .NET regex). You still need to change [[:word:]] to \w.
Use
if (Regex.IsMatch(path, @"/{lcc_root_\w+}/"))


text:
Q: gradle distribution - относительный путь к папке как при отладке, так и при сборке Возможно, заголовок не очень понятен, опишу проблему подробнее.
Требуется настроить build.gradle
Имеется следующая структура проекта:
main
  java
  config

и build.gradle (ниже только значимый код из скрипта)
distributions {
    main {
        contents {
            into('config') {
                from 'src/main/config'
            }
         }
     }
}

в папке config лежат файлы (ini, logback и т.д.) которые я хочу изменять как в процессе разработки, так и в процессе работы уже с собранным приложением.
Т.е к примеру в коде написано new FileReader("main.ini") (main.ini лежит в папке config)
и я хочу, чтобы программа подхватывала параметры по относительному пути во всех трех случаях:

*

*gralde run (application plugin)

*idea - Main - run (обычный run на main классе)

*gradle distZip - unzip - ./program.sh
Как это сделать максимально корректно?

A: Сделайте в структуре проекта ресурсы, и тяните по YourClass.class.getResourceAsStream("/config/my.ini"); При этом никаких танцев с бубном не требуется


text:
Q: Not able to use getElementsById in vba for web scraping I need to get this number 13 from a website
HTML code

to
10
of
13

Some of the issues here:

*

*The id's changes after every refresh, so I'm not able to use getElementsById

*Also, Not able to use getElementsByClassName. I get a run time error 91, Object variable or with block variable not set

VBA Code
Private Sub CommandButton1_Click()

    Dim http As New XMLHTTP60, html As New HTMLDocument
    Dim name As Object

    With http
        .Open "GET", "website", False
        .send
        html.body.innerHTML = .responseText
    End With

    Set name = html.getElementsByClassName("list_row_number_input")(1)
Range("A6").value=name.innerText
End Sub

Please suggest how to handle this situation and get the required value in excel.
Thank you.


text:
Q: How to make this segue animation exit to right or left side? - Swift This code works fine to make my custom segue transition with a downwards animation. How would I make the animation look as if it is transitioning to the left or right?
Also - I am using a UISwipeGestureRecognizer to trigger the segue. It works fine except that the segue occurs as soon as I do the smallest swipe. How would I allow the segue to not occur untill a user has lifted their finger off or atleast done a larger swipe. Would I need to use a scrollView for this?
Below is my code for my UISwipeGestureRecognizer.
override func viewDidLoad() {

    var swipeGestureRecognizer: UISwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "showSecondViewController")
    swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Up
    self.view.addGestureRecognizer(swipeGestureRecognizer)

}

The code below is my animation code
class FirstCustomSegue: UIStoryboardSegue {

override func perform() {

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(0.0, screenHeight, screenWidth, screenHeight)

    // Access the app's key window and insert the destination view above the current (source) one.
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(secondVCView, aboveSubview: firstVCView)

    // Animate the transition.
    UIView.animateWithDuration(0.5, animations: { () -> Void in
        firstVCView.frame = CGRectOffset(firstVCView.frame, 0.0, -screenHeight)
        secondVCView.frame = CGRectOffset(secondVCView.frame, 0.0, -screenHeight)

        }) { (Finished) -> Void in

                    self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                        animated: false,
                        completion: nil)
            }
    }
}

A: Animation Direction
You will simply need to change the initial and destination frames. Currently the secondVCView's initial frame's X,Y origin 0.0, screenHeight, meaning it sits just below the bottom of the screen. If you want it to appear from the right you would need to change it to screenWidth, 0.0.
Then the destination frame of firstVCView would change so the origin is -screenWidth, 0.0 and the destination frame of secondVCView would change so the origin is 0.0, 0.0
override func perform() {

    // Specify the initial position of the destination view.
    secondVCView.frame = CGRectMake(screenWidth, 0.0, screenWidth, screenHeight)

    // Access the app's key window and insert the destination view above the current (source) one.
    let window = UIApplication.sharedApplication().keyWindow
    window?.insertSubview(secondVCView, aboveSubview: firstVCView)

    // Animate the transition.
    UIView.animateWithDuration(0.5, animations: { () -> Void in
        firstVCView.frame = CGRectOffset(firstVCView.frame, -screenWidth, 0.0)
        secondVCView.frame = CGRectOffset(secondVCView.frame, -screenWidth, 0.0)

        }) { (Finished) -> Void in

                    self.sourceViewController.presentViewController(self.destinationViewController as! UIViewController,
                        animated: false,
                        completion: nil)
            }
    }
}

Delayed swipe
Modify your showSecondViewController method to accept a UISwipeGestureRecognizer parameter and inspect it's state property. If you want to trigger the segue when the user has lifted their finger trigger the segue when the state is UIGestureRecognizerStateEnded.
If you want more fine grained control such as when they have swiped a certain distance you will need to check the state for UIGestureRecognizerStateChanged and monitor the location of the touch. I'll leave that as an exercise for the reader as there are plenty of examples a quick Google search away :)