text:
Q: How can I generate dynamic button depends on the amount of data in Firebase I store my data in firebase in this format as you can see below:
public class web_view extends AppCompatActivity {
            //for fav
            FloatingActionButton fab;

            private WebView webView;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_web_view);

                fab = findViewById(R.id.btn_fab);
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        //start
                        String passURL = getIntent().getStringExtra("key");
                        //add wishlist to firebase with auto generate ID
                        DatabaseReference myRef = FirebaseDatabase.getInstance()
                                .getReference().child("Users")
                                .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Wishlist");
                        myRef.push().setValue(passURL).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {
                                if(task.isSuccessful()){//show it if complete
                                    Toast.makeText(web_view.this, "Added to wishlist", Toast.LENGTH_SHORT).show();
                                }else{//just error handler
                                    Toast.makeText(web_view.this, "Something went wrong", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                        //End send wishlist to firebase

                    }
                });
    }
}

I want to retrieve these data and create button dynamical. For example if user click this "fab_wishL", program will retrieve data from firebase and auto create button. If there is 5 data in firebase, there will be 5 button. Is there any way to auto create the button depend on the quantity of the data in friebase
public class search_book extends AppCompatActivity {

        //---wishlist

            FloatingActionButton fab_wish;

        @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_search_book);
                //wishlist
                fab_wish = findViewById(R.id.fab_wishL);
                fab_wish.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(search_book.this, wish_list.class));
                    }
                });
        }
}

A: You need to add value change listeners to the database reference child, it will give you the list of data you have there, then you can loop to that data and add buttons at runtime.
Check the link for a better understanding
https://firebase.google.com/docs/database/admin/retrieve-data


text:
Q: How to start a program with command line arguments on Windows' cmd and force it to run foreground? I'm executing a offline smoke test (SELENIUM) and to make it enable the macros in a excel spreadsheet that is generated by the system, I had to use a workaround where in the java code, I open the excel spreadsheet, save and close it, so that I can run the test and write values onto this spreadsheet. To open the excel spreadsheet (I setup excel to trust all macros), I wrote the following java code where I use command line commands to execute it:
@Then("Enable Worksheet Macros")
public void enableWorksheetMacros() throws InterruptedException, IOException, AWTException {

    final String diretory = "c:\\automation\\";
    final File file = new File(diretory);

    final File[] files = file.listFiles(new FileFilter() {
        @Override
        public boolean accept(File file) {
            return file.getName().toLowerCase(Locale.ENGLISH).endsWith(".xls");
        }
    });

    if (files.length > 1) {
        System.out.println("too many files");
    } else if (files.length == 1) {
        final String filename = files[0].getAbsolutePath();

        final ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "start", filename);
        final Process p = pb.start();
        p.waitFor();
        Thread.sleep(5000);

        final Robot r = new Robot();

        r.keyPress(KeyEvent.VK_ALT);
        r.keyPress(KeyEvent.VK_F4);
        Thread.sleep(200);
        r.keyRelease(KeyEvent.VK_F4);
        r.keyRelease(KeyEvent.VK_ALT);
        Thread.sleep(200);

        r.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(200);
        r.keyRelease(KeyEvent.VK_ENTER);
        Thread.sleep(200);

        r.keyPress(KeyEvent.VK_ENTER);
        Thread.sleep(200);
        r.keyRelease(KeyEvent.VK_ENTER);
        Thread.sleep(200);
    }

}

As you can see, right after opening the excel file, I just press ALT+F4 and press ENTER twice (it closes the file and save it). It was working fine, until I run this code in another environment, where when it opens the excel file, it is running background.
Is there a way I can make sure the program will run foreground?
EDIT:
I found this question on SU where the guy has the same problem I do, but no answer until now: https://superuser.com/questions/700879/windows-task-scheduler-starting-excel-in-background-how-to-force-to-start-in-fo

redpajama_set_name: RedPajamaStackExchange


text:
Q: React-Native Invariant Violation: Element type is invalid When I going to run my react native app on my iPhone Expo this error displayed in red background area.

Invariant Violation: Element type is invalid: expected a string (for built-in components)
  or a class/function (for composite components) but got: object. You
  likely forgot to export your component from the file it's defined in.

this is the App.js inside the 'src/components/' folder

import React, { Component } from 'react';
import { View, Text } from 'react-native';

export default class App extends Component {
  render() {
    return (
     <View>
        <Text>Hello</Text>
       </View>
    );
  }
}

This is the main App.js in react-native app folder.

import App from './src/components/App';

I used expo app for run this code. How can I solve this error?

A: In my case instead of exporting like this:
export default App;

...I exported like following:
export {LoginForm};

It worked completely fine.

A: I had this error from doing my export in the following style with no default export specified. I did not specify a default because I was exporting multiple small components from one file.
export const  Modal  = (props) => (
    <div className="someClass">
    </div>
  )

I was able to get it working by adding brackets to the import statement.
import {Modal} from '../components/Modal.js'

A: Expo expects you to export a component from /App.js. But right now you are only importing into /App.js. Expo is not receiving any component to render. You need to export the component you imported like this:
export default App;

On side note: Use a class component only if you must.

A: i had same issue and i put
export default
before
class yourclassname extends Component
in App.js

A: For what it's worth, I had exactly this issue and it had me stumped for 2 days. My mistake was creating and renaming some files — stupidly, whilst my project was still running. This inadvertently messed up some of my paths/imports. I wasn't seeing any issues in VS Code however every time I ran the project it would work first time after a full clean and then when I refreshed I'd get this error:
ERROR  TypeError: undefined is not a function, js engine: hermes
ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication).
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes
ERROR  Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication). A frequent cause of the error is that the application entry file path is incorrect.
This can also happen when the JS bundle is corrupt or there is an early initialization error when loading React Native., js engine: hermes

I only knew this was the issue because I got my colleague to sync the project using my branch and test it on his Mac and it worked fine. The solution might be to try cleaning Android, iOS and Watchman first and if that doesn't work I would suggest try deleting the project folder from your machine and re-clone the repo and run it again.
Useful clean scripts to try:
For Android:
watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf node_modules && rm -rf yarn.lock && yarn cache clean && yarn && cd android && ./gradlew cleanBuildCache && cd ..

For iOS:
watchman watch-del-all && rm -rf $TMPDIR/react-native-packager-cache-* && rm -rf $TMPDIR/metro-bundler-cache-* && rm -rf ~/Library/Developer/Xcode/DerivedData && rm -rf node_modules && rm -rf yarn.lock && rm -rf ios/build && yarn cache clean && yarn && cd ios && pod install --repo-update && cd ..


text:
Q: CouchDB emit on OR match I have query related with CouchDB:
Let's consider my DB name: test, view name: user-view & design name: _design/user.
I have following documents in couchdb:
{ "name" :"ABC", "city" :"Mumbai" }
{ "name" :"PQR", "city" :"Mumbai" }
{ "name" :"XYZ", "city" :"Pune" }
{ "name" :"ABC", "city" :"Pune" }

I have following user-view:
function(doc) {
   emit([doc.name, doc.city], doc);
}

When I send following GET request:
http://127.0.0.1:5984/test/_design/user/_view/user-view?include_docs=true&key=['ABC','Pune']

I get following result:
{ "name" :"ABC", "city" :"Pune" }

Suppose I have only values for either name or city at a time and I want to use same view user-view and get following results:
Case 1 Only name is available as ABC
I should get following result:
[
  { "name" :"ABC", "city" :"Mumbai" }
  { "name" :"ABC", "city" :"Pune" }
]

Case 2 Only city is available as Pune
I should get following result:
[
   { "name" :"XYZ", "city" :"Pune" }
   { "name" :"ABC", "city" :"Pune" }
]

Case 3 Only name as ABC and city as Pune is available
I should get following result:
[
   { "name" :"ABC", "city" :"Mumbai" }
   { "name" :"XYZ", "city" :"Pune" }
   { "name" :"ABC", "city" :"Pune" }
]

Now consider I have multiple keys (name, city, region, zip-code, etc.) and at a time it is possible that I could have any single or multiple combinations of keys to query (e.g. only value for name available at a time or only value for city and region available at a time and etc) and I don't want to end up in creating multiple views. Is it possible to use single view and still able to get results for any combination of keys?

A: This is technically possible, but ill-advised.
The way to use the same view for cities and names is to emit both in your map function:
function(doc) {
   emit(doc.name, doc);
   emit(doc.city, doc);
}

The reason this is ill-advised is that you'll never know if what you're querying is a city or a name. And if you have a person named the same as a city, for example, you'll get both results.
So the correct way to handle this is with two views, one for cities, and one for names.
You could work around this by qualifying the key type in your map function, but this complicates your queries, too, because you must specify which key type you want to query:
function(doc) {
   emit("name:"+doc.name, doc);
   emit("city:"+doc.city, doc);
}

It will be somewhat more efficient in terms of disk usage, index query speed (although probably marginally so), and readability of your queries, to use two views.


text:
Q: Inner Product, Definite Integral Does the map $<f, g>$ $=$ $\int _0^1\:\left(\left(f\left(x\right)-\frac{d}{dx}f\left(x\right)\right)\left(g\left(x\right)-\frac{d}{dx}g\left(x\right)\right)\right)dx$ define an inner product on the set of all polynomial functions of order less than or equal to $n$?
Although I felt that this map was symmetric and bilinear by the properties of definite integrals, I did not think it was positive definite. This was because, say, $<f, f>$ would become $\int _0^1\:\left(\left(f\left(x\right)-\frac{d}{dx}f\left(x\right)\right)^2\right)dx$, which has value greater than zero for values other than the zero function. For example, if $f(x)$ was $2x$, then $f'(x)$ would be $2$ and the value of the above definite integral would be $4/3$. This is why I don't think this space defines an inner product.
So what I am worried about is that I am misunderstanding how the concept of zero vectors with regards to inner products work as this seems to obvious.
If anyone can verify what I have done or tell me how I went wrong, I would greatly appreciate it!

A: We have $<f, f>=\int _0^1\:\left(f\left(x\right)-f'\left(x\right)\right)^2dx \ge 0$ and
$<f, f>=0 \iff f=f'$ on $[0,1] $.
Since $f$ is a polynomial, we get
$<f, f>=0 \iff f=0$ on $[0,1] $.


text:
Q: Deactivate Plugin on Theme Switch I am developing a plugin, let's call it DahPlugin, that provides additional customizer options for a free theme I developed. Let's call this theme DahTheme (I don't want to shamelessly plug either one of them here).
So what I am trying to accomplish is, I would like for DahPlugin to be automatically deactivated the when the user changes themes away from DahTheme.
I found this code snippet here: disable active plugins for specific theme, which works really well if you want to disable plugins if a certain theme is active.
So I decided I would be clever and utilize it in my theme and switch the logic. So I changed the comparison operator from == (equal) to != (not equal)...my thinking: If the current theme name is not equal to "DahTheme", then deactivate "DahPlugin" and here is what it looks like:
if ( ! function_exists('disable_plugins')) :
    function disable_plugins(){
        include_once(ABSPATH.'wp-admin/includes/plugin.php');
        $current_theme = wp_get_theme();
        $current_theme_name = $current_theme->Name;

        if($current_theme_name == 'DahTheme'){
            if ( is_plugin_active('dahplugin/dahplugin.php') ) {
                deactivate_plugins('dahplugin/dahplugin.php');
            }
        }
    }
    add_action('after_switch_theme','disable_plugins');
endif;

Aaaaaaand it doesn't work...lol! Of course this happens whenever I think I'm being clever.
So I have been racking my brain and looking all over the place to try and figure out what or why it isn't working and I can't seem to find that either.
Can anyone show me why it's not working and why my line of thinking is wrong. That would be greatly appreciated.
Thanks in advance for any help.

A: I haven't tested this, so it might not work correctly, but the essence of what you're trying to do is hook into the after_switch_theme hook and see if the $old_name is DahTheme. If it is, that means that the current theme isn't DahTheme, so you want to deactivate the plugin.
function wpse_after_switch_theme( $old_name, $old_theme ) {
  if( 'DahTheme' === $old_name ) {
    //* You may or may not need to include wp-admin/includes/plugin.php here
    deactivate_plugins( 'dahplugin/dahplugin.php' );
  }
}
add_action( 'after_switch_theme', 'wpse_after_switch_theme', 10, 2 );

A: This entire approach is backwards. The problem is not deactivating on theme switch, but making sure the plugin isn't available unless the theme it was built for is active.
So, the check should be in the plugin, not the theme
So lets start by figuring out which theme is active, we can do this via wp_get_theme documented here
We then Register a hook in our plugin on admin_init:
add_action( 'admin_init', function() {
    $theme = wp_get_theme();
} );

Then, if the theme isn't the intended theme, deactivate:
if ( $theme->headers['name'] !== 'DahTheme' ) {
    deactivate_plugins( plugin_basename( __FILE__ ) );
}

Notice that deactivate_plugins is plural, and it requires an absolute path. Because of the use of __FILE__, this check must be in the main plugin file.

Although, this complicates things when switching back to 'DahTheme' as now the plugin is inactive, so it would be better to do the check then return early, so the plugin does nothing, rather than deactivating. This way no customizer options are presented for incompatible themes, and no issues happen when the user previews themes or switches back

A: I basically solved this issue by using is_plugin_active - before I was loading additional panels and sections with the plugin and when someone chose another theme the customize register created by the plugin was still there was still there and when they went into the new themes customizer, a fatal error was generated.
This corrected the issue.

A: This is not exactly the answer to the asked question. However, this will be helpful for many who are looking to perform certain action after activation or deactivation of themes.
// Perform action when your theme is deactivated (actually switched to another)
add_action( 'switch_theme', 'action_switch_theme', 10, 1 );
function action_switch_theme( ) {
    // deactivate your plugin
};

// Perform action after your theme is activated (switched from other theme)
add_action( 'after_switch_theme', 'action_after_switch_theme', 10, 1 );
function action_after_switch_theme( ) {
    // activate your plugin
};


text:
Q: Wave Propagation in Transmission Lines let's consider this image (from AAC book, see here)

The author wanted to show that a transmission line propagates not only voltage and current waves, but also an electromagnetic wave in the space between its 2 conductors.
But I have a question: from the image I think that the magnetic field shown is that generated by the wire, but how is the electric field? From the image I do not see its direction, if it is rotational or not, and I do not understand if it is the electric field generated by the voltage applied to the transmission line (since voltage between two points = electric field) or the electric field generated by the variation in time of the magnetic field represented in green.

A: The magnetic field around the wire corresponds to the current in the wire. More correctly, the magnetic field in the space between the wires corresponds to the current loop formed by the source, one wire, the sink, and the other wire.
The electric field between the wires corresponds to the voltage between the wires. If there's 10v measured between the wires, and a distance of 1m between them, then the field will be about 10v/m (varies with the position), with a conventional direction of from the positive conductor to the negative conductor. The direction isn't shown on your diagram, perhaps to avoid clutter, perhaps because the author thought it was obvious.
It's common to hear transmission lines described as wave guiding structures.

A: For a 2-wire transmission line (antenna lead-in wires, but also a DC flashlight, or a 60Hz lamp-cord,) the fields in 3-dimensions look more like this below, where the red lines are the magnetic field, and the gray lines are the e-field.

Above, the field-pattern for only two planes is depicted, while in reality, there is a stack of infinitely many such planes.  Refer to your textbook diagram, and you'll see that yours is a simplified "side view" of the fully 3D version.   We treat the two wires as capacitor-plates having opposite charge.   Also, we treat the two wires as part of a 1-turn electromagnet (a long, rectangle-shaped loop.)   Multiplying the fields together as vector cross-product gives the power-density at any point in space  ...or multiplying voltage by amp-turns (for 1-turn loop) gives the total energy flow: watts.
For a disconnected pair of wires, there would be zero current, but significant voltage and e-field, with no energy-flow.  That's the electrostatic case for circuits: voltage without current.
Or, for a superconductor rectangle loop, there would be zero voltage, but significant current and b-field, with no energy flow.  That's the magnetostatic case.   Next, add a resistor-load to the loop, and also insert an energy-source, and then we have both voltage and current together (the cross-product of e-field with b-field,) which produces a one-way energy-flux from the power supply and into the resistor.   Like this below:

*

*E-cross-B, the energy-flux or "Poynting field" in 3D

Notice that there is no lower limit to the frequency.   The description applies both to the GHz 2-wire lines, as well as battery-powered DC circuits.  (Most textbooks miss this important point.  Transmission-line theory applies to flashlights and washing machines!  Kraus "Electromagnetics" is one book which gets it right.)   Even at DC, with waves of "infinite wavelength," the energy-flow is still parallel to the wires, while the e-field and b-field vectors are everywhere at 90deg.  (Or, imagine 60Hz waves many thousands of miles long.  In the center of each "lump" of traveling 60Hz radiation, the fields are perpendicular, and the energy is flowing parallel to the two wires.)   It's not the EM waves which are transverse, it's the very field-vectors themselves which are transverse, even at DC with no waves apparent.  Electric circuits are both inductors and capacitors at once, and that's why EM energy can propagate across them.
An electric circuit with a source and a load, and with an energy-flow propagating between the two  ...it's a unique electronic component: a kind of "coil-pacitor!"


text:
Q: Ejecutar comando Linux en PHP da error "sudo: no tty present and no askpass program specified" Estoy intentando reiniciar un servicio de Linux, pero no me funciona.
Tengo este trozo de codigo sacado de la web:
<form action="reset.php" method="post">
    <input type="submit" value="Reiniciar" class="button" >
</form>

Y este es el reset.php:
<?php

$output = shell_exec("service garen restart");

echo "<pre>$output</pre>";
?>

Cuando le doy al boton para ejecutar el reset.php, se queda en blanco y no ejecuta el comando.
Si añado sudo al comando tampoco me funciona y el log indica:

sudo: no tty present and no askpass program specified

A: El sistema te está diciendo:

sudo: no tty present and no askpass program specified

Esto quiere decir que sudo quiere mostrarte un prompt donde pedirte la contraseña... ¡pero no tiene donde hacerlo porque no se está ejecutando en un entorno donde lo haya!
Por tanto, vayamos al origen del problema: el usuario que quieres que ejecute el comando sudo service garen restart no tiene permisos para hacerlo o al menos directamente sin contraseña, de ahí que la pida.
Lo que hay que hacer es darle permisos en el sudoers y hacerlo de manera que no pida la contraseña.
Suponiendo que estás trabajando con Apache y su usuario es apache, deberías abrir el sudoers con visudo y añadir una línea del tipo:
apache ALL = NOPASSWD: /usr/sbin/service garen restart

Donde /usr/sbin/service puede variar según tu sistema pues es la ruta completa de service. Para obtenerla, escribe which service.


text:
Q: Making manipulation database I am starting to learn databases, but I can't understand the concept in general. I have few questions.

*

*After we make the base and connect our web application to it, how do
    we approach to a group of items and display them in web or server controles where we
        can make CSS changes?

*For example I have base with countries in the world and their
capital cities in two columns, and if I have to add them in a html -
            table, how do I do that, and does it not make one step for making
            the base and one more for adding them to a list so the complexity is twice bigger.

*Why we sometimes create JSON object for database data.

A: *

*After establishing a successful connection, you will be able to bind
data to your controls. You can do it programmatically but using
webforms, you can easily do with sqlDataSource

*For this example you can use a gridview to display that data, or you
can use asp table and build it manually.

*JSON is used to make it easy to send data between server and client.
Otherwise you would have the client directly connect to the DB server,
and that is not good idea.


text:
Q: Can't find elements but they exist Selenium Python I have encountered a problem: the program does not see the elements and cannot print them. Though, I use it several times in code and it worked the first time. A little later, as I said, it stops seeing the element:
HTML code:

...

...

Python code:
elements = driver.find_elements(By.XPATH, "//div[@class='entries-container']/div")
print(len(elements))
print(driver.find_elements(By.XPATH, "//div[@class='entries-container']/div"))

Console output:
0
[]

If instead of elements to find 1 element (print(driver.find_element(By.XPATH, "//div[@class='entries-container']/div"))), then an error will appear in the console, Unable to locale element
What is the problem? Is there another way to find an element?
Updated: I just recreated the HTML page and the program started working. Most likely it was a bug.

A: To get string value from the text nodes you have to invoke .text method. The following xpath expression selects all the div elements
elements = driver.find_elements(By.XPATH, "//div[@class='entries-container']/div")
for element in elements:
    print(element.text)

See the provement from here


text:
Q: Docker Ubuntu cannot stat 'keys/id_rsa' no such file or directory I successfully added my shh key and I copied it from the original file to the folder keys however it cant access to it

My dockerfile :
FROM wernight/phantomjs
#Install casperjs WORKDIR /home

WORKDIR /home
USER root
RUN (apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y git socat python dnsutils )

RUN git clone https://github.com/n1k0/casperjs.git
RUN mv /home/casperjs /usr/local/share/casperjs-latest
RUN ln -sf /usr/local/share/casperjs-latest/bin/casperjs /usr/local/share/casperjs
RUN ln -sf /usr/local/share/casperjs-latest/bin/casperjs /usr/local/bin/casperjs
RUN ln -sf /usr/local/share/casperjs-latest/bin/casperjs /usr/bin/casperjs
ADD /home/afaf/reworldmedia-network/keys/id_rsa  /home/afaf/.ssh/id_rsa
ADD /home/afaf/reworldmedia-network/keys/id_rsa.pub  /home/afaf/.ssh/id_rsa.pub
ADD start.sh /start.sh

ENTRYPOINT /start.sh

A: I solved the problem by adding the following lines to the file docker-compose.yml
tty: true
stdin_open: true

Also I removed the file /var/run/docker.sock and restarted docker services


text:
Q: Microsoft HoloLens Menu creation I could need a little help with creating a menu for my HoloLens App in Unity. I want to have a Menu that always flies with the user (like the Windows Menu of the HoloLens itself). I got a menu that floats with the user (I use the SimpleTagalong and the Billboard scripts from the MixedReality Toolkit), but I still have problems with walls. The menu has always the same distance to the user that leads to the problem that the menu gets lost behind walls. Is it possible to decrease the distance depending to the users distance to a wall, just like the HoloLens Windows menu? Maybe you know an open source project that contains such a menu.
Thanks for your answers.


text:
Q: Failed to set an indexed property on 'FileList': Index property setter is not supported.v angular.module('myApp')
    .directive('fileModel', ['$parse', 'uploadService','messageService','CONF', function ($parse, uploadService,messageService,CONF) {
        return {
            restrict: 'A',
            link: function (scope, element, attrs) {
                var model = $parse(attrs.fileModel);
                var modelSetter = model.assign;
                element.bind('change', function () {

                    var file = element[0].files[0];

                    var fd = new FormData();
                    fd.append('file', file);
                    console.log(fd)

                    self.isDisabled = true;

                       ParkingService.uploadImage(fd).then(
                            function (response) {
                                response = JSON.parse(response);
                                element[0].files[1] = response;
                                console.log(response)
                                    if (response.message !== 'ERROR') {
                                        // self.image = response.result;
                                            messageService.toasterMessage(CONF.TOASTER_TOP_RIGHT,CONF.TOASTER_SUCCESS,"Success Upload File");
                                    }
                                    else {
                                        messageService.toasterMessage(CONF.TOASTER_TOP_RIGHT,CONF.TOASTER_ERROR,response.result);

                                    }
                                }
                        );

                    scope.$apply(function () {
                        modelSetter(scope, element[0].files);
                    });
                });
            }
        };
    }]);

how to set response in this variable?
element[0].files[1] = response;

it works in safari or older chrome. but not support in new chrome..

A: Both Chrome and Firefox now disallow setting new indexes on NodeList and FileList. I suspect this has to do with recent changes to make these "array-like" structures more compatible in general with JavaScript and is general direction where browsers are headed.
Running in non-strict mode reverts the behavior, but is not feasible in a transpiled JavaScript environment - or likely desirable.
Best option would be to convert the FileList to an array using const files = Array.from(element[0].files) or just const files = [...element[0].files] (depending on what browsers you support and what transpilation you're using).


text:
Q: Copiar os arquivos de um remote para outro usando GIT Eu tenho dois remotes configurados, o origin (repositório no heroku) e o github (repositório no github).
No meu repositório local eu fiz diversas alterações porém eu dava o "push" apenas no origin, deixando o github sem atualizações e commits.
Agora eu gostaria de saber como faço para que eu "copie" o origin (heroku) direto pro github.
Os passos que eu fiz foram o seguinte:
git clone git@heroku.com:meurepo.git meurepo
cd meurepo
heroku create
git remote add github git@github.com:meuusuario/meurepo.git
git push github

De início ele dizia que não havia dados a atualizar e que o repositório já estava atualizado mas eu sabia que não. Após alguns comandos como git remote update eu tentei dar novamente git push github e agora aparece o seguinte erro:
! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:rodrigokiller/speedup.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Tentei dar o git pull porém o mesmo erro aparece (de [rejected]).

A: Apenas defina o novo remote e dê um push para o mesmo.
git remote add <nome do novo remote> <url do novo remote>
git push <nome do novo remote> <url do novo remote>

A: Fiquei receoso quanto à tentar corrigir o git pull github master pois pelo que entendo, o pull "baixa" pro repositório local, e como o remote do github estava desatualizado, preferi optar pelo comando que eu também estava receoso:
git push --force github master.
Ao utilizar este comando, deu certo e parece que as novas alterações agora estão indo para os dois remotes (claro, dando um push em cada um separadamente).


text:
Q: Dilworth's theorem
Show that the truth of Dilworth's theorem for two-level posets can be deduced from Hall's theorem.

I am not sure how to prove this.
A poset $P$ is a two-level poset if it is the union of two antichains $U$ and $L$ with no element of $L$ greater than any element of $U$, so the only comparability which occur are of the form $l<u$ for $l\in L, \ u \in U.$
For Hall's theorem we have that if a family $(A_1,\dots,A_n)$ of subsets of $X$ satisfies $|A(J)|\ge|J|-r$ for all $J\subset\{1,\dots,n\},$ then there is a subfamily of size $n-r$ which has a SDR.

A: For $A\subseteq L$ let $U(A)=\{u\in U:\ell<u\text{ for some }\ell\in A\}$. Let
$$r=\max\{|A|-|U(A)|:A\subseteq L\}\;;\tag{1}$$
then $|U(A)|\ge|A|-r$ for all $A\subseteq L$, so there is an $A\subseteq L$ such that $|A|=|L|-r$, and $\{U(a):a\in A\}$ has a transversal (SDR). Let $T$ be a transversal for $\{U(a):a\in A\}$, and for each $a\in A$ let $u_a$ be the representative of $a$ in $T$. Let
$$\mathscr{C}=\big\{\{a,u_a\}:a\in A\big\}\cup(L\setminus A)\cup(U\setminus T)\;;$$
$\mathscr{C}$ is a partition of $P$ into chains. The set $L\cup(U\setminus T)$ clearly intersects each chain in $\mathscr{C}$ in exactly one point, so to complete the argument it suffices to show that this set is an antichain.
HINT: $(1)$ is the smallest possible choice of $r$, so no transversal can be larger than $T$.


text:
Q: Referencing self in Block passed to constructor I have an Objective-C object where I'm passing a Block to it's constructor. It's a special case where I want to fire that Block in a view controller when it loads completely. However, in that Block I also want to reference the object that I'm passing the Block into. Consider this example:
typedef void (^MyBlock)();

//constructor of my object
-(id)initMyObjectWithBlock:(MyBlock)block{
    self = [super init];
    if(self){
        myivar = block; //to be used later
    }
}

//somewhere else in my app
MyObject *obj = [[MyObject alloc] initMyObjectWithBlock:^{
   [obj doSomething];
}];

At that [obj doSomething] line, I am getting "Variable is uninitialized when captured by block" warning, which makes sense. In that Block, I need a reference to the "parent" object (obj in this case). Is there any way to achieve this? I do know workarounds and patterns to my specific problem, but I wanted to know if such a reference is possible.

A: typedef void (^MyBlock)(MyObject*);

//constructor of my object
-(id)initMyObjectWithBlock:(MyBlock)block{
    self = [super init];
    if(self){
        myivar = block;
    }
}

//somewhere else in app
MyObject *obj = [[MyObject alloc] initMyObjectWithBlock:^(MyObject* myObj){
   [myObj doSomething];
}];

//and somewhere else in app
obj.myivar(obj);

A: If you simply set your object to nil before creating an instance as following, it should take care of your warning.
__block TestClass *obj = nil;
obj = [[TestClass alloc] initMyObjectWithBlock:^{
    [obj doSomething];
}];

Regarding object, it does exit since you are not calling block inside your initMyObjectWithBlock initializer.
Although above code works, but as Josh mentioned, there is a retain cycle. To get around retain cycle, you can do something like:
TestClass *obj = nil;
__block __weak TestClass *objWeak = nil;

obj = [[TestClass alloc] initMyObjectWithBlock:^{
    TestClass *newObj = objWeak;

    [newObj doSomething];
}];

objWeak = obj;

Where you are simply creating a dummy variable to pass in to your block.

A: This is an addition to the answer of Cy-4AH. It was to long to put it into a comment.
First of all: Running into the "work-arounds" is a code smell. There could be two reasons for it:
A. MyObject is a symbiosis of two different task: 1. Fire, when $something happened. 2. Do something with 1) when it fired. Breaking MyObject into MyObject1 and MyObject2 could help. But of course we would need more information.
B. Very often it is a part of the concept that when one object fires, something should happen exactly to this object. (Getting more information, changing a state, …) In this case the pattern is quite easy: Pass self to the block:
From Cy-4AH:
typedef void (^MyBlock)(MyObject*);

//constructor of my object
-(id)initMyObjectWithBlock:(MyBlock)block{
    self = [super init];
    if(self){
        myivar = block;
    }
    return self; // Added this line for obvious reasons
}

//somewhere else in app
MyObject *obj = [[MyObject alloc] initMyObjectWithBlock:^(MyObject* myObj){
   [myObj doSomething];
}];

Now a little change:
Inside MyObject, when it is calling the block
self.myivar( self );

As Cy-4AH said, then you do not need all the __block __unsafe_unretained __weak trash to cover a conceptional problem.


text:
Q: jQuery issue with hoverIntent and show hide for div Hi I have a div that I show to users every time they add something to the shopping cart (it's a mini cart that's displayed on the page for 5 seconds, then dissappears).
The minicart div display is triggered by two events:

*

*HOVER: When user hovers over a container div (using hoverIntent plugin)

*CLICK: When an item is added to the cart

The code for 1 is:
// Show / Hide mini cart on hover
$('#cartWrapper').hoverIntent(function () {
   $("#cartPreviewWrapper").stop().slideDown('fast');
   },
   function () {
     $("#cartPreviewWrapper").stop().slideUp('fast');
});

The code for 2 is:
// When user clicks the add to cart button
$('#purchase').click(function() {  // div will not show fully at times when this is triggered
    // show the minicart div for 5 seconds, then hide
    $("#cartPreviewWrapper").show().delay(5000).queue(function(n) {

        // I NEED TO ADD SOME CODE HERE
        // THAT WILL MAKE THE DIV STAY / SHOW
        // IF USER HOVERS OVER IT

        $(this).hide(); n();
    });
});

The HTML:

        // cart content

One issue I am having is that when number 2 is fired the div does not display correctly.  It sort of gets stuck half way and does not extend all the way at times.  Note:  The div shows and hides with no issues with hoverIntent on all my other pages.  Just when I'm on the page where users add an item to the cart and number 2 is fired this issue comes up.
And also, does anyone know how I can make the div show if users go and hover over it when triggered by number two?
Hope this makes sense and any help greatly appreciated!

A: I guess it's the stop() method that is causing this problem, try to clear the queue:
// Show / Hide mini cart on hover
$('#cartWrapper').hoverIntent(function () {
   $("#cartPreviewWrapper").stop(true,true).slideDown('fast');
   },
   function () {
     $("#cartPreviewWrapper").stop(true,true).slideUp('fast');
});


text:
Q: Filtering an array based on presence of string value I know filter questions are covered extensivly on SO - but I'm struggling to implement my idea:
I want to filter through my panels & return an array filteredPanelTabItems for any that include the layouthint: "tab-view-item" and then the remainder of the array (without "tab-view-item") to another const so I can use it elsewhere, can anyone guide where I'm going wrong?

The screenshot above shows what's happening in the console when I log:
panel.panelLinks.links
  const hasTabItemViewHint() => {
    //check for string
  }

  const filteredPanelTabItems = panel.panelLinks.links.filter<Node>(
    (panelLink) => panelLink.(call hasTabItemViewHint function?)
  );

A: Consider something like this.
var filteredPanelTabItems = $.map(panel.panelLinks.links, function(l, i) {
  if (l.LinkModal.layouthint._collections.indexOf("tab-view-item") >= 0) {
    return l;
  }
});

See more: https://api.jquery.com/jquery.map/


text:
Q: How to customize bar annotations to not show selected values I have the following data set:
data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

Is there a way to remove the 0.0 labels from the bar plot?

I tried df = df.replace(0, "") but then I get a list index out of range error code.
My code:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

df = pd.DataFrame(np.array(data).reshape(6,5), columns=['Bank1', 'Bank2', 'Bank3', 'Bank4', 'Bank5'], index =['2016', '2017', '2018', '2019', '2020', '2021'])

print(df)
ax = df.plot(kind='bar', rot=0, xlabel='Year', ylabel='Total Return %', title='Overall Performance', figsize=(15, 10))

ax.bar_label(ax.containers[0], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[1], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[2], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[3], fmt='%.1f', fontsize=8, padding=3)
ax.bar_label(ax.containers[4], fmt='%.1f', fontsize=8, padding=3)

ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()

A: *

*labels passed to matplotlib.pyplot.bar_label must be customized

*

*Adjust the comparison (!= 0) value or range as needed.

*labels = [f'{v.get_height():0.0f}' if v.get_height() != 0 else '' for v in c ] without the assignment expression (:=).

*See this answer for additional details and examples using .bar_label

*Tested in pandas 1.3.4, python 3.8.121., and matplotlib 3.4.31.

*

*Minimum version required are 3.8 and 3.4.2 respectively

import pandas as pd
import matplotlib.pyplot as plt

data = [6.92, 1.78, 0.0, 0.0, 3.5, 8.82, 3.06, 0.0, 0.0, 5.54, -10.8, -6.03, 0.0, 0.0, -6.8, 13.69, 8.61, 9.98, 0.0, 9.42, 4.91, 3.54, 2.62, 5.65, 1.95, 8.91, 11.46, 5.31, 6.93, 6.42]

df = pd.DataFrame(np.array(data).reshape(6,5), columns=['Bank1', 'Bank2', 'Bank3', 'Bank4', 'Bank5'], index =['2016', '2017', '2018', '2019', '2020', '2021'])

ax = df.plot(kind='bar', rot=0, xlabel='Year', ylabel='Total Return %', title='Overall Performance', figsize=(15, 10))

for c in ax.containers:

    # customize the label to account for cases when there might not be a bar section
    labels = [f'{h:0.1f}' if (h := v.get_height()) != 0 else '' for v in c ]

    # set the bar label
    ax.bar_label(c, labels=labels, fontsize=8, padding=3)

ax.legend(title='Columns', bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()


text:
Q: Distributed master-worker architecture simulation design in Java I need to simulate a system in Java where there is a master and a number of workers. Each worker may process its data locally but needs to communicate the master to read data from other nodes. And workers should work concurrently.
How can I simulate this system? Do I need to start a new thread for every running worker and a master thread? Is there another way?

A: If you want to do it on a single machine then I see two options:

*

*Create a master and a worker application (make sure that you can run multiple instances of those). Run one master application and multiple instances of the worker application.

*Create a single application in which you have a single instance of your Master class and multiple instances of your Worker class. Let the Master run in a separate thread and let each Worker run in its own thread too.

So the first option is to run each "node" (master or worker) as a separate process, while the second option is to run each "node" as a separate thread.

A: This is a pretty generic question which is open to many architectural solutions. I'd like to present the one I've used in the past. I used RMI here for ease of remote calls.
All master and slave processes are RMI services. Both master and slaves are spawned using the RMI daemon (RMID) which have the bonus feature of "upping" the services in case one goes down due to a JVM crash or any other "abnormal" reason. RMI services in general work based on an interface which defines the contract between the client and the server. Let's say for e.g. that I have to write a service which solves an equation.
We start off with creating two services: master and slave. Both these services implement/expose the same interface to the client. The only difference would be that the "master" service would be solely responsible for "forking" across work to the different slave agents, getting the response back (or re-arranging them if required) and returning it to the client. The master is a simple RMI service which accepts the list of "equations" and splits them across the different clients. Obviously, the master here has references to all the clients it governs in terms of RMI handle (i.e. communication between master and slaves is again a RMI invocation).
Here again, we have a lot of possibilities of configuring how master "looks up" the slaves but I'm sure you can work it out quite easily. This architecture has the advantage of a grid based solution wherein you are not limited by a single process to do all the work for you and hence gain the resiliency and freedom from monolithic heap sizes for your JVM process.
I really haven't used them but Rio and JINI is something you should look into if you want to build distributed systems in Java.


text:
Q: Can animate each state of `AnimatedStateListDrawableCompat` is it possible to animate each state of <animated-selector>?
for example, in this part of code, I want active state also animate (I know that transition can animate between states but I want each state animate too, no matter whether programmatically or by XML).
in this case assume that animatable_src1 is an animatable vector drawable
<animated-selector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/middle"
    android:drawable="@drawable/animatable_src1"
    android:state_activated="true" />

<item
    android:id="@+id/done"
    android:drawable="@drawable/simple_drawable" />

<transition
    android:drawable="@drawable/anim_done_to_middle"
    android:fromId="@+id/done"
    android:toId="@+id/middle" />

<transition
    android:drawable="@drawable/anim_middle_to_done"
    android:fromId="@+id/middle"
    android:toId="@+id/done" />

</animated-selector>

If this is not possible, can I get drawable of specific state as AnimatedVectorDrawableCompat? (Then I can animate it)


text:
Q: Can't find the mistake I'm making in the proof of triangle inequality I've produced the following proof of the triangle inequality:
$|a+b| \leq |a| + |b|$
$\iff \sqrt{(a+b)^2} \leq \sqrt{(a)^2} + \sqrt{(b)^2}$
$\iff (a+b)^2 \leq a^2 + 2\sqrt{(ab)^2}+b^2$ (we squared both sides)
$\iff a^2 + 2ab + b^2 \leq a^2 + 2\sqrt{(ab)^2}+b^2$ (just developping LHS)
$\iff ab \leq \sqrt{(ab)^2}$ (simplified expression)
$\iff (ab)^2 \leq (ab)^2$ (squared both sides)
Therefore, since the last statement is a tautology, using the transitivity of the logical biconditional, the statement at the beginning of the biconditional chain is also a tautology, proving the theorem.
I've been told there's a mistake in my proof, but I've been meditating on it for some time now and I have no clue where I've gone wrong. Would someone have any hints on the mistake I'm making?
Thank you very much!

A: For real quantities, the true equivalence is $$X\le \sqrt Y\Leftrightarrow (X< 0\land Y\ge 0)\lor (X\ge 0\land X^2\le Y)$$ This comes into play when you assert that $$ab\le \sqrt{(ab)^2}\Leftrightarrow (ab)^2\le (ab)^2$$
instead of $$ab\le \sqrt{(ab)^2}\Leftrightarrow ab<0\lor ((ab)^2\le (ab)^2\land ab\ge 0)$$
This is of course a simple tautology, but a different one.

A: Here it is another way to approach it:
\begin{align*}
|ab| \geq ab & \Longleftrightarrow 2|a||b| \geq 2ab\\\\
& \Longleftrightarrow |a|^{2} + 2|a||b| + |b|^{2} \geq a^{2} + 2ab + b^{2}\\\\
& \Longleftrightarrow (|a| + |b|)^{2} \geq (a+b)^{2}\\\\
& \Longleftrightarrow |a| + |b| \geq \sqrt{(a+b)^{2}}\\\\
& \Longleftrightarrow |a| + |b| \geq |a + b|
\end{align*}
Hopefully this helps!

A: Yet another way to show it ...
First note that:

*

*$x\leq|x|$,

*$-x\leq|x|$,

*if $x\leq u$ and $y\leq v$ then $x+y\leq u+v$,

*$|x|=\max(x,-x)$,

*if $x\leq u$ and $y\leq u$ then $\max(x,y)\leq u$.

By 1 and 3 we have $a+b \leq |a|+|b|$. By 2 and 3 we have $-(a+b) = -a-b \leq |a|+|b|$. So finally, by 4 and 5 we get $|a+b|=\max(a+b,-(a+b)) \leq |a|+|b|.$


text:
Q: Creating a SharePoint Quiz OOTB I am trying to create a quiz that users can take in SharePoint to test their knowledge. I can do this by creating a custom list with calculated fields to work out whether they have passed or not.
This is fine but the issue comes in making sure that users cannot see other user's completed quizzes too. I see you can tick the option of 'Read items that were created by the user'. How can I make sure then that I can see all items created by all users in this list?
I am new to SharePoint so any help would be great.
Thanks in advance

A: What you're doing is setting item-level permissions. Options such as "Read items that were created by the user" and "Create items and edit items that were created by the user" only apply to users with Contribute or Edit permissions. They do not apply to users with at least Design permissions.
So, to see all items created by all users in this list, make yourself a Designer or an Admin.


text:
Q: PostgreSQL database dump: makes it sense to grant all privileges on user backup? I want to make a database backup of a postgresql database.
I did this on my existing database:
sudo -u postgres psql oder psql -U postgres
CREATE USER backup;
ALTER USER backup WITH PASSWORD 'new_password';
GRANT CONNECT ON DATABASE confluence TO backup;
GRANT CONNECT ON DATABASE taiga TO backup;
GRANT USAGE ON SCHEMA public TO backup;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup;

ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO backup;

If I run pg_dump -Fc confluence > dumpfile I get
pg_dump: [archiver (db)] query failed: ERROR:  permission denied for relation EVENTS
pg_dump: [archiver (db)] query was: LOCK TABLE public."EVENTS" IN ACCESS SHARE MODE

In Permission denied for relation I read that this would help:
GRANT ALL PRIVILEGES ON TABLE confluence TO backup;

I wonder if it is the rigth way to give all privileges to a backup user who shall not have the permissions to write the database. I want it to be a read only user.
Is this a nonsense requirement?
What do you suggest me to do instead?

A: In addition to grant CONNECT permission on the database and SELECT permission on all tables (in the public schema), you also need to grant select on all sequences (in the public schema).
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO <user>

to to summarize:
--Create user
CREATE USER backup;
ALTER USER backup WITH PASSWORD 'new_password';

--Grant read only privileges
GRANT CONNECT ON DATABASE <database> TO backup;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO backup;
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO backup;  -- new!

--Automatically grant read only privileges on new tables
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO backup;


text:
Q: NavBar should scroll up again when clicking twice on the same link

@import "../../colors.scss";
@import "../../responsive.scss";

.navbar-container {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 2rem 4rem;
    position: fixed;
    width: 100%;
    max-width: 100vw;
    top: 0;
    left: 0;
    background-color: $white;
    z-index: 100;
    height: 5rem;
    font-family: Montserrat;
    transition: all 0.3s;

    @include responsive(mobile) {
        padding: 0.8rem 2rem;
        height: 5rem;
    }

    &,
    & * {
        box-sizing: border-box;
    }

    .left-side {
        display: flex;
        align-items: center;

        .logo {
            font-family: "Pacifico", cursive;
            font-size: 1.8rem;
            font-weight: 400;
            color: rgba($black-text, 0.8);
            margin-top: -1rem;

            @include responsive(mobile) {
                margin-top: -0.3rem;
            }
        }

        .links {
            @include responsive(desktop-small) {
                display: none;
            }

            margin-left: 4rem;
            display: flex;

            a {
                margin: 0 2rem;

                @include responsive(desktop-small) {
                    margin: 0 1.5rem;
                }

                &:hover {
                    color: $blue;
                }
            }

            .active {
                color: $blue;
            }
        }
    }

    .right-side {
        .auth {
            display: flex;
            align-items: center;

            .logout {
                margin-right: 2rem;
                cursor: pointer;
                color: $blue;

                &:hover {
                    color: $red;
                }
            }
        }

        @include responsive(desktop-small) {
            display: none;
        }
    }

    // ----------mobile-------------------
    .mobile-right-side {
        display: none;

        @include responsive(desktop-small) {
            display: flex;
            align-items: center;
        }

        .background {
            position: absolute;
            transform-origin: top;
            transition: all 0.2s ease-out;
            top: 5rem;
            right: 0;
            background-color: $white;
            display: flex;
            justify-content: center;
            align-items: flex-start;
            width: 100vw;
            height: 100vh;
            border-radius: 0;
        }

        .opened {
            .background {
                transform: scaleY(1);
                opacity: 1;
            }

            .hamburger {
                div {
                    width: 1.9rem !important;
                }
            }
        }

        .closed {
            .background {
                transform: scaleY(0);
                opacity: 0;
            }
        }

        .nav-dropdown {
            // padding: 1.2rem;
            display: flex;
            flex-direction: column;
            justify-content: space-evenly;
            text-align: center;
            width: 100%;
            align-items: center;

            &>* {
                cursor: pointer;
                margin: 0.8rem;
            }

            .active {
                color: $blue;
            }

            .register-btn {
                width: 100%;
                background-color: $blue;
                color: $white;
                padding: 1.5rem;
            }

            .underline {
                width: 100%;
                height: 1px;
                margin-left: auto;
                margin-right: auto;
                border: 1px solid rgba($black, 0.1);
            }
        }

        .hamburger {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            justify-content: center;
            margin-left: 2rem;
            cursor: pointer;

            @include responsive(mobile) {
                margin-left: 1rem;
            }

            div {
                width: 1.9rem;
                height: 0.15rem;
                background-color: rgba($black, 0.5);
                transition: all 0.1s ease-out;
            }

            &>div:nth-child(2) {
                margin: 0.25rem 0;
            }

            &>div:nth-child(1) {
                width: 1.55rem;
            }

            &>div:nth-child(3) {
                width: 1.3rem;
            }

            &:hover {
                @include responsive(desktop-small) {
                    div {
                        width: 1.9rem;
                    }
                }

                @include responsive(mobile) {
                    &>div:nth-child(1) {
                        width: 1.55rem;
                    }

                    &>div:nth-child(3) {
                        width: 1.3rem;
                    }
                }
            }
        }
    }
}

import React, { useState, Fragment } from "react";
import { NavLink, useHistory } from "react-router-dom";

export default ({ toggleRegister, auth, logout }) => {
    const [showDropDown, toggleDropDown] = useState(false);
    const history = useHistory();

    return (
        <div
            className={`nav-dropdown-wrapper ${showDropDown ? "opened" : "closed"}`}
            onClick={() => toggleDropDown((prev) => !prev)}
        >

                    {auth ? (
                        <Fragment>

 history.push("dashboard")}
                            >
                                Dashboard

Log Out

                        </Fragment>
                    ) : (
                        <Fragment>

 toggleRegister("register")}
                            >
                                Create Free Account

 toggleRegister("login")}>Sign In

                        </Fragment>
                    )}

                    <NavLink to="/features">Features</NavLink>

                    <NavLink to="/blogs">Blogs</NavLink>

                    Docs

                    <NavLink to="/pricing">Pricing</NavLink>

                    <NavLink to="/support">Support</NavLink>

    );
};

When I click on the link of my NavBar the page scroll up, but when I'm on the page and click again on the link the page is not scrolling up anymore.
for example, if we are on /contact and we click contact again in navbar or footer, then the screen should scroll up. Do I need to use css to do that?
I search everywhere on google, but could not find anyway how to do that. Any help would be welcome.


text:
Q: Complete Segal operads and dendroidal sets There is a Quillen equivalence between the model category presenting Lurie's $\infty$-operads (which are inner fibrations $\mathcal{C}\to\mathrm{N}(\mathbf{F})$ satisfying certain conditions) and the model category of dendroidal sets. On the other hand, in his paper on operator categories and topological operads (http://arxiv.org/abs/1302.5756), Barwick proves that there is an equivalence of $\infty$-categories between complete Segal $\Phi$-operads and $\infty$-operads over $\Phi$ for a perfect operator category $\Phi$.
This provides a zig-zag of Quillen equivalences between Barwick's complete Segal $\Phi$-operads and dendroidal sets when $\Phi$ is the perfect operator category $\mathbf{F}$. Is there a direct construction of a Quillen equivalence between these two models (namely, complete Segal operads and dendroidal sets) for $\infty$-operads?


text:
Q: get more than 10 documents from firestore in one round trip using Flutter I am currently using whereIn for this. But only get 10 or less douments at once. whereIn 10 entries or less according to the firestore documentation
Is there any way to get more than 10 documents at once in one round trip?
 return _db
        .collection('books')
        .where('docId', whereIn: ['id1', 'id2'...'id10'])
        .get()
        .then((value) => value.docs.map((e) => BookModel.fromFireStore(e)).toList());

A: No, 10 is a hard limit and can't be exceeded.  You will need to perform multiple queries to get more than 10 documents by ID. The documentation states:

Use the in operator to combine up to 10 equality (==) clauses on the same field with a logical OR.

A: The question has been answered. Here I just want to show how you can get those documents with multiple round-trips cause it is not an easy task as well. It took me some time to implement this, so I hope it will save someone else's time.
First create a function for one round-trip:
Future<List<Book>> _getBooksByIds(ids) {
  return _instance
      .collection('books')
      .where(FieldPath.documentId, whereIn: ids)
      .get()
      .then((QuerySnapshot snapshot) {
    return snapshot.docs.map((DocumentSnapshot doc) => BookModel.fromSnapshot(doc)).toList();
  });
}

Then split by 10 your ids
ids = ['id1', 'id2'...'id11'];
final idsBy10 = [
  for (var i = 0; i < ids.length; i += 10)
    ids.sublist(i, min(i + 10, ids.length))
];

Then run multiple requests and merge their results:
Future.wait<List<Book>>(idsBy10.map((ids) => _getBooksByIds(ids)))
        .then((listOfLists) => listOfLists.expand((l) => l).toList());


text:
Q: NotFoundHttpException when editing an object I have tournament > category > setting, and I need to edit the settings.
For the creation ( http://laravel.dev:8000/tournaments/1/categories/5/settings/create
) , I have no problem, only updating is failing ( http://laravel.dev:8000/tournaments/1/categories/2/settings/5/edit )
I checked the params (1,2,5), and they are OK.
I use my route with resource()
        Route::resource('tournaments/{tournamentId}/categories/{categoryId}/settings', 'CategorySettingsController');

When I type php artisan route:list, I get this route:
GET|HEAD | tournaments/{tournamentId}/categories/{categoryId}/settings/{settings}/edit | tournaments.{tournamentId}.categories.{categoryId}.settings.edit    | App\Http\Controllers\CategorySettingsController@edit           | auth,roles |

So, as for me, everything should be OK, I don't understand why I get a NotFoundHttpException
Any idea????

A: in RouteServiceProvider.php, I had binding defined:
        $router->model('settings','App\Settings');

So General settings bindings was conflicting with Category Settings


text:
Q: SeekBar с отрицательным значением Android Studio Могу ли я каким-то образом получить ползунок с диапазоном значений, допустим, от -100 до 100? На самом деле, могу, находил пару постов на форумах, но довольно стареньких. Может что-то актуальнее уже есть. И, собственно, самый главный вопрос после этого. Могу ли я сделать, чтобы шкала прогресса заполнялась в обе стороны?
Если что, рисовал в пейнте, не судите))

A: Нашел на забугорном stackoverflow, понравился второй ответ, сделал так же, работает отлично. да и с кастомизацией можно побаловаться.
клик


text:
Q: Exclude files in Jacoco Coverage Report I have been trying to remove certain files from the generated coverage report. I tried below things:
<plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.8.1</version>
            <executions>
                <execution>
                    <id>report-aggregate</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>report-aggregate</goal>
                    </goals>
                    <configuration>
                        <excludes>
                            <exclude>**/com/abc/def/**</exclude>
                        </excludes>
                    </configuration>
                </execution>
                <execution>
                    <id>check</id>
                    <goals>
                        <goal>check</goal>
                    </goals>
                    <configuration>
                        <rules>
                            <rule >
                                <element>BUNDLE</element>
                                    <limits>
                                        <limit >
                                            <counter>LINE</counter>
                                            <value>COVEREDRATIO</value>
                                            <minimum>0.50</minimum>
                                        </limit>
                                    </limits>
                            </rule>
                        </rules>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Modified code:
<plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.9</version>
            <configuration>
                <excludes>
                    <exclude>**/com/abc/def/**</exclude>
                </excludes>
            </configuration>
            <executions>
                <execution>
                    <id>report-aggregate</id>
                    <phase>verify</phase>
                    <goals>
                        <goal>report-aggregate</goal>
                    </goals>
                </execution>
                <execution>
                    <id>check</id>
                    <goals>
                        <goal>check</goal>
                    </goals>
                    <configuration>
                        <rules>
                            <rule >
                                <element>BUNDLE</element>
                                    <limits>
                                        <limit >
                                            <counter>LINE</counter>
                                            <value>COVEREDRATIO</value>
                                            <minimum>0.50</minimum>
                                        </limit>
                                    </limits>
                            </rule>
                        </rules>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Also tried,
<configuration>
                        <rules>
                            <rule >
                                <element>BUNDLE</element>
                                    <limits>
                                        <limit >
                                            <counter>LINE</counter>
                                            <value>COVEREDRATIO</value>
                                            <minimum>0.50</minimum>
                                        </limit>
                                    </limits>
                                <excludes>
                                    <exclude>com.abc.def.className</exclude>
                                </excludes>
                            </rule>
                        </rules>
                    </configuration>

Some of the many links I referred while trying to reach the solution:
Maven Jacoco Configuration - Exclude classes/packages from report not working
Jacoco how to correctly exclude package
How to add more Jacoco exclusions in a child project?
http://tdongsi.github.io/blog/2017/09/23/jacoco-in-maven-project/
But every time I generate the report, the files still show up in the given module.

A: After also being stuck at this for hours, here's what I did:
<configuration>
     <excludes>
          <exclude>com/package/name/FileName*</exclude>
     </excludes>
</configuration>

Adding * after filename was the critical part for me. I had tried putting FileName.java several times but it would still include it util I added *


text:
Q: xmlns="something" - must be in parent nod I have a problem. Can't name XAttribute like this: XAttribute("xmlns", nss.NamespaceName)
XNamespace ns = "urn:hl7-org:v3";
XNamespace nsVoc = "urn:hl7-org:v3/voc";
 new XElement("ClinicalDocument",
              new XAttribute(XNamespace.Xmlns + "xsi", xsiNs.NamespaceName),
              new XAttribute("xmlns", nss.NamespaceName),
              new XAttribute(XNamespace.Xmlns + "voc", nsVoc.NamespaceName),
              new XAttribute(xsiNs + "schemaLocation", ns.NamespaceName + "../Schemas/cda/Schemas/CDA.xsd"),
 new XElement("typeId",
              new XAttribute("root", rootTypeId),
              new XAttribute("extension", extensionTypeId)),
 new XElement("templateId",
              new XAttribute("root", rootTemplateId)),
              new XElement("templateId",
              new XAttribute("root", rootTemplatedId)),

.
.
.
i dont close this parent nod here.. I have 2000 lines betwean end nod
THE MESSAGE IS: The prefix '' cannot be redefined from '' to 'urn:hl7-org:v3' within the same start element tag.

A: Instead of
new XElement("ClinicalDocument",
              new XAttribute(XNamespace.Xmlns + "xsi", xsiNs.NamespaceName),
              new XAttribute("xmlns", nss.NamespaceName),

you need
XNamespace df = nss.NamespaceName;
new XElement(df + "ClinicalDocument",
  new XAttribute(XNamespace.Xmlns + "xsi", xsiNs.NamespaceName),
              new XAttribute(XNamespace.Xmlns + "voc", nsVoc.NamespaceName),
              new XAttribute(xsiNs + "schemaLocation", ns.NamespaceName + "../Schemas/cda/Schemas/CDA.xsd"),
 new XElement(df + "typeId",

so you need to make sure you create an XNamespace for that default namespace and then your code needs to make sure the new XElement() calls use e.g new XElement(df + "foo") to create the element in the right namespace.


text:
Q: Audio encoding on Android Wear With the help of the AudioRecord API I am now able to record audio using the microphone of the watch. However, this is uncompressed audio and the file sizes get pretty big.
Around 5.3MB per minute recording at 16bit, 44.1Khz, mono. So I started looking into reducing the size by encoding it to a different format.
I looked into MediaCodec and the other low level audio multimedia support that is mentioned.
Looping over the available codecs:
MediaCodecList codecs = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
MediaCodecInfo[] infos = codecs.getCodecInfos();
for(MediaCodecInfo info : infos) {
  Log.d(TAG, "Name: " + info.getName());
  Log.d(TAG, "Types: " + Arrays.toString(info.getSupportedTypes()));
  Log.d(TAG, "Encoder? " + info.isEncoder());
}

It turns out that none of them are encoders. Just 9 decoders. Attempting to use any of these in MediaCodec.createByCodecName() results in an exception. Any idea how I can compress my recorded audio on Android Wear?


text:
Q: PHP returning part of the code document I have a PHP page that does a couple of different things depending on what action is set to in the GET data. Depending, it is supposed to return some JSON, but instead of doing anything it is supposed to it returns the bottom half of the code document itself, starting in the middle of the line. Heres the snippit from where it starts:
...
} elseif ($_GET['action'] == 'addtop') {
    if (!isset($_GET['pname']) || !isset($_GET['url']) || !isset($_GET['artist']) || !isset($_GET['album']) || !isset($_GET['file'])) {
        die('Error: Incomplete data!');
    }
    if (!file_exists($_GET['pname'].".txt")) {
        die('Error: No such playlist!');
    }
    $plist = json_decode(file_get_contents($_GET['pname'].".txt"), true);
    $fh = fopen($_GET['pname'].".txt", 'w') or die('Could not open playlist!');
    array_push($plist, array("artist" => $_GET['artist'], "album" => $_GET['album'], "file" => $_GET['file'], "url" => $_GET['url']));
    fwrite($fh,json_encode($plist));
} elseif ($_GET['action'] == 'delfromp') {
...

And here is what I get when I go to the page:

$_GET['artist'], "album" =>
  $_GET['album'], "file" =>
  $_GET['file'], "url" =>
  $_GET['url']));
  fwrite($fh,json_encode($plist)); }
  elseif ($_GET['action'] == 'delfromp')
  { if (!isset($_GET['pname']) ||
  !isset($_GET['id'])) { die('Error:
  Incomplete data!'); } if
  (!file_exists($_GET['pname'].".txt"))
  { die('Error: No such playlist!'); }
  $plist =
  json_decode(file_get_contents($_GET['pname'].".txt"),
  true); $fh =
  fopen($_GET['pname'].".txt", 'w') or
  die('Could not open playlist!');
  unset($plist[$_GET['id']]); $plist =
  array_values($plist);
  fwrite($fh,json_encode($plist)); }
  elseif ($_GET['action'] == 'readp') {
  if
  (!file_exists($_GET['pname'].".txt"))
  { die('Error: No such playlist!'); }
  $plist =
  json_decode(file_get_contents($_GET['pname'].".txt"),
  true); $arr = array("entries" =>
  $plist); $json = json_encode($arr);
  echo $json; } elseif ($_GET['action']
  == 'getps') { $plists = array(); if ($handle = opendir('Playlists')) {
  while (false !== ($playlist =
  readdir($handle))) { if ($playlist !=
  "." && $playlist != "..") {
  array_push($plists, substr($playlist,
  0, strripos($playlist, '.')-1)); } } }
  else { die('Error: Can\'T open
  playlists!'); } $arr =
  array("entries"=>$plists); $json =
  json_encode($arr); echo $json; } else
  { die('Error: No such action!'); } ?>

It starts in the middle of the array_push(... line.
I really can't think of what it is doing. Theres no echos anywhere around it. Any ideas?

A: Looks like => is closing your PHP code.  Do you have short tags enabled?  Or some sort of custom tags?


text:
Q: Horizontal CSS - Input Field 100% and Margin for button Task: Make text box 100% width but allow enough room for button.
Problem: Button appears on next line and text box exceeds width of its container.

    <input type="text" name="my-field" />
    <input type="button" id="my-button" value="Add +" />

 .field {
     margin-right: -70px;
     width: 100%;
 }
 .field input[type=text] {
     display: block;
     float: left;
     margin-right: 70px;
 }
 .field input[type=button] {
     display: block;
     float: right;
 }

My primary layout uses the following trick to achieve flexible width with fixed sidebar, but for some reason this is not working on the above.

        ...

        ...

 .outer-wrap {
     margin-right: -300px;
     width: 100%;
 }
 .content {
     float: left;
     margin-right: 300px;
 }
 .sidebar {
     float: right;
 }

What mistake am I making here?

A: You have to screw with the HTML a bit, but otherwise this works perfectly in IE7+ and all modern browsers.
See: http://jsfiddle.net/thirtydot/25bZC/
CSS:
.field > span {
    display: block;
    overflow: hidden;
    padding-right: 10px
}
.field input[type=text] {
    width: 100%
}
.field input[type=button] {
    float: right
}

HTML:

    <input type="button" id="my-button" value="Add +" />
    <input type="text" name="my-field" />

A: To pull this off you must ensure that the element which you are floating right comes before the one floating left. Like this

    <input type="button" id="my-button" value="Add +" />
    <input type="text" name="my-field" />

A: try giving fixed width to
field input[type=text]

and
.field input[type=button]


text:
Q: Inject GET parameter to target URL of a button, on click I have multiple buttons with the class myButton. Each button has a value which is send to a server on click. The target URL of the button does look like this:
http://mysite/test/test.html?cid=15

After I click on the button, the following GET parameter should be added to the URL and then the button should be submitted:
mySessionVar=1

So the new URL should look like this:
http://mysite/test/test.html?cHash=d009eb3f9f4e1020435b96a8f7251ad5&mySessionVar=1

Why I have to inject it?
I am working with fluid. AFAIK it is not possible to manipulate fluid tags with JavaScript. However, I need to add a sessionStorage item value to the fluid tags arguments attribute.
My fluid code:
<f:link.action controller="Download" action="download" arguments="{cid: category.uid}" class="myButton">Download</f:link.action>

So my attempt is to append my sessionStorage item as GET parameter to the target URL of the button and then send it, e.g.:
$(".myButton").on
(
  "click",
  function(event)
  {
      //First prevent the default event
      event.preventDefault();

    ...inject the sessionStorage item as GET parameter to the target URL of the button, then do whatever the button would do normally...

      //Go to new URL
      window.location.replace(NEW URL);
  }
);

Is this possible?
EDIT: This is how the rendered HTML of the buttons looks like:
Download

EDIT: I have another idea, maybe I could just read the target URL somehow, then add my new GET param to it and then load that URL with window.location.replace?

A: You can indeed just use the href from the button and use it to feed window.location.href, like so:
$('.myButton').on('click', function(e) {

    e.preventDefault();

    var href = $(this).attr('href'),
        queryString = 'mySessionVar='+sessionStorage.getItem("myItem"),
        newHref;

    if (href.indexOf('?') !== -1) {

        newHref = href + '&' + queryString;

    } else {

        newHref = href + '?' + queryString;
    }

    window.location.href = newHref;
});

This also handles the case when there is no previous query string present on the link and appends it with ? instead of &, but that part can be omitted if that won't happen in your app.

A: The following snippet should be enough to add your mySessionVar=1 parameter to the href attribute:
$('.myButton').on('click', function(e) {
    $(this).attr('href', $(this).attr('href') + "&mySessionVar="+ sessionStorage.getItem('myVar');
});

You don't have to prevent the default, because your click handler function is called before the default event handler (who does roughly speaking: read the href attribute and load it).

A: You can use .serialize function in jquery which is simple and modern function to get all the selected buttons/filters into a url param format with amberson simple. I can't explain more clear than what is said in Jquery website. Please refer the link below  to find how to use the function. https://api.jquery.com/serialize/#serialize


text:
Q: How to add jar files while spinning up AWS EMR? I have a jar maven dependency 'org.mongodb:mongo-java-driver:3.12.11' exclude io.netty:*  which is not present in the spark and zeppelin jars files by default. I right now use Uber jar (shade plugin) for running on spark and update the zeppelin configuration every-time I spin up a new EMR.
Is there anyway to do it directly through a EMR bootstrap step or altering the spark and zeppelin configuration. Where I can just add something like a pom file which have this mongo dependency with exclude io.netty:*. So, I can just directly run the spark jars without creating a Uber jar.


text:
Q: Shifting and adding cells with Excel Macros and VBA I am new to writing Excel Macros and I was wondering what is wrong with my code, I keep getting an object value error.
What the code is supposed to do is break up data into columns that have spaces in between and then add the left and top left values into new cells. For Example:
Starting Data
1    2
2    4
3    5
4    6
5    7
6    8
7    9

After Macro Data
(Making New Columns)
1        2
2        4
3        5
4        6
5        7
6        8
7        9

(Finished Product)
1    1+0 = 1     2    2
2    1+2 = 3     4    6
3    2+3 = 5     5    9
4    7           6    11
5    9           7    13
6    11          8    15
7    13          9    17

Code:
Sub shift_and_add()

    For i = 1 To Selection.height

        'Easier to start shifting cell by cell to the right'
        For j = Selection.width To 1 Step (-1)

           'Offset each cell by 1'
            Cells(i, j).Offset(0, 1).Insert Shift:=xlToRight

            'add the left and top left values from the cell'
            v = v + x.Offset(0, -1).Value + x.Offset(-1, -1).Value

            'update the cell value'
            Cells(i, j).Value = v
        Next j
    Next i
End Sub

A: Yes, x does not exist but the v = v... line is trying to use x's address.
I've done a very dirty example of some code that might work for you. I've assumed your data starts in cell A1, however you can change this very easily in this code by simply adjusting theColumn and theRow values near the top (e.g. if your data starts in cell D10 then theColumn = 4, theRow = 10).
Sub shift_and_add_2()

Dim values As Range

'set starting column and starting row:
theColumn = 1
theRow = 1

Do 'loop for each original column of data:
    'reset iteration requirement:
    theNewCol = 0

    'get the next column of data, based on a) your starting column and row and then b) subsequent columns found later on:
    Set values = Range(Cells(theRow, theColumn).Address, Range(Cells(theRow, theColumn).Address).End(xlDown))

    If values.Height > 99999 Then 'perhaps only one value, so we'll curtail the range:
        Set values = Range(Cells(theRow, theColumn).Address)
    End If

    x = 0
    For Each cell In values
        If x = 0 Then 'is the first row, we'll check for subsequent columns:
            'if we find a subsequent column, we'll first insert a new column before doing sums:
            If cell(1, 2).Value <> "" Then
                cell(1, 2).EntireColumn.Insert
                'and the REQUIREMENT for another iteration of this loop is switched "on":
                theNewCol = 1
                'and the next data column address is established:
                theColumn = theColumn + 2
            End If
            'here we do the actual sum, and colour the result:
            cell(1, 2).Value = cell.Value
            cell(1, 2).Interior.ColorIndex = 45
            x = 1
        Else 'was not the first row, so we didn't need to check for subsequent columns,
                'AND our sum is a little different:
            cell(1, 2).Value = (cell.Value + cell(0, 1).Value)
            cell(1, 2).Interior.ColorIndex = 45
        End If
    Next

    'If there's no requirement for another iteration (i.e. we found no further data columns) then exit:
    If theNewCol = 0 Then Exit Do
Loop

End Sub

A: Try this code

Sub D()
Dim rng As Range
Dim i As Integer
Dim j As Integer
i = 2
j = 1
Set rng = Range(Cells(1, 1).Address, Cells(1, 1).End(xlDown).Address)
Cells(1, 2).EntireColumn.Insert
For Each dng In rng
D = Cells(1, 2).Value
If D = "" Then
Cells(1, 2).Value = Cells(1, 2).Offset(0, -1).Value
Else
Cells(i, 2).Value = dng.Value + Cells(j, 1).Value
i = i + 1
j = j + 1
End If
Next dng
End Sub


text:
Q: Why wont my if statements work? Hi my if statements wont work here is my code please help?
case WM_COMMAND:
  {

    if (LOWORD(wParam) == 3); {

      std::exit(EXIT_FAILURE);
    }
    break;

    if (LOWORD(wParam) == 1); {

      system("test.txt");

    }

    break;
  }

i just don't get it!

A: Control structers govern either the next bracket, or everything to the next semikolon. What you wrote is interpreted as:
//This is a really short if, but okay
if (LOWORD(wParam) == 3);

//this is just a bracket that has nothing to do with the if that was already finished.
{

      std::exit(EXIT_FAILURE);
    }

A: Oh i fixed it here is my code:
        case WM_COMMAND: {

    if (LOWORD(wParam) == 3) {
    std::exit(EXIT_FAILURE);
    }

    if (LOWORD(wParam) == 1) {
    system ("test.txt");
    }

    break;
    }


text:
Q: jQuery global load page issue I'm trying to create a global page, which would just change content instead of completely loading a new page.
When i try to call the loadPage function on the home.php page it just tells me the loadPage function isn't defined.
The problem is i think, that the function has to be re-created when the new content is loaded...
Global page code(HTML):

<link type="text/css" rel="stylesheet" href="css/style-loading.css">

<!doctype html>

Page loading code(JS):
//Copyright © 2016 Dynavio Cooperative
var currentPage = null;
$(document).ready(function()
{
    loadPage();
});
function loadPage(pageToLoad)
{
    $(".loading-img").removeAttr("style");
    if(typeof pageToLoad == "undefined")
    {
        if(currentPage == null)
        {
            $("html").load("pages/home.php", function()
            {
                $(".loading-img").css("display", "none");
            });
        }
    }
    else
    {
        $("html").load(pageToLoad, function()
        {
                $(".loading-img").css("display", "none");
        });
    }
}

home.php code(HTML):

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Dynavio">
<meta name="keywords" content="Dynavio,Cooperative,Administration">
<meta name="author" content="Dynavio Cooperative">
<title>Dynavio - Homepage</title>

<link type="text/css" rel="stylesheet" href="css/plugins/font-awesome-4.6.1/css/font-awesome.min.css">
<link type="text/css" rel="stylesheet" href="css/style-main-global.css">
<link type="text/css" rel="stylesheet" href="css/style-fonts.css">
<link type="text/css" rel="stylesheet" href="css/style-navbar.css">
<link type="text/css" rel="stylesheet" href="css/style-slider.css">

Homepage

Products

Company

Research

Contact

Login

A: There is a problem in your HTML. I know that that code was only a part of your code but doctype definition should always be in the first line.
Then, I can not see  tag open. I hope that it is on other part of your code.

A: Turns out the problem was because function names are case-sensitive...


text:
Q: Running a complex command line in python I would like to call a complex command line in Python and capture its output, and I don't understand how I should be doing it:
Command line that I'm trying to run is:
cat codegen_query_output.json | jq -r '.[0].code' | echoprint-inverted-query index.bin

As far as I got is:
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print out

but this is a simple ls -a ([cmd, args]) any idea how should I run/structure my complex command line call?

A: The cleanest way is to create 2 subprocesses piped together. You don't need a subprocess for the cat command, just pass an opened file handle:
import subprocess

with open("codegen_query_output.json") as input_stream:
    jqp = subprocess.Popen(["jq","-r",'.[0].code'],stdin=input_stream,stdout=subprocess.PIPE)
    ep = subprocess.Popen(["echoprint-inverted-query","index.bin"],stdin=jqp.stdout,stdout=subprocess.PIPE)
    output = ep.stdout.read()
    return_code = ep.wait() or jqp.wait()

The jqp process takes the file contents as input. Its output is passed to ep input.
In the end we read output from ep to get the final result. The return_code is a combination of both return codes. If something goes wrong, it's different from 0 (more detailed return code info would be to test separately of course)
Standard error isn't considered here. It will be displayed to the console, unless stderr=subprocess.STDOUT is set (to merge with piped output)
This method doesn't require a shell or shell=True, it's then more portable and secure.

A: It takes a shell to interpret operators like |.  You can ask Python to run a shell, and pass your command as the thing to execute:
cmd = "cat test.py | tail -n3"
process = subprocess.Popen(['bash', '-c', cmd], stdout=subprocess.PIPE)
out, err = process.communicate()
print out


text:
Q: 400 bad request when accessing server via https Im using Portainer to run Atlassian Jira instances. I would like to be able to access each container via tpg.xyz/containerName (in this case jira). Currently I have this working with the exception of it throwing an error of 400 Bad Request - The plain HTTP request was sent to HTTP Port.
This happens when I input the url https://tpg.xyz/jira, it is then changed to tpg.xyz:443/jira. If I then add https:// to the beginning of the url It will take me to the homepage of jira. however each time I navigate to a new page the https:// is removed from the url and I am met with the same error 400.
Any ideas what ive missed?
Edit: realised the config had my domain in it so I may aswell add it to the question just in case someone poking around could help.
Heres my Nginx config

server {
  server_name docker.tpg.xyz tpg.xyz www.tpg.xyz; # managed by Certbot

    location / {
        proxy_set_header Host $host;
        proxy_pass http://127.0.0.1:9000;
        proxy_redirect off;
    }

    location /jira{
           proxy_pass            http://127.0.0.1:8081/jira;
           proxy_read_timeout    300;
          proxy_connect_timeout 300;
           proxy_redirect        off;
           proxy_set_header      X-Forwarded-Host $host;
           proxy_set_header      X-Forwarded-Server $host;
           proxy_set_header      X-Real-IP $remote_addr;
           proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
 }

        listen 443 ssl http2 default_server;
    listen [::]:443 ssl http2 default_server; # managed by Certbot
  #  listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/tpg.xyz/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/tpg.xyz/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}

server {
    if ($host = docker.tpg.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = www.tpg.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    if ($host = tpg.xyz) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80 ;
    listen [::]:80 ;
    server_name docker.tpg.xyz tpg.xyz www.tpg.xyz;
    return 404; # managed by Certbot

}

A: Turns out that I had set an env variable wrong because I hadn't initially planned to use https when setting up the jira instance in the first place. I had set the env variable CATALINA_CONNECTOR_SCHEME to http. Changing it to https has solved the problem


text:
Q: Object created in Python via Pybind11 not recognized as a derived class by C++ functions The minimum code to reproduce the issue is as follows:
aaa.hpp
#include <string>
#include <vector>
#include <iostream>
#include <stdexcept>
#include <cmath>
#include <cassert>
#include <utility>

template <typename D>
class BaseClass{
    /* The base class. */
protected:
    bool skip_nan = true;
};

template <typename D>
class DerivedClass : public BaseClass<D>{
public:
    explicit DerivedClass(bool skip_nan_){ this->skip_nan = skip_nan_; }
};

aaa_py.cpp
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include "aaa.hpp"
namespace py = pybind11;

template <typename D>
void fff(BaseClass<D>& rs){

}

PYBIND11_MODULE(aaa_py, m) {
    m.def("fff_float", &fff<float>);
    py::class_<DerivedClass<float>>(m, "DerivedClass_float").def(py::init<bool>(), py::arg("skip_nan")=true);
}

test.py
import aaa_py as rsp
ds = rsp.DerivedClass_float()
rsp.fff_float(ds)

Error:
Traceback (most recent call last):
  File "usage_example_python.py", line 8, in <module>
    rsp.fff_float(ds)
TypeError: fff_float(): incompatible function arguments. The following argument types are supported:
    1. (arg0: BaseClass<float>) -> None

Invoked with: <aaa_py.DerivedClass_float object at 0x000002C9EAF57308>

Basically the error is saying that function fff_float expects somebody from BaseClass<float>, but receives DerivedClass<float>. If I change the function to accept DerivedClass<D>&, then there would be no errors. Or, if I create an instantiation of DerivedClass<float> directly in c++ and pass it to the float_fff, there would also be no issues. So it seems that the issue is that for an object created in Python, somehow the information about its base class is lost. How can I deal with this?

A: You need to declare BaseClass<float> in Python and tell pybind11 that DerivedClass_float extends it.
PYBIND11_MODULE(MyModule, m)
{
    m.def("fff_float", &fff<float>);

    // declare base class - this simply expose to Python, it's impossible to
    // construct a BaseClass_float in Python since no constructor is provided
    py::class_<BaseClass<float>>(m, "BaseClass_float");

    // tell pybind11 that DerivedClass<float> extends BaseClass<float>
    py::class_<DerivedClass<float>, BaseClass<float>>(m, "DerivedClass_float")
    //                              ^^^^^^^^^^^^^^^^
        .def(py::init<bool>(), py::arg("skip_nan") = true);
}


text:
Q: flask error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand To create a sign up page, I ask to the user his informations (name, surname, email, password), then I put this info on my database, but it always save as NULL. (I use DB browser). I search a lot to solve this, I tried all I found, but nothing solved this.
This is my HTML script:

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

                    Login

Sign up

              <form method="post" class="m-5">

                  <input type="text" class="form-control" id="floatingInput1" placeholder="Name"
                         required="required" value="{{ request.form['name'] }}">
                  Name

                  <input type="text" class="form-control" id="floatingInput2" placeholder="Surname"
                         required="required" value="{{ request.form['surname'] }}">
                  Surname

                  <input type="email" class="form-control" id="floatingInput3" placeholder="name@example.com"
                  required="required" value="{{ request.form['email'] }}">
                  Email

                  <input type="password" class="form-control" id="floatingPassword" placeholder="Password"
                  required="required" value="{{ request.form['password'] }}">
                  Password

                  <input class="form-check-input" type="checkbox" value="" id="rememberPasswordCheck">

                    Remember password

                  <button class="btn btn-primary btn-login text-uppercase fw-bold" type="submit">Registrati</button>

              </form>

And this is the python script:
import sqlite3

from flask import Flask, render_template, request, redirect

app = Flask(__name__)

def connect_db():
    connection = sqlite3.connect('users.db')
    connection.row_factory = sqlite3.Row
    return connection

@app.route('/')
def index():
    connection = connect_db()
    posts = connection.execute('SELECT * FROM posts').fetchall()
    connection.close()
    return render_template('index.html', posts=posts)

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/signup', methods=('GET','POST'))
def signup():
    if request.method == 'POST':
        name = request.form['name']
        surname = request.form['surname']
        email = request.form['email']
        password = request.form['password']
        connection = connect_db()
        connection.execute(
            'INSERT INTO posts (name, surname, email, password) VALUES (?,?,?,?)',
            (name, surname, email, password)
        )
        connection.commit()
        connection.close()
        return redirect('/')
    return render_template('signup.html')

if __name__ == "__main__":
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)

This is the screenshot of the error:
flask error
and this is the screenshot of the database:
database result

A: You're not setting the id on your form inputs to match the keys for
request.form, it's a dict and it's keys are made up of the id's from the html inputs. You've used the id floatingInput1 for the name input in your html, so when you try access your form data with request.form['name'] you're getting the BadKey error.
So either change the line for getting your data to request.form.get('floatingInput1') or change your html inputs to use <input type="text" id="name" name="name">


text:
Q: How does a thermoelectric generator generates electricity? I want to know how a thermoelectric generator generates electricity. I know that it converts 'heat flow' to electricity.But some people say it consumes heat and converts it into electricity.The rest of the heat is dissipated  through the other side. Which is true?

A: It converts some (a small fraction) of the heat flow to electricity. It absorbs X amount of heat from the hot side, and rejects X-delta amount to the cold side. The output voltage is related to the temperature difference between the hot and cold sides. The output current is related to delta, the heat flow difference.
Because present devices are very inefficient, without taking very careful measurements, measurements that are beyond most hobbyists to do accurately, it would be easy to conclude that it doesn't consume any heat at all. X-delta is very similar in magnitude to X. A small difference between two big measurements has been the bane of experimenters since antiquity!
So people that say 'it converts heat flow to electricity', or 'it converts heat to electricity', are both correct, up to a hand-wavy approximation. It needs both.

A: It takes a part of the heat flow and generates electricity from it.
However, there must be a heat flow; otherwise you'd have a perpetual motion machine of the second kind, and that is impossible.

A: This seems to really be a physics question about heat engines.  Anything that converts energy from a heat difference into some other form is a heat engine.  In this case, you are apparently asking about one of the ways of converting a heat difference into a electric potential directly.  What the output is (electric power, rotating shaft, etc) makes no difference.  When the input is a heat difference, you have a heat engine.
Heat engines are limited by the Carnot efficiency:
  Efficiency = (Thot - Tcold)/Thot
The temperatures must be in a linear absolute scale, like degrees Kelvin.
For example, to extract power from reservoirs of boiling water (373°K) and ice water (273°K), the best you can ever do is 27% efficiency.  This means that if you were to extract 10 W from this setup with a theoretical perfect heat engine, there would actually be 37 W of heat flowing from the hot reservoir to the cold reservoir.
This basic physics applies to heat engines with electric output too, like thermocouples and thermionic generators.  The main difference is that real heat engines won't achieve 100% of the possible Carnot efficiency.  In a thermistor, for example, there is significant heat flow along each wire that is not converted to a electric potential.  The heat gradient along the wire produces the electric potential, but also provides a heat leakage path.